2 * Copyright (C) 2013 FooProject
3 * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
6 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
7 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
9 You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
14 using System.ComponentModel;
15 using System.Collections.Generic;
17 using System.Text.RegularExpressions;
18 using System.Threading;
19 using System.Threading.Tasks;
21 using System.Runtime.CompilerServices;
23 namespace FooEditEngine
26 /// オートインデントを行うためのデリゲートを表す
28 /// <param name="sender">イベント発生元のオブジェクト</param>
29 /// <param name="e">イベントデーター</param>
30 public delegate void AutoIndentHookerHandler(object sender, EventArgs e);
35 public enum ProgressState
49 public sealed class ProgressEventArgs : EventArgs
54 public ProgressState state;
58 /// <param name="state">ProgressStateオブジェクト</param>
59 public ProgressEventArgs(ProgressState state)
68 /// <param name="sender">送信元クラス</param>
69 /// <param name="e">イベントデータ</param>
70 public delegate void ProgressEventHandler(object sender, ProgressEventArgs e);
75 public enum UpdateType
78 /// ドキュメントが置き換えられたことを表す
82 /// ドキュメント全体が削除されたことを表す
92 /// 更新タイプを通知するためのイベントデータ
94 public sealed class DocumentUpdateEventArgs : EventArgs
99 public const int EmptyValue = -1;
103 public UpdateType type;
107 public int startIndex;
111 public int removeLength;
115 public int insertLength;
117 /// 更新イベントが発生した行。行が不明な場合や行をまたぐ場合はnullを指定すること。
123 /// <param name="type">更新タイプ</param>
124 /// <param name="startIndex">開始インデックス</param>
125 /// <param name="removeLength">削除された長さ</param>
126 /// <param name="insertLength">追加された長さ</param>
127 /// <param name="row">開始行。nullを指定することができる</param>
128 public DocumentUpdateEventArgs(UpdateType type, int startIndex = EmptyValue, int removeLength = EmptyValue, int insertLength = EmptyValue, int? row = null)
131 this.startIndex = startIndex;
132 this.removeLength = removeLength;
133 this.insertLength = insertLength;
139 /// ドキュメントに更新があったことを伝えるためのデリゲート
141 /// <param name="sender">送信元クラス</param>
142 /// <param name="e">イベントデータ</param>
143 public delegate void DocumentUpdateEventHandler(object sender, DocumentUpdateEventArgs e);
148 /// <remarks>この型のすべてのメソッド・プロパティはスレッドセーフです</remarks>
149 public sealed class Document : IEnumerable<char>, IRandomEnumrator<char>, IDisposable
154 LineToIndexTable _LayoutLines;
155 bool _EnableFireUpdateEvent = true,_UrlMark = false, _DrawLineNumber = false, _HideRuler = true, _RightToLeft = false;
156 LineBreakMethod _LineBreak;
157 int _TabStops, _LineBreakCharCount = 80;
158 bool _ShowFullSpace, _ShowHalfSpace, _ShowTab, _ShowLineBreak,_InsertMode, _HideCaret, _HideLineMarker, _RectSelection;
159 IndentMode _IndentMode;
164 public const int MaximumLineLength = 1000;
177 /// <param name="doc">ドキュメントオブジェクト</param>
178 /// <remarks>docが複製されますが、プロパティは引き継がれません</remarks>
179 public Document(Document doc)
182 this.buffer = new StringBuffer();
184 this.buffer = new StringBuffer(doc.buffer);
185 this.buffer.Update = new DocumentUpdateEventHandler(buffer_Update);
186 this.Update += new DocumentUpdateEventHandler((s, e) => { });
187 this.ChangeFireUpdateEvent += new EventHandler((s, e) => { });
188 this.StatusUpdate += new EventHandler((s, e) => { });
189 this.Markers = new MarkerCollection();
190 this.UndoManager = new UndoManager();
191 this._LayoutLines = new LineToIndexTable(this);
192 this._LayoutLines.SpilitString = (s,e)=> {
193 return this.CreateLineList(e.index, e.length, MaximumLineLength);
195 this._LayoutLines.Clear();
196 this.MarkerPatternSet = new MarkerPatternSet(this._LayoutLines, this.Markers);
197 this.MarkerPatternSet.Updated += WacthDogPattern_Updated;
198 this.Selections = new SelectCollection();
199 this.CaretPostion = new TextPoint();
200 this.HideLineMarker = true;
201 this.SelectGrippers = new GripperRectangle(new Gripper(), new Gripper());
202 this.SelectionChanged += new EventHandler((s, e) => { });
203 this.CaretChanged += (s, e) => { };
204 this.AutoIndentHook += (s, e) => { };
205 this.LineBreakChanged += (s, e) => { };
209 void WacthDogPattern_Updated(object sender, EventArgs e)
211 this._LayoutLines.ClearLayoutCache();
215 /// ダーティフラグ。保存されていなければ真、そうでなければ偽。
224 /// キャレットでの選択の起点となる位置
226 internal int AnchorIndex
235 internal SrcPoint Src
251 /// 補完候補プロセッサーが切り替わったときに発生するイベント
253 public event EventHandler AutoCompleteChanged;
255 AutoCompleteBoxBase _AutoComplete;
259 public AutoCompleteBoxBase AutoComplete
263 return this._AutoComplete;
267 this._AutoComplete = value;
268 if (this.AutoCompleteChanged != null)
269 this.AutoCompleteChanged(this, null);
276 public event ProgressEventHandler LoadProgress;
279 /// ルーラーやキャレット・行番号などの表示すべきものが変化した場合に呼び出される。ドキュメントの内容が変化した通知を受け取り場合はUpdateを使用してください
281 public event EventHandler StatusUpdate;
286 public bool ShowFullSpace
288 get { return this._ShowFullSpace; }
291 if (this._ShowFullSpace == value)
293 this._ShowFullSpace = value;
294 this.StatusUpdate(this, null);
301 public bool ShowHalfSpace
303 get { return this._ShowHalfSpace; }
306 if (this._ShowHalfSpace == value)
308 this._ShowHalfSpace = value;
309 this.StatusUpdate(this, null);
318 get { return this._ShowTab; }
321 if (this._ShowTab == value)
323 this._ShowTab = value;
324 this.StatusUpdate(this, null);
331 public bool ShowLineBreak
333 get { return this._ShowLineBreak; }
336 if (this._ShowLineBreak == value)
338 this._ShowLineBreak = value;
339 this.StatusUpdate(this, null);
346 internal GripperRectangle SelectGrippers
355 public bool RightToLeft {
356 get { return this._RightToLeft; }
359 if (this._RightToLeft == value)
361 this._RightToLeft = value;
362 this.StatusUpdate(this, null);
367 /// 矩形選択モードなら真を返し、そうでない場合は偽を返す
369 public bool RectSelection
373 return this._RectSelection;
377 this._RectSelection = value;
378 this.StatusUpdate(this, null);
385 public IndentMode IndentMode
389 return this._IndentMode;
393 this._IndentMode = value;
394 this.StatusUpdate(this, null);
399 /// ラインマーカーを描くなら偽。そうでなければ真
401 public bool HideLineMarker
405 return this._HideLineMarker;
409 this._HideLineMarker = value;
410 this.StatusUpdate(this, null);
415 /// キャレットを描くなら偽。そうでなければ真
417 public bool HideCaret
421 return this._HideCaret;
425 this._HideCaret = value;
426 this.StatusUpdate(this, null);
431 /// 挿入モードなら真を返し、上書きモードなら偽を返す
433 public bool InsertMode
437 return this._InsertMode;
441 this._InsertMode = value;
442 this.StatusUpdate(this, null);
447 /// ルーラーを表示しないなら真、そうでないなら偽
449 public bool HideRuler
451 get { return this._HideRuler; }
454 if (this._HideRuler == value)
456 this._HideRuler = value;
457 this.LayoutLines.ClearLayoutCache();
458 this.StatusUpdate(this, null);
462 TextPoint _CaretPostion;
464 /// レイアウト行のどこにキャレットがあるかを表す
466 public TextPoint CaretPostion
470 return this._CaretPostion;
474 if(this._CaretPostion != value)
476 this._CaretPostion = value;
477 this.CaretChanged(this, null);
482 internal void SetCaretPostionWithoutEvent(TextPoint value)
484 if (this._CaretPostion != value)
485 this._CaretPostion = value;
491 internal SelectCollection Selections
500 public bool DrawLineNumber
502 get { return this._DrawLineNumber; }
505 if (this._DrawLineNumber == value)
507 this._DrawLineNumber = value;
508 this._LayoutLines.ClearLayoutCache();
509 this.StatusUpdate(this, null);
514 /// URLをハイパーリンクとして表示するなら真。そうでないなら偽
518 get { return this._UrlMark; }
521 if (this._UrlMark == value)
523 this._UrlMark = value;
526 Regex regex = new Regex("(http|https|ftp)(:\\/\\/[-_.!~*\\'()a-zA-Z0-9;\\/?:\\@&=+\\$,%#]+)");
527 this.MarkerPatternSet.Add(MarkerIDs.URL, new RegexMarkerPattern(regex, HilightType.Url, new Color()));
531 this.MarkerPatternSet.Remove(MarkerIDs.URL);
533 this.StatusUpdate(this, null);
540 public event EventHandler LineBreakChanged;
546 /// 変更した場合、呼び出し側で再描写とレイアウトの再構築を行う必要があります
547 /// また、StatusUpdatedではなく、LineBreakChangedイベントが発生します
549 public LineBreakMethod LineBreak
553 return this._LineBreak;
557 if (this._LineBreak == value)
559 this._LineBreak = value;
560 this.LineBreakChanged(this, null);
565 /// 折り返し行う文字数。実際に折り返しが行われる幅はem単位×この値となります
567 /// <remarks>この値を変えた場合、LineBreakChangedイベントが発生します</remarks>
568 public int LineBreakCharCount
572 return this._LineBreakCharCount;
576 if (this._LineBreakCharCount == value)
578 this._LineBreakCharCount = value;
579 this.LineBreakChanged(this, null);
586 /// <remarks>変更した場合、呼び出し側で再描写する必要があります</remarks>
589 get { return this._TabStops; }
591 if (this._TabStops == value)
593 this._TabStops = value;
594 this.StatusUpdate(this, null);
601 public MarkerPatternSet MarkerPatternSet
610 public LineToIndexTable LayoutLines
614 return this._LayoutLines;
621 /// <param name="index">開始インデックス</param>
622 /// <param name="length">長さ</param>
623 /// <param name="lineLimitLength">1行当たりの最大文字数。-1で無制限</param>
624 /// <returns>レイアウト行リスト</returns>
625 internal IList<LineToIndexTableData> CreateLineList(int index, int length, int lineLimitLength = -1)
627 int startIndex = index;
628 int endIndex = index + length - 1;
629 List<LineToIndexTableData> output = new List<LineToIndexTableData>();
631 foreach (Tuple<int, int> range in this.ForEachLines(startIndex, endIndex, lineLimitLength))
633 int lineHeadIndex = range.Item1;
634 int lineLength = range.Item2;
635 char c = this.buffer[lineHeadIndex + lineLength - 1];
636 bool hasNewLine = c == Document.NewLine;
637 output.Add(this.LayoutLines.CreateLineToIndexTableData(lineHeadIndex, lineLength, hasNewLine, null));
640 if (output.Count > 0)
641 output.Last().LineEnd = true;
646 internal void FireUpdate(DocumentUpdateEventArgs e)
648 this.buffer_Update(this.buffer, e);
652 /// ドキュメントが更新された時に呼ばれるイベント
654 public event DocumentUpdateEventHandler Update;
657 /// FireUpdateEventの値が変わったときに呼び出されるイベント
659 public event EventHandler ChangeFireUpdateEvent;
664 public const char NewLine = '\n';
669 public const char EndOfFile = '\u001a';
674 public UndoManager UndoManager
687 return this.buffer.Length;
692 /// 変更のたびにUpdateイベントを発生させるかどうか
694 public bool FireUpdateEvent
698 return this._EnableFireUpdateEvent;
702 this._EnableFireUpdateEvent = value;
703 this.ChangeFireUpdateEvent(this, null);
710 /// <param name="i">インデックス(自然数でなければならない)</param>
711 /// <returns>Char型</returns>
712 public char this[int i]
716 return this.buffer[i];
723 public MarkerCollection Markers
729 internal StringBuffer StringBuffer
740 public bool IsRequestRedraw { get; internal set; }
745 public void RequestRedraw()
747 this.IsRequestRedraw = true;
751 /// レイアウト行が再構成されたときに発生するイベント
753 public event EventHandler PerformLayouted;
755 /// レイアウト行をすべて破棄し、再度レイアウトを行う
757 public void PerformLayout()
759 this.LayoutLines.IsFrozneDirtyFlag = true;
760 this.FireUpdate(new DocumentUpdateEventArgs(UpdateType.RebuildLayout, -1, -1, -1));
761 this.LayoutLines.IsFrozneDirtyFlag = false;
762 if (this.PerformLayouted != null)
763 this.PerformLayouted(this, null);
767 /// オードインデントが可能になった時に通知される
770 /// FireUpdateEventの影響を受けます
772 public event AutoIndentHookerHandler AutoIndentHook;
777 public event EventHandler SelectionChanged;
782 public event EventHandler CaretChanged;
787 /// <param name="start"></param>
788 /// <param name="length"></param>
789 /// <remarks>RectSelectionの値によって動作が変わります。真の場合は矩形選択モードに、そうでない場合は行ごとに選択されます</remarks>
790 public void Select(int start, int length)
792 if (this.FireUpdateEvent == false)
793 throw new InvalidOperationException("");
794 if (start < 0 || start + length < 0 || start + length > this.Length)
795 throw new ArgumentOutOfRangeException("startかendが指定できる範囲を超えてます");
797 foreach (Selection sel in this.Selections)
798 this.LayoutLines.ClearLayoutCache(sel.start, sel.length);
799 this.Selections.Clear();
802 int oldStart = start;
804 length = oldStart - start;
806 if (this.RectSelection && length != 0)
808 TextPoint startTextPoint = this.LayoutLines.GetTextPointFromIndex(start);
809 TextPoint endTextPoint = this.LayoutLines.GetTextPointFromIndex(start + length);
810 this.SelectByRectangle(new TextRectangle(startTextPoint, endTextPoint));
811 this.LayoutLines.ClearLayoutCache(start, length);
813 else if (length != 0)
815 this.Selections.Add(Selection.Create(start, length));
816 this.LayoutLines.ClearLayoutCache(start, length);
818 this.SelectionChanged(this, null);
824 /// <param name="tp">開始位置</param>
825 /// <param name="width">桁数</param>
826 /// <param name="height">行数</param>
827 public void Select(TextPoint tp, int width, int height)
829 if (this.FireUpdateEvent == false || !this.RectSelection)
830 throw new InvalidOperationException("");
833 end.row = tp.row + height;
834 end.col = tp.col + width;
836 if (end.row > this.LayoutLines.Count - 1)
837 throw new ArgumentOutOfRangeException("");
839 this.Selections.Clear();
841 this.SelectByRectangle(new TextRectangle(tp, end));
843 this.SelectionChanged(this, null);
846 private void SelectByRectangle(TextRectangle rect)
848 if (this.FireUpdateEvent == false)
849 throw new InvalidOperationException("");
850 if (rect.TopLeft <= rect.BottomRight)
852 for (int i = rect.TopLeft.row; i <= rect.BottomLeft.row; i++)
854 int length = this.LayoutLines.GetLengthFromLineNumber(i);
855 int leftCol = rect.TopLeft.col, rightCol = rect.TopRight.col, lastCol = length;
856 if (length > 0 && this.LayoutLines[i][length - 1] == Document.NewLine)
857 lastCol = length - 1;
860 if (rect.TopLeft.col > lastCol)
862 if (rect.TopRight.col > lastCol)
865 int StartIndex = this.LayoutLines.GetIndexFromTextPoint(new TextPoint(i, leftCol));
866 int EndIndex = this.LayoutLines.GetIndexFromTextPoint(new TextPoint(i, rightCol));
869 sel = Selection.Create(StartIndex, EndIndex - StartIndex);
871 this.Selections.Add(sel);
879 /// <param name="index">探索を開始するインデックス</param>
880 /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
881 public void SelectWord(int index, bool changeAnchor = false)
883 this.SelectSepartor(index, (c) => Util.IsWordSeparator(c), changeAnchor);
889 /// <param name="index">探索を開始するインデックス</param>
890 /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
891 public void SelectLine(int index,bool changeAnchor = false)
893 this.SelectSepartor(index, (c) => c == Document.NewLine, changeAnchor);
897 /// セパレーターで囲まれた範囲内を選択する
899 /// <param name="index">探索を開始するインデックス</param>
900 /// <param name="find_sep_func">セパレーターなら真を返し、そうでないなら偽を返す</param>
901 /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
902 public void SelectSepartor(int index,Func<char,bool> find_sep_func, bool changeAnchor = false)
904 if (this.FireUpdateEvent == false)
905 throw new InvalidOperationException("");
907 if (find_sep_func == null)
908 throw new ArgumentNullException("find_sep_func must not be null");
910 if (this.Length <= 0 || index >= this.Length)
916 while (start > 0 && !find_sep_func(str[start]))
919 if (find_sep_func(str[start]))
925 while (end < this.Length && !find_sep_func(str[end]))
928 this.Select(start, end - start);
931 this.AnchorIndex = start;
935 /// DocumentReaderを作成します
937 /// <returns>DocumentReaderオブジェクト</returns>
938 public DocumentReader CreateReader()
940 return new DocumentReader(this.buffer);
946 /// <param name="id">マーカーID</param>
947 /// <param name="m">設定したいマーカー</param>
948 public void SetMarker(int id,Marker m)
950 if (m.start < 0 || m.start + m.length > this.Length)
951 throw new ArgumentOutOfRangeException("startもしくはendが指定できる範囲を超えています");
953 this.Markers.Add(id,m);
959 /// <param name="id">マーカーID</param>
960 /// <param name="start">開始インデックス</param>
961 /// <param name="length">削除する長さ</param>
962 public void RemoveMarker(int id,int start, int length)
964 if (start < 0 || start + length > this.Length)
965 throw new ArgumentOutOfRangeException("startもしくはendが指定できる範囲を超えています");
967 this.Markers.RemoveAll(id,start, length);
973 /// <param name="id">マーカーID</param>
974 /// <param name="type">削除したいマーカーのタイプ</param>
975 public void RemoveMarker(int id, HilightType type)
977 this.Markers.RemoveAll(id,type);
983 /// <param name="id">マーカーID</param>
984 public void RemoveAllMarker(int id)
986 this.Markers.RemoveAll(id);
990 /// インデックスに対応するマーカーを得る
992 /// <param name="id">マーカーID</param>
993 /// <param name="index">インデックス</param>
994 /// <returns>Marker構造体の列挙子</returns>
995 public IEnumerable<Marker> GetMarkers(int id, int index)
997 if (index < 0 || index > this.Length)
998 throw new ArgumentOutOfRangeException("indexが範囲を超えています");
999 return this.Markers.Get(id,index);
1005 /// <param name="index">開始インデックス</param>
1006 /// <param name="length">長さ</param>
1007 /// <returns>Stringオブジェクト</returns>
1008 public string ToString(int index, int length)
1010 return this.buffer.ToString(index, length);
1014 /// インデックスを開始位置とする文字列を返す
1016 /// <param name="index">開始インデックス</param>
1017 /// <returns>Stringオブジェクト</returns>
1018 public string ToString(int index)
1020 return this.ToString(index, this.buffer.Length - index);
1026 /// <param name="startIndex">開始インデックス</param>
1027 /// <param name="endIndex">終了インデックス</param>
1028 /// <param name="maxCharCount">最大長</param>
1029 /// <returns>行イテレーターが返される</returns>
1030 public IEnumerable<string> GetLines(int startIndex, int endIndex, int maxCharCount = -1)
1032 return this.buffer.GetLines(startIndex, endIndex, maxCharCount);
1035 internal IEnumerable<Tuple<int, int>> ForEachLines(int startIndex, int endIndex, int maxCharCount = -1)
1037 return this.buffer.ForEachLines(startIndex, endIndex, maxCharCount);
1044 /// <param name="s">追加したい文字列</param>
1045 /// <remarks>非同期操作中はこのメソッドを実行することはできません</remarks>
1046 public void Append(string s)
1048 this.Replace(this.buffer.Length, 0, s);
1054 /// <param name="index">開始インデックス</param>
1055 /// <param name="s">追加したい文字列</param>
1056 /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
1057 public void Insert(int index, string s)
1059 this.Replace(index, 0, s);
1065 /// <param name="index">開始インデックス</param>
1066 /// <param name="length">長さ</param>
1067 /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
1068 public void Remove(int index, int length)
1070 this.Replace(index, length, "");
1076 /// <param name="index">開始インデックス</param>
1077 /// <param name="length">長さ</param>
1078 /// <param name="s">文字列</param>
1079 /// <param name="UserInput">ユーザーからの入力として扱うなら真</param>
1080 /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
1081 public void Replace(int index, int length, string s, bool UserInput = false)
1083 if (index < 0 || index > this.buffer.Length || index + length > this.buffer.Length || length < 0)
1084 throw new ArgumentOutOfRangeException();
1085 if (length == 0 && (s == string.Empty || s == null))
1088 foreach(int id in this.Markers.IDs)
1089 this.RemoveMarker(id,index, length);
1091 ReplaceCommand cmd = new ReplaceCommand(this.buffer, index, length, s);
1092 this.UndoManager.push(cmd);
1095 if (this.FireUpdateEvent && UserInput)
1097 var input_str = string.Empty;
1098 if (s == Document.NewLine.ToString())
1100 else if (s == string.Empty && length > 0)
1102 //入力は終わっているので空文字を渡すが処理の都合で一部文字だけはそのまま渡す
1103 if (this.AutoComplete != null)
1104 this.AutoComplete.ParseInput(input_str);
1105 if (s == Document.NewLine.ToString())
1106 this.AutoIndentHook(this, null);
1113 /// <remarks>Dirtyフラグも同時にクリアーされます</remarks>
1114 /// <remarks>非同期操作中はこのメソッドを実行することはできません</remarks>
1117 this.buffer.Clear();
1122 /// ストリームからドキュメントを非同期的に構築します
1124 /// <param name="fs">IStreamReaderオブジェクト</param>
1125 /// <param name="tokenSource">キャンセルトークン</param>
1126 /// <returns>Taskオブジェクト</returns>
1128 /// 読み取り操作は別スレッドで行われます。
1129 /// また、非同期操作中はこのメソッドを実行することはできません。
1131 public async Task LoadAsync(TextReader fs, CancellationTokenSource tokenSource = null)
1133 if (fs.Peek() == -1)
1136 if (this.LoadProgress != null)
1137 this.LoadProgress(this, new ProgressEventArgs(ProgressState.Start));
1142 await this.buffer.LoadAsync(fs, tokenSource);
1146 this.PerformLayout();
1147 if (this.LoadProgress != null)
1148 this.LoadProgress(this, new ProgressEventArgs(ProgressState.Complete));
1153 /// ストリームに非同期モードで保存します
1155 /// <param name="fs">IStreamWriterオブジェクト</param>
1156 /// <param name="tokenSource">キャンセルトークン</param>
1157 /// <returns>Taskオブジェクト</returns>
1158 /// <remarks>非同期操作中はこのメソッドを実行することはできません</remarks>
1159 public async Task SaveAsync(TextWriter fs, CancellationTokenSource tokenSource = null)
1161 await this.buffer.SaveAsync(fs, tokenSource);
1165 /// Find()およびReplaceAll()で使用するパラメーターをセットします
1167 /// <param name="pattern">検索したい文字列</param>
1168 /// <param name="UseRegex">正規表現を使用するなら真</param>
1169 /// <param name="opt">RegexOptions列挙体</param>
1170 public void SetFindParam(string pattern, bool UseRegex, RegexOptions opt)
1174 this.regex = new Regex(pattern, opt);
1176 this.regex = new Regex(Regex.Escape(pattern), opt);
1180 /// 現在の検索パラメーターでWatchDogを生成する
1182 /// <param name="type">ハイライトタイプ</param>
1183 /// <param name="color">色</param>
1184 /// <returns>WatchDogオブジェクト</returns>
1185 public RegexMarkerPattern CreateWatchDogByFindParam(HilightType type,Color color)
1187 if (this.regex == null)
1188 throw new InvalidOperationException("SetFindParam()を呼び出してください");
1189 return new RegexMarkerPattern(this.regex,type,color);
1195 /// <returns>見つかった場合はSearchResult列挙子を返却します</returns>
1196 /// <remarks>見つかったパターン以外を置き換えた場合、正常に動作しないことがあります</remarks>
1197 public IEnumerator<SearchResult> Find()
1199 return this.Find(0, this.Length);
1205 /// <returns>見つかった場合はSearchResult列挙子を返却します</returns>
1206 /// <param name="start">開始インデックス</param>
1207 /// <param name="length">検索する長さ</param>
1208 /// <remarks>見つかったパターン以外を置き換えた場合、正常に動作しないことがあります</remarks>
1209 public IEnumerator<SearchResult> Find(int start, int length)
1211 if (this.regex == null)
1212 throw new InvalidOperationException();
1213 if (start < 0 || start >= this.Length)
1214 throw new ArgumentOutOfRangeException();
1216 int end = start + length - 1;
1218 if(end > this.Length - 1)
1219 throw new ArgumentOutOfRangeException();
1221 StringBuilder line = new StringBuilder();
1222 int oldLength = this.Length;
1223 for (int i = start; i <= end; i++)
1227 if (c == Document.NewLine || i == end)
1229 this.match = this.regex.Match(line.ToString());
1230 while (this.match.Success)
1232 int startIndex = i - line.Length + 1 + this.match.Index;
1233 int endIndex = startIndex + this.match.Length - 1;
1235 yield return new SearchResult(this.match, startIndex, endIndex);
1237 if (this.Length != oldLength) //長さが変わった場合は置き換え後のパターンの終点+1まで戻る
1239 int delta = this.Length - oldLength;
1240 i = endIndex + delta;
1242 oldLength = this.Length;
1246 this.match = this.match.NextMatch();
1254 /// 任意のパターンですべて置き換えます
1256 /// <param name="replacePattern">置き換え後のパターン</param>
1257 /// <param name="groupReplace">グループ置き換えを行うなら真。そうでないなら偽</param>
1258 public void ReplaceAll(string replacePattern,bool groupReplace)
1260 if (this.regex == null)
1261 throw new InvalidOperationException();
1262 ReplaceAllCommand cmd = new ReplaceAllCommand(this.buffer, this.LayoutLines, this.regex, replacePattern, groupReplace);
1263 this.UndoManager.push(cmd);
1270 /// <param name="target">対象となる文字列</param>
1271 /// <param name="pattern">置き換え後の文字列</param>
1272 /// <param name="ci">大文字も文字を区別しないなら真。そうでないなら偽</param>
1274 /// 検索時に大文字小文字を区別します。また、このメソッドでは正規表現を使用することはできません
1276 public void ReplaceAll2(string target, string pattern,bool ci = false)
1278 FastReplaceAllCommand cmd = new FastReplaceAllCommand(this.buffer, this.LayoutLines, target, pattern,ci);
1279 this.UndoManager.push(cmd);
1283 #region IEnumerable<char> メンバー
1288 /// <returns>IEnumeratorオブジェクトを返す</returns>
1289 public IEnumerator<char> GetEnumerator()
1291 return this.buffer.GetEnumerator();
1296 #region IEnumerable メンバー
1298 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
1300 throw new NotImplementedException();
1305 void buffer_Update(object sender, DocumentUpdateEventArgs e)
1309 case UpdateType.RebuildLayout:
1310 this._LayoutLines.Clear();
1311 this._LayoutLines.UpdateAsReplace(0, 0, this.Length);
1313 case UpdateType.Replace:
1316 this._LayoutLines.UpdateAsReplace(e.startIndex, e.removeLength, e.insertLength);
1317 this.Markers.UpdateMarkers(e.startIndex, e.insertLength, e.removeLength);
1321 this._LayoutLines.UpdateLineAsReplace(e.row.Value, e.removeLength, e.insertLength);
1322 this.Markers.UpdateMarkers(this.LayoutLines.GetIndexFromLineNumber(e.row.Value), e.insertLength, e.removeLength);
1326 case UpdateType.Clear:
1327 this._LayoutLines.Clear();
1331 if(this.FireUpdateEvent)
1332 this.Update(this, e);
1335 #region IDisposable Support
1336 private bool disposedValue = false; // 重複する呼び出しを検出するには
1338 void Dispose(bool disposing)
1344 this.buffer.Clear();
1345 this.LayoutLines.Clear();
1348 disposedValue = true;
1355 public void Dispose()
1365 public class SearchResult
1367 private Match Match;
1384 get { return this.Match.Value; }
1388 /// 指定したパターンを置き換えて返す
1390 /// <param name="replacement">置き換える文字列</param>
1391 /// <returns>置き換え後の文字列</returns>
1392 public string Result(string replacement)
1394 return this.Match.Result(replacement);
1400 /// <param name="m">Matchオブジェクト</param>
1401 /// <param name="start">開始インデックス</param>
1402 /// <param name="end">終了インデックス</param>
1403 public SearchResult(Match m, int start,int end)
1414 public class DocumentReader : TextReader
1416 StringBuffer document;
1422 /// <param name="doc"></param>
1423 internal DocumentReader(StringBuffer doc)
1426 throw new ArgumentNullException();
1427 this.document = doc;
1433 /// <returns>文字。取得できない場合は-1</returns>
1434 public override int Peek()
1436 if (this.document == null)
1437 throw new InvalidOperationException();
1438 if (this.currentIndex >= this.document.Length)
1440 return this.document[this.currentIndex];
1444 /// 文字を取得し、イテレーターを一つ進める
1446 /// <returns>文字。取得できない場合は-1</returns>
1447 public override int Read()
1449 int c = this.Peek();
1451 this.currentIndex++;
1456 /// 文字列を読み取りバッファーに書き込む
1458 /// <param name="buffer">バッファー</param>
1459 /// <param name="index">開始インデックス</param>
1460 /// <param name="count">カウント</param>
1461 /// <returns>読み取られた文字数</returns>
1462 public override int Read(char[] buffer, int index, int count)
1464 if (this.document == null)
1465 throw new InvalidOperationException();
1468 throw new ArgumentNullException();
1470 if (this.document.Length < count)
1471 throw new ArgumentException();
1473 if (index < 0 || count < 0)
1474 throw new ArgumentOutOfRangeException();
1476 if (this.document.Length == 0)
1479 int actualCount = count;
1480 if (index + count - 1 > this.document.Length - 1)
1481 actualCount = this.document.Length - index;
1483 string str = this.document.ToString(index, actualCount);
1485 for (int i = 0; i < str.Length; i++) //ToCharArray()だと戻った時に消えてしまう
1488 this.currentIndex = index + actualCount;
1496 /// <param name="disposing">真ならアンマネージドリソースを解放する</param>
1497 protected override void Dispose(bool disposing)
1499 this.document = null;