/MarkDownSharpEditor/Form1.cs
C# | 3551 lines | 2262 code | 325 blank | 964 comment | 525 complexity | c88aa535553c02d781cd86a947e9b9dd MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Collections;
- using System.Security.Cryptography;
- using System.Text.RegularExpressions;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Windows.Documents;
- using MarkDownSharpEditor.Properties;
- using mshtml;
- namespace MarkDownSharpEditor
- {
- public partial class Form1 : Form
- {
- //-----------------------------------
- // WebBrowserコンポーネントプレビューの更新音(クリック音)をOFFにする
- // Click sound off when webBrowser component preview
- const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
- const int SET_FEATURE_ON_PROCESS = 0x00000002;
- [DllImport("urlmon.dll")]
- [PreserveSig]
- [return: MarshalAs(UnmanagedType.Error)]
- static extern int CoInternetSetFeatureEnabled(int FeatureEntry, [MarshalAs(UnmanagedType.U4)] int dwFlags, bool fEnable);
- //-----------------------------------
- int undoCounter = 0; // Undo buffer counter
- List<string> UndoBuffer = new List<string>();
- private bool _fSearchStart = false; //検索を開始したか ( Start search flag )
- private int _richEditBoxInternalHeight; //richTextBox1の内部的な高さ ( internal height of richTextBox1 component )
- private int _WebBrowserInternalHeight; //webBrowser1の内部的な高さ(body)( internal height of webBrowser1 component )
- private Point _preFormPos; //フォームサイズ変更前の位置を一時保存 ( Temporary form position before resizing form )
- private Size _preFormSize; //フォームサイズ変更前のサイズを一時保存 ( Temporay form size before resizing form )
- private bool _fNoTitle = true; //無題のまま編集中かどうか ( no name of file flag )
- private string _MarkDownTextFilePath = ""; //編集中のMDファイルパス ( Editing .MD file path )
- private string _TemporaryHtmlFilePath = ""; //プレビュー用のテンポラリHTMLファイルパス ( Temporary HTML file path for preview )
- private string _SelectedCssFilePath = ""; //選択中のCSSファイルパス ( Applying CSS file path )
- private Encoding _EditingFileEncoding = Encoding.UTF8; //編集中MDファイルの文字エンコーディング ( Character encoding of MD file editing )
- private bool _fConstraintChange = true; //更新状態の抑制 ( Constraint changing flag )
- private List<MarkdownSyntaxKeyword> _MarkdownSyntaxKeywordAarray = new List<MarkdownSyntaxKeyword>(); // Array of MarkdownSyntaxKeyword Class
- private ArrayList _SyntaxArrayList = new ArrayList();
- //-----------------------------------
- // コンストラクタ ( Constructor )
- //-----------------------------------
- public Form1()
- {
- InitializeComponent();
- //IME Handler On/Off
- if (MarkDownSharpEditor.AppSettings.Instance.Lang == "ja")
- {
- richTextBox1.IMEWorkaroundEnabled = true;
- }
- else
- {
- richTextBox1.IMEWorkaroundEnabled = false;
- }
- this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragEnter);
- this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop);
- richTextBox1.AllowDrop = true;
- //設定を読み込む ( Read options )
- //Program.csで読み込むようにした ( Load in "Program.cs" )
- //MarkDownSharpEditor.AppSettings.Instance.ReadFromXMLFile();
- //WebBrowserClickSoundOFF();
- CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS, SET_FEATURE_ON_PROCESS, true);
- }
- //----------------------------------------------------------------------
- // フォームをロード ( Load main form )
- //----------------------------------------------------------------------
- private void Form1_Load(object sender, EventArgs e)
- {
- var obj = MarkDownSharpEditor.AppSettings.Instance;
- //-----------------------------------
- //フォーム位置・サイズ ( Form position & size )
- //-----------------------------------
- this.Location = obj.FormPos;
- this.Size = obj.FormSize;
- this.richTextBox1.Width = obj.richEditWidth;
- //ウィンドウ位置の調整(へんなところに行かないように戻す)
- // Ajust window position ( Set position into Desktop range )
- if (this.Left < 0 || this.Left > Screen.PrimaryScreen.Bounds.Width)
- {
- this.Left = 0;
- }
- if (this.Top < 0 || this.Top > Screen.PrimaryScreen.Bounds.Height)
- {
- this.Top = 0;
- }
- if (obj.FormState == 1)
- { //最小化 ( Minimize )
- this.WindowState = FormWindowState.Minimized;
- }
- else if (obj.FormState == 2)
- { //最大化 ( Maximize )
- this.WindowState = FormWindowState.Maximized;
- }
- //メインメニュー表示
- //View main menu
- this.menuViewToolBar.Checked = obj.fViewToolBar;
- this.toolStrip1.Visible = obj.fViewToolBar;
- this.menuViewStatusBar.Checked = obj.fViewStatusBar;
- this.statusStrip1.Visible = obj.fViewStatusBar;
- this.menuViewWidthEvenly.Checked = obj.fSplitBarWidthEvenly;
- //言語 ( Language )
- if (obj.Lang == "ja")
- {
- menuViewJapanese.Checked = true;
- menuViewEnglish.Checked = false;
- }
- else
- {
- menuViewJapanese.Checked = false;
- menuViewEnglish.Checked = true;
- }
- //ブラウザープレビューまでの間隔
- //Interval time of browser preview
- if (obj.AutoBrowserPreviewInterval > 0)
- {
- timer1.Interval = obj.AutoBrowserPreviewInterval;
- }
- //-----------------------------------
- //RichEditBox font
- FontConverter fc = new FontConverter();
- try { richTextBox1.Font = (Font)fc.ConvertFromString(obj.FontFormat); }
- catch { }
- //RichEditBox font color
- richTextBox1.ForeColor = Color.FromArgb(obj.richEditForeColor);
- //ステータスバーに表示
- //View in statusbar
- toolStripStatusLabelFontInfo.Text =
- richTextBox1.Font.Name + "," + richTextBox1.Font.Size.ToString() + "pt";
- //エディターのシンタックスハイライター設定の反映
- //Syntax highlighter of editor window is enabled
- _MarkdownSyntaxKeywordAarray = MarkdownSyntaxKeyword.CreateKeywordList();
- //-----------------------------------
- //選択中のエンコーディングを表示
- //View selected character encoding name
- foreach (EncodingInfo ei in Encoding.GetEncodings())
- {
- if (ei.GetEncoding().IsBrowserDisplay == true)
- {
- if (ei.CodePage == obj.CodePageNumber)
- {
- toolStripStatusLabelHtmlEncoding.Text = ei.DisplayName;
- break;
- }
- }
- }
- //-----------------------------------
- //指定されたCSSファイル名を表示
- //View selected CSS file name
- toolStripStatusLabelCssFileName.Text = Resources.toolTipCssFileName; //"CSSファイル指定なし"; ( No CSS file )
- if (obj.ArrayCssFileList.Count > 0)
- {
- string FilePath = (string)obj.ArrayCssFileList[0];
- if (File.Exists(FilePath) == true)
- {
- toolStripStatusLabelCssFileName.Text = Path.GetFileName(FilePath);
- _SelectedCssFilePath = FilePath;
- }
- }
- //-----------------------------------
- //出力するHTMLエンコーディング表示
- //View HTML charcter encoding name for output
- if (obj.HtmlEncodingOption == 0)
- {
- // 編集中(RichEditBox側)のエンコーディング
- // 基本的にはテキストファイルが読み込まれたときに表示する
- // View encoding name of editor window
- toolStripStatusLabelHtmlEncoding.Text = _EditingFileEncoding.EncodingName;
- }
- else
- {
- //エンコーディングを指定する(&C)
- //Select encoding
- Encoding enc = Encoding.GetEncoding(obj.CodePageNumber);
- toolStripStatusLabelHtmlEncoding.Text = enc.EncodingName;
- }
- //-----------------------------------
- //検索フォーム・オプション
- //Search form options
- chkOptionCase.Checked = obj.fSearchOptionIgnoreCase ? false : true;
- }
- //----------------------------------------------------------------------
- // フォームを表示
- // View Main form
- //----------------------------------------------------------------------
- private void Form1_Shown(object sender, EventArgs e)
- {
- string DirPath = MarkDownSharpEditor.AppSettings.GetAppDataLocalPath();
- ArrayList FileArray = new ArrayList();
- //TODO: 「新しいウィンドウで開く」="/new"などの引数も含まれるので、
- // その辺りの処理も将来的に入れる。
- //コマンドラインでファイルが投げ込まれてきている
- //Launch with arguments
- string[] cmds = System.Environment.GetCommandLineArgs();
- for (int i = 1; i < cmds.Count(); i++)
- {
- if (File.Exists(cmds[i]) == true)
- {
- FileArray.Add(cmds[i]);
- }
- }
- try
- {
- if (FileArray.Count > 1)
- { //"問い合わせ"
- //"複数のファイルが読み込まれました。\n現在の設定内容でHTMLファイルへの一括変換を行いますか?
- //「いいえ」を選択するとそのまますべてのファイル開きます。"
- //"Question"
- //"More than one were read.\nDo you wish to convert all files to HTML files on this options?\n
- // if you select 'No', all files will be opend without converting."
- DialogResult ret = MessageBox.Show(Resources.MsgConvertAllFilesToHTML,
- Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
- if (ret == DialogResult.Yes)
- { //一括でHTMLファイル出力
- //Output HTML files in batch process
- BatchOutputToHtmlFiles((String[])FileArray.ToArray(typeof(string)));
- return;
- }
- else if (ret == DialogResult.Cancel)
- { //キャンセル
- //Cancel
- return;
- }
- else
- { //「いいえ」
- // "NO" button
- bool fOpen = false;
- foreach (string FilePath in FileArray)
- { //最初のファイルだけ、このウィンドウだけ開く
- //First file open in this window
- if (fOpen == false)
- {
- richTextBox1.Modified = false;
- OpenFile(FilePath);
- fOpen = true;
- }
- else
- { //他の複数ファイルは順次新しいウィンドウで開く
- //Other files open in new windows
- System.Diagnostics.Process.Start(
- Application.ExecutablePath, string.Format("{0}", FilePath));
- }
- }
- }
- }
- else if (FileArray.Count == 1)
- {
- richTextBox1.Modified = false;
- OpenFile((string)FileArray[0]);
- }
- else
- { //前に編集していたファイルがあればそれを開く
- //Open it if there is editing file before
- if (MarkDownSharpEditor.AppSettings.Instance.fOpenEditFileBefore == true)
- {
- if (MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Count > 0)
- {
- AppHistory EditedFilePath = new AppHistory();
- EditedFilePath = (AppHistory)MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles[0];
- if (File.Exists(EditedFilePath.md) == true)
- {
- _TemporaryHtmlFilePath = "";
- richTextBox1.Modified = false;
- OpenFile(EditedFilePath.md);
- return;
- }
- }
- }
- if (_MarkDownTextFilePath == "")
- { //無ければ「無題」ファイル
- // "No title" if no file exists
- richTextBox1.Modified = false;
- OpenFile("");
- }
- }
- }
- finally
- {
- _fConstraintChange = false;
- //SyntaxHighlighter
- if (backgroundWorker2.IsBusy == false)
- {
- //backgroundWorker2.WorkerReportsProgress = true;
- backgroundWorker2.RunWorkerAsync(richTextBox1.Text);
- }
- richTextBox1.Modified = false;
- //フォームタイトル更新 / Refresh form caption
- FormTextChange();
- }
- }
- //----------------------------------------------------------------------
- // フォームタイトルの表示(更新)
- // Refresh form caption
- //----------------------------------------------------------------------
- private void FormTextChange()
- {
- string FileName;
- if (_fNoTitle == true)
- {
- FileName = Resources.NoFileName; //"(無題)" "(No title)"
- }
- else
- {
- //FileName = System.IO.Path.GetFileName(_MarkDownTextFilePath);
- FileName = _MarkDownTextFilePath;
- }
- if (richTextBox1.Modified == true)
- {
- FileName = FileName + Resources.FlagChanged; //"(更新)"; "(Changed)"
- }
- this.Text = FileName + " - " + Application.ProductName;
- }
- //----------------------------------------------------------------------
- // 見出しリストメニューの表示
- //----------------------------------------------------------------------
- private void mnuShowHeaderListMenu_Click(object sender, EventArgs e)
- {
- ShowHeaderListContextMenu();
- }
- //----------------------------------------------------------------------
- // 見出しリストメニューの表示
- //----------------------------------------------------------------------
- void ShowHeaderListContextMenu()
- {
- int retCode;
- //Markdown
- object[][] mkObject = {
- new object[2] { 1, @"^#[^#]*?$" }, //見出し1 (headline1)
- new object[2] { 1, @"^.*\n=+$" }, //見出し1 (headline1)
- new object[2] { 2, @"^##[^#]*?$" }, //見出し2 (headline2)
- new object[2] { 2, @"^.+\n-+$" }, //見出し2 (headline2)
- new object[2] { 3, @"^###[^#]*?$" }, //見出し3 (headline3)
- new object[2] { 4, @"^####[^#]*?$" }, //見出し4 (headline4)
- new object[2] { 5, @"^#####[^#]*?$" }, //見出し5 (headline5)
- new object[2] { 6, @"^######[^#]*?$"} //見出し6 (headline6)
- };
- //コンテキストメニュー項目を初期化(クリア)
- //Clear context menus
- contextMenu2.Items.Clear();
- bool fModify = richTextBox1.Modified;
- _fConstraintChange = true;
- //現在のカーソル位置
- //Current cursor position
- int selectStart = this.richTextBox1.SelectionStart;
- int selectEnd = richTextBox1.SelectionLength;
- Point CurrentOffset = richTextBox1.AutoScrollOffset;
- //現在のスクロール位置
- //Current scroll position
- int CurrentScrollPos = richTextBox1.VerticalPosition;
- //描画停止
- //Stop to update
- richTextBox1.BeginUpdate();
- for (int i = 0; i < mkObject.Length; i++)
- {
- Regex r = new Regex((string)mkObject[i][1], RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
- MatchCollection col = r.Matches(richTextBox1.Text, 0);
- if (col.Count > 0)
- {
- foreach (Match m in col)
- {
- int IndexNum = m.Groups[0].Index;
- string title = new String(' ', (int)mkObject[i][0]) + richTextBox1.Text.Substring(m.Groups[0].Index, m.Groups[0].Length);
- if ((retCode = title.LastIndexOf("\n")) > -1)
- {
- title = title.Substring(0, title.LastIndexOf("\n"));
- }
- //コンテキストメニューに登録
- //Regist item to context menus
- bool fAdd = false;
- ToolStripMenuItem item = new ToolStripMenuItem();
- for (int c = 0; c < contextMenu2.Items.Count; c++)
- {
- //登録されている項目よりも前の項目のときは挿入する
- //Insert item to registed items
- if (IndexNum < (int)contextMenu2.Items[c].Tag)
- {
- item.Text = title;
- item.Tag = IndexNum;
- contextMenu2.Items.Insert(c, item);
- fAdd = true;
- break;
- }
- }
- if (fAdd == false)
- {
- item.Text = title;
- item.Tag = IndexNum;
- contextMenu2.Items.Add(item);
- }
- }
- }
- }
- //カーソル位置を戻す
- //Restore cursor position
- richTextBox1.Select(selectStart, selectEnd);
- richTextBox1.AutoScrollOffset = CurrentOffset;
- //描画再開
- //Resume to update
- richTextBox1.EndUpdate();
- richTextBox1.Modified = fModify;
- _fConstraintChange = false;
- //richTextBox1のキャレット位置
- //Curret position in richTextBox1
- Point pt = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
- //スクリーン座標に変換
- //Convert the position to screen position
- pt = richTextBox1.PointToScreen(pt);
- //コンテキストメニューを表示
- //View context menus
- contextMenu2.Show(pt);
- }
- //----------------------------------------------------------------------
- // 見出しメニュークリックイベント
- // Click event in context menus
- //----------------------------------------------------------------------
- private void contextMenu2_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
- {
- if ((int)e.ClickedItem.Tag > 0)
- {
- richTextBox1.SelectionStart = (int)e.ClickedItem.Tag;
- richTextBox1.ScrollToCaret();
- }
- }
- //----------------------------------------------------------------------
- // HACK: RichTextBox内容変更 [ シンタックス・ハイライター表示)]
- // Apply richTextBox1 to syntax highlight with changing
- //----------------------------------------------------------------------
- private void richTextBox1_TextChanged(object sender, EventArgs e)
- {
- if (_fConstraintChange == true)
- {
- return;
- }
- if (backgroundWorker2.IsBusy == false)
- {
- //バックグラウンドワーカーへパースを投げる / SyntaxHightlighter on BackgroundWorker
- backgroundWorker2.RunWorkerAsync(richTextBox1.Text);
- }
- //-----------------------------------
- //Formキャプション変更 / Change form caption
- FormTextChange();
- //-----------------------------------
- //ブラウザプレビュー制御 / Preview webBrowser component
- if (MarkDownSharpEditor.AppSettings.Instance.fAutoBrowserPreview == true)
- {
- timer1.Enabled = true;
- }
- }
- //----------------------------------------------------------------------
- // RichTextBox Key Press
- //----------------------------------------------------------------------
- private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
- {
- //-----------------------------------
- // Add undo buffer
- //-----------------------------------
- //現在のUndoCounterから先を削除
- //Remove first item of undo counter
- if (undoCounter < UndoBuffer.Count)
- {
- UndoBuffer.RemoveRange(undoCounter, UndoBuffer.Count - undoCounter);
- }
- UndoBuffer.Add(richTextBox1.Rtf);
- undoCounter = UndoBuffer.Count;
- //EnterやEscapeキーでビープ音が鳴らないようにする
- //Stop to beep in Enter & Escape key
- if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Escape)
- {
- e.Handled = true;
- }
- timer2.Enabled = true;
- }
-
- //----------------------------------------------------------------------
- // RichTextBox VScroll event
- //----------------------------------------------------------------------
- private void richTextBox1_VScroll(object sender, EventArgs e)
- {
- if (_fConstraintChange == false)
- {
- WebBrowserMoveCursor();
- }
- }
- //----------------------------------------------------------------------
- // RichTextBox Enter event
- //----------------------------------------------------------------------
- private void richTextBox1_Enter(object sender, EventArgs e)
- {
- //ブラウザプレビュー制御 / Preview webBrowser component
- if (MarkDownSharpEditor.AppSettings.Instance.fAutoBrowserPreview == true)
- {
- timer1.Enabled = true;
- }
- }
- //----------------------------------------------------------------------
- // RichTextBox Mouse click
- //----------------------------------------------------------------------
- private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
- {
- //timer1.Enabled = true;
- }
- //----------------------------------------------------------------------
- // Form Closing event
- //----------------------------------------------------------------------
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- if (richTextBox1.Modified == true)
- {
- //"問い合わせ"
- //"編集中のファイルがあります。保存してから終了しますか?"
- //"Question"
- //"This file being edited. Do you wish to save before exiting?"
- DialogResult ret = MessageBox.Show(Resources.MsgSaveFileToEnd,
- Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
- if (ret == DialogResult.Yes)
- {
- if (SaveToEditingFile() == true)
- {
- _fNoTitle = false;
- }
- else
- {
- //キャンセルで抜けてきた
- //user cancel
- e.Cancel = true;
- return;
- }
- }
- else if (ret == DialogResult.Cancel)
- {
- e.Cancel = true;
- return;
- }
- }
- _fConstraintChange = true;
- //無題ファイルのまま編集しているのなら削除
- //Delete file if the file is no title
- if (_fNoTitle == true)
- {
- if (File.Exists(_MarkDownTextFilePath) == true)
- {
- try
- {
- File.Delete(_MarkDownTextFilePath);
- }
- catch
- {
- }
- }
- }
- //データバージョン
- //Data version
- System.Reflection.Assembly asmbly = System.Reflection.Assembly.GetExecutingAssembly();
- System.Version ver = asmbly.GetName().Version;
- MarkDownSharpEditor.AppSettings.Instance.Version = ver.Major * 1000 + ver.Minor * 100 + ver.Build * 10 + ver.Revision;
- //フォーム位置・サイズ ( Form position & size )
- if (this.WindowState == FormWindowState.Minimized)
- { //最小化 ( Minimize )
- MarkDownSharpEditor.AppSettings.Instance.FormState = 1;
- //一時記憶していた位置・サイズを保存 ( Save temporary position & size value )
- MarkDownSharpEditor.AppSettings.Instance.FormPos = new Point(_preFormPos.X, _preFormPos.Y);
- MarkDownSharpEditor.AppSettings.Instance.FormSize = new Size(_preFormSize.Width, _preFormSize.Height);
- }
- else if (this.WindowState == FormWindowState.Maximized)
- { //最大化 ( Maximize )
- MarkDownSharpEditor.AppSettings.Instance.FormState = 2;
- //一時記憶していた位置・サイズを保存 ( Save temporary position & size value )
- MarkDownSharpEditor.AppSettings.Instance.FormPos = new Point(_preFormPos.X, _preFormPos.Y);
- MarkDownSharpEditor.AppSettings.Instance.FormSize = new Size(_preFormSize.Width, _preFormSize.Height);
- }
- else
- { //通常 ( Normal window )
- MarkDownSharpEditor.AppSettings.Instance.FormState = 0;
- MarkDownSharpEditor.AppSettings.Instance.FormPos = new Point(this.Left, this.Top);
- MarkDownSharpEditor.AppSettings.Instance.FormSize = new Size(this.Width, this.Height);
- }
- MarkDownSharpEditor.AppSettings.Instance.richEditWidth = this.richTextBox1.Width;
- FontConverter fc = new FontConverter();
- MarkDownSharpEditor.AppSettings.Instance.FontFormat = fc.ConvertToString(richTextBox1.Font);
- MarkDownSharpEditor.AppSettings.Instance.richEditForeColor = richTextBox1.ForeColor.ToArgb();
- //表示オプションなど
- //Save view options etc
- MarkDownSharpEditor.AppSettings.Instance.fViewToolBar = this.menuViewToolBar.Checked;
- MarkDownSharpEditor.AppSettings.Instance.fViewStatusBar = this.menuViewStatusBar.Checked;
- MarkDownSharpEditor.AppSettings.Instance.fSplitBarWidthEvenly = this.menuViewWidthEvenly.Checked;
- //検索オプション
- //Save search options
- MarkDownSharpEditor.AppSettings.Instance.fSearchOptionIgnoreCase = chkOptionCase.Checked ? false : true;
- if (File.Exists(_MarkDownTextFilePath) == true)
- {
- //編集中のファイルパス
- //Save editing file path
- foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
- {
- if (data.md == _MarkDownTextFilePath)
- { //いったん削除して ( delete once ... )
- MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Remove(data);
- break;
- }
- }
- AppHistory HistroyData = new AppHistory();
- HistroyData.md = _MarkDownTextFilePath;
- HistroyData.css = _SelectedCssFilePath;
- MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Insert(0, HistroyData); //先頭に挿入 ( Insert at the top )
- }
- //設定の保存
- //Save settings
- MarkDownSharpEditor.AppSettings.Instance.SaveToXMLFile();
- //MarkDownSharpEditor.AppSettings.Instance.SaveToJsonFile();
- timer1.Enabled = false;
- //webBrowser1.Navigate("about:blank");
- //クリック音対策
- //Constraint click sounds
- if (webBrowser1.Document != null)
- {
- webBrowser1.Document.OpenNew(true);
- webBrowser1.Document.Write("");
- }
- }
- //-----------------------------------
- // Form closed event
- //-----------------------------------
- private void Form1_FormClosed(object sender, FormClosedEventArgs e)
- {
- //テンポラリファイルの削除
- //Delete temporary files
- Delete_TemporaryHtmlFilePath();
- }
- //-----------------------------------
- // Form resize begin event
- //-----------------------------------
- private void Form1_ResizeBegin(object sender, EventArgs e)
- {
- //リサイズ前の位置・サイズを一時記憶
- _preFormPos.X = this.Left;
- _preFormPos.Y = this.Top;
- _preFormSize.Width = this.Width;
- _preFormSize.Height = this.Height;
- }
- //-----------------------------------
- // Form resize end event
- //-----------------------------------
- private void Form1_ResizeEnd(object sender, EventArgs e)
- {
- //ソースウィンドウとビューウィンドウを均等にするか
- //Equalize width of source window and view window
- if (menuViewWidthEvenly.Checked == true)
- {
- this.richTextBox1.Width =
- (splitContainer1.Width - splitContainer1.SplitterWidth) / 2;
- }
- }
- //-----------------------------------
- // richTextBox1 DragEnter event
- //-----------------------------------
- private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
- {
- if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
- {
- e.Effect = DragDropEffects.Copy;
- }
- else
- {
- e.Effect = DragDropEffects.None;
- }
- }
- //-----------------------------------
- // richTextBox1 Drag and Drop event
- //-----------------------------------
- private void richTextBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
- {
- string[] FileArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
- if (FileArray.Length > 1)
- {
- if (FileArray.Length > 0)
- {
- //"問い合わせ"
- //"複数のファイルが読み込まれました。\n現在の設定内容でHTMLファイルへの一括変換を行いますか?
- //「いいえ」を選択するとそのまますべてのファイル開きます。"
- //"Question"
- //"More than one were read.\nDo you wish to convert all files to HTML files on this options?\n
- // if you select 'No', all files will be opend without converting."
- DialogResult ret = MessageBox.Show("MsgConvertAllFilesToHTML",
- Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
- if (ret == DialogResult.Yes)
- {
- //一括でHTMLファイル出力
- //Output HTML files in batch process
- BatchOutputToHtmlFiles(FileArray);
- return;
- }
- else if (ret == DialogResult.Cancel)
- {
- //キャンセル
- //Cancel
- return;
- }
- else
- { //「いいえ」
- // "No" button
- bool fOpen = false;
- foreach (string FilePath in FileArray)
- {
- //最初のファイルだけ、このウィンドウだけ開く
- //First file open in this window
- if (fOpen == false)
- {
- OpenFile(FilePath);
- fOpen = true;
- }
- else
- {
- //他の複数ファイルは順次新しいウィンドウで開く
- //Other files open in new windows
- System.Diagnostics.Process.Start(
- Application.ExecutablePath, string.Format("{0}", FilePath));
- }
- }
- }
- }
- else
- {
- //前に編集していたファイルがあればそれを開く
- //Open it if there is editing file before
- if (MarkDownSharpEditor.AppSettings.Instance.fOpenEditFileBefore == true)
- {
- if (MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Count > 0)
- {
- AppHistory EditedFilePath = new AppHistory();
- EditedFilePath = (AppHistory)MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles[0];
- if (File.Exists(EditedFilePath.md) == true)
- {
- OpenFile(EditedFilePath.md);
- }
- }
- }
- }
- _fConstraintChange = false;
- //フォームタイトル更新
- //Refresh form caption
- FormTextChange();
- ArrayList ArrayFileList = new ArrayList();
- foreach (string FilePath in FileArray)
- {
- ArrayFileList.Add(FilePath);
- }
- BatchOutputToHtmlFiles((String[])ArrayFileList.ToArray(typeof(string)));
- }
- else if (FileArray.Count() == 1)
- {
- //ファイルが一個の場合は編集中のウィンドウで開く
- //Open it in this window if file is one
- OpenFile(FileArray[0]);
- }
- }
- //----------------------------------------------------------------------
- // OpenFile [ .mdファイルを開く ]
- //----------------------------------------------------------------------
- private bool OpenFile(string FilePath, bool fOpenDialog = false)
- {
- //引数 FilePath = "" の場合は「無題」編集で開始する
- // Argument "FilePath" = "" => Start editing in 'no title'
- if (FilePath == "")
- {
- _fNoTitle = true; // No title flag
- }
- else
- {
- _fNoTitle = false;
- }
- //-----------------------------------
- //編集中のファイルがある
- if (richTextBox1.Modified == true)
- {
- //"問い合わせ"
- //"編集中のファイルがあります。保存してから終了しますか?"
- //"Question"
- //"This file being edited. Do you wish to save before exiting?"
- DialogResult ret = MessageBox.Show(Resources.MsgSaveFileToEnd,
- Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
- if (ret == DialogResult.Yes)
- {
- if (SaveToEditingFile() == false)
- {
- //キャンセルで抜けてきた
- //Cancel
- return (false);
- }
- }
- else if (ret == DialogResult.Cancel)
- {
- return (false);
- }
- //編集履歴に残す
- //Save file path to editing history
- foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
- {
- if (data.md == _MarkDownTextFilePath)
- { //いったん削除して ( delete once ... )
- MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Remove(data);
- break;
- }
- }
- AppHistory HistroyData = new AppHistory();
- HistroyData.md = _MarkDownTextFilePath;
- HistroyData.css = _SelectedCssFilePath;
- MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Insert(0, HistroyData); //先頭に挿入 ( Insert at the top )
- }
- //-----------------------------------
- //オープンダイアログ表示
- //View open file dialog
- if (fOpenDialog == true)
- {
- if (File.Exists(_MarkDownTextFilePath) == true)
- { //編集中のファイルがあればそのディレクトリを初期フォルダーに
- //Set parent directory of editing file to initial folder
- openFileDialog1.InitialDirectory = Path.GetDirectoryName(_MarkDownTextFilePath);
- //テンポラリファイルがあればここで削除
- //Delete it if temporary file exists
- Delete_TemporaryHtmlFilePath();
- }
- openFileDialog1.FileName = "";
- if (openFileDialog1.ShowDialog() == DialogResult.OK)
- {
- FilePath = openFileDialog1.FileName;
- _fNoTitle = false;
- }
- else
- {
- return (false);
- }
- }
- //編集中のファイルパスとする
- //Set this file to 'editing file' path
- _MarkDownTextFilePath = FilePath;
- //-----------------------------------
- //文字コードを調査するためにテキストファイルを開く
- //Detect encoding
- if (_fNoTitle == false)
- {
- byte[] bs;
- using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
- {
- bs = new byte[fs.Length];
- fs.Read(bs, 0, bs.Length);
- }
- //文字コードを取得する
- //Get charcter encoding
- _EditingFileEncoding = GetCode(bs);
- }
- else
- {
- //「無題」はデフォルトのエンコーディング
- // Set this file to default encoding in 'No title'
- _EditingFileEncoding = Encoding.UTF8;
- }
- //ステータスバーに表示
- //View in statusbar
- toolStripStatusLabelTextEncoding.Text = _EditingFileEncoding.EncodingName;
- //編集中のエンコーディングを使用する(&D)か
- //Use encoding of editing file
- if (MarkDownSharpEditor.AppSettings.Instance.HtmlEncodingOption == 0)
- {
- toolStripStatusLabelHtmlEncoding.Text = _EditingFileEncoding.EncodingName;
- }
- //-----------------------------------
- //ペアとなるCSSファイルがあるか探索してあれば適用する
- //Apply that the pair CSS file to this file exists
- foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
- {
- if (data.md == _MarkDownTextFilePath)
- {
- if (File.Exists(data.css) == true)
- {
- _SelectedCssFilePath = data.css;
- break;
- }
- }
- }
- //選択中のCSSファイル名をステータスバーに表示
- //View selected CSS file name to stausbar
- if (File.Exists(_SelectedCssFilePath) == true)
- {
- toolStripStatusLabelCssFileName.Text = Path.GetFileName(_SelectedCssFilePath);
- }
- else
- {
- toolStripStatusLabelCssFileName.Text = Resources.toolTipCssFileName; //"CSSファイル指定なし"; ( not selected CSS file)
- }
- _fConstraintChange = true;
- richTextBox1.Clear();
- //RichEditBoxの「フォント」設定
- // richTextBox1 font name setting
- var obj = MarkDownSharpEditor.AppSettings.Instance;
- FontConverter fc = new FontConverter();
- try { richTextBox1.Font = (Font)fc.ConvertFromString(obj.FontFormat); }
- catch { }
- //RichEditBoxの「フォントカラー」設定
- // richTextBox1 font color setting
- richTextBox1.ForeColor = Color.FromArgb(obj.richEditForeColor);
- //View them in statusbar
- toolStripStatusLabelFontInfo.Text = richTextBox1.Font.Name + "," + richTextBox1.Font.Size.ToString() + "pt";
- //-----------------------------------
- //テキストファイルの読み込み
- //Read text file
- if (File.Exists(FilePath) == true)
- {
- richTextBox1.Text = File.ReadAllText(FilePath, _EditingFileEncoding);
- }
- richTextBox1.BeginUpdate();
- richTextBox1.SelectionStart = richTextBox1.Text.Length;
- richTextBox1.ScrollToCaret();
- //richTextBox1の全高さを求める
- //Get height of richTextBox1 ( for webBrowser sync )
- _richEditBoxInternalHeight = richTextBox1.VerticalPosition;
- //カーソル位置を戻す
- //Restore cursor position
- richTextBox1.SelectionStart = 0;
- richTextBox1.EndUpdate();
- //変更フラグOFF
- richTextBox1.Modified = false;
- //Undoバッファに追加
- //Add all text to undo buffer
- UndoBuffer.Clear();
- UndoBuffer.Add(richTextBox1.Rtf);
- undoCounter = UndoBuffer.Count;
-
- //プレビュー更新
- PreviewToBrowser();
- _fConstraintChange = false;
- FormTextChange();
- return (true);
- }
- //----------------------------------------------------------------------
- // 表示するHTMLのテンポラリファイルパスを取得する
- // Get temporary HTML file path
- //----------------------------------------------------------------------
- private string Get_TemporaryHtmlFilePath(string FilePath)
- {
- string DirPath = Path.GetDirectoryName(FilePath);
- string FileName = Path.GetFileNameWithoutExtension(FilePath);
- MD5 md5Hash = MD5.Create();
- byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(FileName));
- StringBuilder sBuilder = new StringBuilder();
- for (int i = 0; i < data.Length; i++)
- {
- sBuilder.Append(data[i].ToString("x2"));
- }
- return (Path.Combine(DirPath, FileName + "_" + sBuilder.ToString() + ".html"));
- }
- //----------------------------------------------------------------------
- // 表示しているHTMLのテンポラリファイルを削除する
- // Delete temporary HTML file
- //----------------------------------------------------------------------
- private void Delete_TemporaryHtmlFilePath()
- {
- string TempHtmlFilePath;
- if (_MarkDownTextFilePath == "")
- {
- return;
- }
- TempHtmlFilePath = Get_TemporaryHtmlFilePath(_MarkDownTextFilePath);
- //見つかったときだけ削除
- //Delete it if the file exists
- if (File.Exists(TempHtmlFilePath) == true)
- {
- try
- {
- File.Delete(TempHtmlFilePath);
- }
- catch
- {
- //"エラー"
- //"テンポラリファイルの削除に失敗しました。編集中の場所に残った可能性があります。
- //"このファイルは手動で削除していただいても問題ありません。
- //"Error"
- //"Error during deleting temporary file!\na temporary file may be left in the folder the file is edited.\n"
- // This file is not a problem even if you delete it manually.
- MessageBox.Show(Resources.MsgErrorDeleteTemporaryFile + TempHtmlFilePath,
- Resources.DialogTitleError, MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- }
- //----------------------------------------------------------------------
- // ブラウザープレビューの間隔を調整
- // Ajust browser preview interval
- //----------------------------------------------------------------------
- private void timer1_Tick(object sender, EventArgs e)
- {
- PreviewToBrowser();
- timer1.Enabled = false;
- }
- private void timer2_Tick(object sender, EventArgs e)
- {
- timer2.Enabled = false;
- }
- //----------------------------------------------------------------------
- // HACK: PreviewToBrowser [ ブラウザプレビュー ]
- //----------------------------------------------------------------------
- private void PreviewToBrowser()
- {
- //更新抑制中のときはプレビューしない
- //Do not preview in constraint to change
- if (_fConstraintChange == true)
- {
- return;
- }
- if (backgroundWorker1.IsBusy == true)
- {
- return;
- }
- string ResultText = "";
- backgroundWorker1.WorkerReportsProgress = true;
- //編集箇所にマーカーを挿入する
- //Insert marker in editing
- if (richTextBox1.SelectionStart > 0)
- {
- //int NextLineNum = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) + 1;
- int ParagraphStart = richTextBox1.GetFirstCharIndexOfCurrentLine();
- //if (ParagraphStart == 0)
- //{
- // ParagraphStart = 1;
- //}
- ResultText =
- richTextBox1.Text.Substring(0, ParagraphStart) + "<!-- edit -->" +
- richTextBox1.Text.Substring(ParagraphStart);
- }
- else
- {
- ResultText = richTextBox1.Text;
- }
- backgroundWorker1.RunWorkerAsync(ResultText);
- }
- //----------------------------------------------------------------------
- // BackgroundWorker ProgressChanged
- //----------------------------------------------------------------------
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- //ProgressBar1.Value = e.ProgressPercentage;
- //Label1.Text = e.ProgressPercentage.ToString();
- }
- //----------------------------------------------------------------------
- // BackgroundWorker browser preview
- //----------------------------------------------------------------------
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- string ResultText = (string)e.Argument;
- string MkResultText = "";
- string BackgroundColorString;
- string EncodingName;
- //編集中のファイル名
- //Editing file name
- string FileName = (_MarkDownTextFilePath == "" ? "" : Path.GetFileName(_MarkDownTextFilePath));
- //DOCTYPE
- HtmlHeader htmlHeader = new HtmlHeader();
- string DocType = htmlHeader.GetHtmlHeader(MarkDownSharpEditor.AppSettings.Instance.HtmlDocType);
- //マーキングの色づけ
- //Marker's color
- if (MarkDownSharpEditor.AppSettings.Instance.fHtmlHighLightColor == true)
- {
- Color ColorBackground = Color.FromArgb(MarkDownSharpEditor.AppSettings.Instance.HtmlHighLightColor);
- BackgroundColorString = ColorTranslator.ToHtml(ColorBackground);
- }
- else
- {
- BackgroundColorString = "none";
- }
- //指定のエンコーディング
- //Codepage
- int CodePageNum = MarkDownSharpEditor.AppSettings.Instance.CodePageNumber;
- try
- {
- Encoding enc = Encoding.GetEncoding(CodePageNum);
- //ブラウザ表示に対応したエンコーディングか
- //Is the encoding supported browser?
- if (enc.IsBrowserDisplay == true)
- {
- EncodingName = enc.WebName;
- }
- else
- {
- EncodingName = "utf-8";
- }
- }
- catch
- {
- //エンコーディングの取得に失敗した場合
- //Default encoding if failing to get encoding
- EncodingName = "utf-8";
- }
- //Header
- string header = string.Format(
- @"{0}
- <html>
- <head>
- <meta http-equiv='Content-Type' content='text/html; charset={1}' />
- <link rel='stylesheet' href='{2}' type='text/css' />
- <style type='text/css'>
- ._mk {{background-color:{3}}}
- </style>
- <title>{4}</title>
- </head>
- <body>
- ",
- DocType, //DOCTYPE
- EncodingName, //エンコーディング ( encoding )
- _SelectedCssFilePath, //適用中のCSSファイル ( Selected CSS file )
- BackgroundColorString, //編集箇所の背景色 ( background color in Editing )
- FileName); //タイトル(=ファイル名) ( title = file name )
- //Footer
- string footer = "</body>\n</html>";
- //-----------------------------------
- //Markdown parse ( default )
- //Markdown mkdwn = new Markdown();
- //-----------------------------------
- //-----------------------------------
- // MarkdownDeep
- // Create an instance of Markdown
- //-----------------------------------
- var mkdwn = new MarkdownDeep.Markdown();
- // Set options
- mkdwn.ExtraMode = MarkDownSharpEditor.AppSettings.Instance.fMarkdownExtraMode;
- mkdwn.SafeMode = false;
- //-----------------------------------
- ResultText = mkdwn.Transform(ResultText);
- //表示するHTMLデータを作成
- //Creat HTML data
- ResultText = header + ResultText + footer;
- //パースされた内容から編集行を探す
- //Search editing line in parsed data
- string OneLine;
- StringReader sr = new StringReader(ResultText);
- StringWriter sw = new StringWriter();
- while ((OneLine = sr.ReadLine()) != null)
- {
- if (OneLine.IndexOf("<!-- edit -->") >= 0)
- {
- MkResultText += ("<div class='_mk'>" + OneLine + "</div>\n");
- }
- else
- {
- MkResultText += (OneLine + "\n");
- }
- }
- //エンコーディングしつつbyte値に変換する(richEditBoxは基本的にutf-8 = 65001)
- //Encode and convert it to 'byte' value ( richEditBox default encoding is utf-8 = 65001 )
- byte[] bytesData = Encoding.GetEncoding(CodePageNum).GetBytes(MkResultText);
- //-----------------------------------
- // Write to temporay file
- if (_fNoTitle == false)
- {
- //テンポラリファイルパスを取得する
- //Get temporary file path
- if (_TemporaryHtmlFilePath == "")
- {
- _TemporaryHtmlFilePath = Get_TemporaryHtmlFilePath(_MarkDownTextFilePath);
- }
- //他のプロセスからのテンポラリファイルの参照と削除を許可して開く(でないと飛ぶ)
- //Open temporary file to allow references from other processes
- using (FileStream fs = new FileStream(
- _TemporaryHtmlFilePath,
- FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read | FileShare.Delete))
- {
- fs.Write(bytesData, 0, bytesData.Length);
- e.Result = _TemporaryHtmlFilePath;
- }
- }
- //-----------------------------------
- // Navigate and view in browser
- else
- {
- //Write data as it is, if the editing data is no title
- ResultText = Encoding.GetEncoding(CodePageNum).GetString(bytesData);
- e.Result = ResultText;
- }
- }
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- if (e.Error != null)
- {
- //Error!
- }
- else
- {
- if ((string)e.Result != "")
- {
- //-----------------------------------
- //スクロールバーの位置を退避しておく
- //Memorize scroll positions
- HtmlDocument doc = webBrowser1.Document;
- Point scrollpos = new Point(0, 0);
- if (doc == null)
- {
- webBrowser1.Navigate("about:blank");
- }
- else
- {
- IHTMLDocument3 doc3 = (IHTMLDocument3)webBrowser1.Document.DomDocument;
- IHTMLElement2 elm = (IHTMLElement2)doc3.documentElement;
- scrollpos = new Point(elm.scrollLeft, elm.scrollTop);
- }
- //-----------------------------------
- System.Threading.Tasks.Task waitTask;
- if (_fNoTitle == false)
- {
- //ナビゲート
- //Browser navigate
- //webBrowser1.Navigate(@"file://" + (string)e.Result);
- waitTask = WebBrowserNavigate(@"file://" + (string)e.Result);
- richTextBox1.Focus();
- toolStripButtonBrowserPreview.Enabled = true;
- }
- else
- {
- webBrowser1.Document.OpenNew(true);
- //webBrowser1.Document.Write((string)e.Result);
- waitTask = WebBrowserDocumentWrite((string)e.Result);
- //ツールバーの「関連付けられたブラウザーを起動」を無効に
- //"Associated web browser" in toolbar is invalid
- toolStripButtonBrowserPreview.Enabled = false;
- }
- //-----------------------------------
- //スクロールバーの位置を復帰する
- //Restore scroll bar position
- if (doc != null)
- {
- waitTask.ContinueWith((arg1) =>
- {
- this.BeginInvoke(new Action(() =>
- {
- doc.Window.ScrollTo(scrollpos);
- this.webBrowser1.Document.Body.AttachEventHandler("onscroll", OnScrollEventHandler);
- }));
- });
- }
- }
- }
- }
- /// <summary>
- /// webBrowser コンポーネントにHTMLを出力して
- /// DocumentComplate になるのを非同期で待ち合わせる
- /// </summary>
- /// <param name="html"></param>
- /// <returns></returns>
- System.Threading.Tasks.Task WebBrowserDocumentWrite(string html)
- {
- if (browserWaitTimer == null)
- {
- browserWaitTimer = new Timer();
- browserWaitTimer.Tick += browserWaitTimer_Tick;
- browserWaitTimer.Enabled = true;
- }
- var obj = waitObject;
- if (obj != null)
- {
- obj.SetCanceled();
- }
- waitObject = new System.Threading.Tasks.TaskCompletionSource<string>();
- timerCount = 0;
- this.webBrowser1.DocumentText = html;
- browserWaitTimer.Enabled = true;
- return waitObject.Task;
- }
- /// <summary>
- /// webBrowser コンポーネントにHTMLを出力して
- /// DocumentComplate になるのを非同期で待ち合わせる
- /// </summary>
- /// <param name="html"></param>
- /// <returns></returns>
- System.Threading.Tasks.Task WebBrowserNavigate(string url)
- {
- if (browserWaitTimer == null)
- {
- browserWaitTimer = new Timer();
- browserWaitTimer.Tick += browserWaitTimer_Tick;
- browserWaitTimer.Enabled = true;
- }
- var obj = waitObject;
- if (obj != null)
- {
- obj.SetCanceled();
- }
- waitObject = new System.Threading.Tasks.TaskCompletionSource<string>();
- timerCount = 0;
- this.webBrowser1.Navigate(url);
- browserWaitTimer.Enabled = true;
- return waitObject.Task;
- }
- void browserWaitTimer_Tick(object sender, EventArgs e)
- {
- if (waitObject == null)
- {
- browserWaitTimer.Enabled = false;
- return;
- }
- timerCount++;
- if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
- {
- waitObject.SetResult("OK");
- waitObject = null;
- browserWaitTimer.Enabled = false;
- }
- else if (timerCount > 20)
- {
- // 反応ないので終わりにする
- waitObject.SetResult("OK");
- waitObject = null;
- browserWaitTimer.Enabled = false;
- }
- }
- System.Threading.Tasks.TaskCompletionSource<string> waitObject = null;
- int timerCount = 0;
- Timer browserWaitTimer;
- //----------------------------------------------------------------------
- // BackgroundWorker Syntax hightlighter work
- //----------------------------------------------------------------------
- private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
- {
- var text = e.Argument as string;
- if (string.IsNullOrEmpty(text))
- {
- e.Result = null;
- return;
- }
- if (timer2.Enabled == true)
- {
- e.Result = null;
- return;
- }
- var result = new List<SyntaxColorScheme>();
- foreach (MarkdownSyntaxKeyword mk in _MarkdownSyntaxKeywordAarray)
- {
- MatchCollection col = mk.Regex.Matches(text, 0);
-
- if (col.Count > 0)
- {
- foreach (Match m in col)
- {
- SyntaxColorScheme sytx = new SyntaxColorScheme();
- sytx.SelectionStartIndex = m.Groups[0].Index;
- sytx.SelectionLength = m.Groups[0].Length;
- sytx.ForeColor = mk.ForeColor;
- sytx.BackColor = mk.BackColor;
- result.Add(sytx);
- }
- }
- }
- e.Result = result;
- }
- //----------------------------------------------------------------------
- // BackgroundWorker Editor Syntax hightlighter progress changed
- //----------------------------------------------------------------------
- private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- }
- //-------------------------------------------------------…
Large files files are truncated, but you can click here to view the full file