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 /// ドキュメント全体が削除されたことを表す
88 /// 更新タイプを通知するためのイベントデータ
90 public sealed class DocumentUpdateEventArgs : EventArgs
95 public const int EmptyValue = -1;
99 public UpdateType type;
103 public int startIndex;
107 public int removeLength;
111 public int insertLength;
113 /// 更新イベントが発生した行。行が不明な場合や行をまたぐ場合はnullを指定すること。
119 /// <param name="type">更新タイプ</param>
120 /// <param name="startIndex">開始インデックス</param>
121 /// <param name="removeLength">削除された長さ</param>
122 /// <param name="insertLength">追加された長さ</param>
123 /// <param name="row">開始行。nullを指定することができる</param>
124 public DocumentUpdateEventArgs(UpdateType type, int startIndex = EmptyValue, int removeLength = EmptyValue, int insertLength = EmptyValue, int? row = null)
127 this.startIndex = startIndex;
128 this.removeLength = removeLength;
129 this.insertLength = insertLength;
135 /// ドキュメントに更新があったことを伝えるためのデリゲート
137 /// <param name="sender">送信元クラス</param>
138 /// <param name="e">イベントデータ</param>
139 public delegate void DocumentUpdateEventHandler(object sender, DocumentUpdateEventArgs e);
144 /// <remarks>この型のすべてのメソッド・プロパティはスレッドセーフです</remarks>
145 public sealed class Document : IEnumerable<char>, IRandomEnumrator<char>, IDisposable
150 LineToIndexTable _LayoutLines;
151 bool _EnableFireUpdateEvent = true,_UrlMark = false, _DrawLineNumber = false, _HideRuler = true, _RightToLeft = false;
152 LineBreakMethod _LineBreak;
153 int _TabStops, _LineBreakCharCount = 80;
154 bool _ShowFullSpace, _ShowHalfSpace, _ShowTab, _ShowLineBreak,_InsertMode, _HideCaret, _HideLineMarker, _RectSelection;
155 IndentMode _IndentMode;
160 public const int MaximumLineLength = 1000;
173 /// <param name="doc">ドキュメントオブジェクト</param>
174 /// <remarks>docが複製されますが、プロパティは引き継がれません</remarks>
175 public Document(Document doc)
178 this.buffer = new StringBuffer();
180 this.buffer = new StringBuffer(doc.buffer);
181 this.buffer.Update = new DocumentUpdateEventHandler(buffer_Update);
182 this.Update += new DocumentUpdateEventHandler((s, e) => { });
183 this.ChangeFireUpdateEvent += new EventHandler((s, e) => { });
184 this.StatusUpdate += new EventHandler((s, e) => { });
185 this.Markers = new MarkerCollection();
186 this.UndoManager = new UndoManager();
187 this._LayoutLines = new LineToIndexTable(this);
188 this._LayoutLines.SpilitString = (s,e)=> {
189 return this.CreateLineList(e.index, e.length, MaximumLineLength);
191 this._LayoutLines.Clear();
192 this.MarkerPatternSet = new MarkerPatternSet(this._LayoutLines, this.Markers);
193 this.MarkerPatternSet.Updated += WacthDogPattern_Updated;
194 this.Selections = new SelectCollection();
195 this.CaretPostion = new TextPoint();
196 this.HideLineMarker = true;
197 this.SelectGrippers = new GripperRectangle(new Gripper(), new Gripper());
198 this.SelectionChanged += new EventHandler((s, e) => { });
199 this.CaretChanged += (s, e) => { };
200 this.AutoIndentHook += (s, e) => { };
201 this.LineBreakChanged += (s, e) => { };
205 void WacthDogPattern_Updated(object sender, EventArgs e)
207 this._LayoutLines.ClearLayoutCache();
211 /// ダーティフラグ。保存されていなければ真、そうでなければ偽。
220 /// キャレットでの選択の起点となる位置
222 internal int AnchorIndex
231 internal SrcPoint Src
247 /// 補完候補プロセッサーが切り替わったときに発生するイベント
249 public event EventHandler AutoCompleteChanged;
251 AutoCompleteBoxBase _AutoComplete;
255 public AutoCompleteBoxBase AutoComplete
259 return this._AutoComplete;
263 this._AutoComplete = value;
264 if (this.AutoCompleteChanged != null)
265 this.AutoCompleteChanged(this, null);
272 public event ProgressEventHandler LoadProgress;
275 /// ルーラーやキャレット・行番号などの表示すべきものが変化した場合に呼び出される。ドキュメントの内容が変化した通知を受け取り場合はUpdateを使用してください
277 public event EventHandler StatusUpdate;
282 public bool ShowFullSpace
284 get { return this._ShowFullSpace; }
287 if (this._ShowFullSpace == value)
289 this._ShowFullSpace = value;
290 this.StatusUpdate(this, null);
297 public bool ShowHalfSpace
299 get { return this._ShowHalfSpace; }
302 if (this._ShowHalfSpace == value)
304 this._ShowHalfSpace = value;
305 this.StatusUpdate(this, null);
314 get { return this._ShowTab; }
317 if (this._ShowTab == value)
319 this._ShowTab = value;
320 this.StatusUpdate(this, null);
327 public bool ShowLineBreak
329 get { return this._ShowLineBreak; }
332 if (this._ShowLineBreak == value)
334 this._ShowLineBreak = value;
335 this.StatusUpdate(this, null);
342 internal GripperRectangle SelectGrippers
351 public bool RightToLeft {
352 get { return this._RightToLeft; }
355 if (this._RightToLeft == value)
357 this._RightToLeft = value;
358 this.StatusUpdate(this, null);
363 /// 矩形選択モードなら真を返し、そうでない場合は偽を返す
365 public bool RectSelection
369 return this._RectSelection;
373 this._RectSelection = value;
374 this.StatusUpdate(this, null);
381 public IndentMode IndentMode
385 return this._IndentMode;
389 this._IndentMode = value;
390 this.StatusUpdate(this, null);
395 /// ラインマーカーを描くなら偽。そうでなければ真
397 public bool HideLineMarker
401 return this._HideLineMarker;
405 this._HideLineMarker = value;
406 this.StatusUpdate(this, null);
411 /// キャレットを描くなら偽。そうでなければ真
413 public bool HideCaret
417 return this._HideCaret;
421 this._HideCaret = value;
422 this.StatusUpdate(this, null);
427 /// 挿入モードなら真を返し、上書きモードなら偽を返す
429 public bool InsertMode
433 return this._InsertMode;
437 this._InsertMode = value;
438 this.StatusUpdate(this, null);
443 /// ルーラーを表示しないなら真、そうでないなら偽
445 public bool HideRuler
447 get { return this._HideRuler; }
450 if (this._HideRuler == value)
452 this._HideRuler = value;
453 this.LayoutLines.ClearLayoutCache();
454 this.StatusUpdate(this, null);
458 TextPoint _CaretPostion;
460 /// レイアウト行のどこにキャレットがあるかを表す
462 public TextPoint CaretPostion
466 return this._CaretPostion;
470 if(this._CaretPostion != value)
472 this._CaretPostion = value;
473 this.CaretChanged(this, null);
478 internal void SetCaretPostionWithoutEvent(TextPoint value)
480 if (this._CaretPostion != value)
481 this._CaretPostion = value;
487 internal SelectCollection Selections
496 public bool DrawLineNumber
498 get { return this._DrawLineNumber; }
501 if (this._DrawLineNumber == value)
503 this._DrawLineNumber = value;
504 this._LayoutLines.ClearLayoutCache();
505 this.StatusUpdate(this, null);
510 /// URLをハイパーリンクとして表示するなら真。そうでないなら偽
514 get { return this._UrlMark; }
517 if (this._UrlMark == value)
519 this._UrlMark = value;
522 Regex regex = new Regex("(http|https|ftp)(:\\/\\/[-_.!~*\\'()a-zA-Z0-9;\\/?:\\@&=+\\$,%#]+)");
523 this.MarkerPatternSet.Add(MarkerIDs.URL, new RegexMarkerPattern(regex, HilightType.Url, new Color()));
527 this.MarkerPatternSet.Remove(MarkerIDs.URL);
529 this.StatusUpdate(this, null);
536 public event EventHandler LineBreakChanged;
542 /// 変更した場合、呼び出し側で再描写とレイアウトの再構築を行う必要があります
543 /// また、StatusUpdatedではなく、LineBreakChangedイベントが発生します
545 public LineBreakMethod LineBreak
549 return this._LineBreak;
553 if (this._LineBreak == value)
555 this._LineBreak = value;
556 this.LineBreakChanged(this, null);
561 /// 折り返し行う文字数。実際に折り返しが行われる幅はem単位×この値となります
563 /// <remarks>この値を変えた場合、LineBreakChangedイベントが発生します</remarks>
564 public int LineBreakCharCount
568 return this._LineBreakCharCount;
572 if (this._LineBreakCharCount == value)
574 this._LineBreakCharCount = value;
575 this.LineBreakChanged(this, null);
582 /// <remarks>変更した場合、呼び出し側で再描写する必要があります</remarks>
585 get { return this._TabStops; }
587 if (this._TabStops == value)
589 this._TabStops = value;
590 this.StatusUpdate(this, null);
597 public MarkerPatternSet MarkerPatternSet
606 public LineToIndexTable LayoutLines
610 return this._LayoutLines;
617 /// <param name="index">開始インデックス</param>
618 /// <param name="length">長さ</param>
619 /// <param name="lineLimitLength">1行当たりの最大文字数。-1で無制限</param>
620 /// <returns>レイアウト行リスト</returns>
621 internal IList<LineToIndexTableData> CreateLineList(int index, int length, int lineLimitLength = -1)
623 int startIndex = index;
624 int endIndex = index + length - 1;
625 List<LineToIndexTableData> output = new List<LineToIndexTableData>();
627 foreach (Tuple<int, int> range in this.ForEachLines(startIndex, endIndex, lineLimitLength))
629 int lineHeadIndex = range.Item1;
630 int lineLength = range.Item2;
631 char c = this.buffer[lineHeadIndex + lineLength - 1];
632 bool hasNewLine = c == Document.NewLine;
633 output.Add(this.LayoutLines.CreateLineToIndexTableData(lineHeadIndex, lineLength, hasNewLine, null));
636 if (output.Count > 0)
637 output.Last().LineEnd = true;
642 internal void FireUpdate(DocumentUpdateEventArgs e)
644 this.buffer_Update(this.buffer, e);
648 /// ドキュメントが更新された時に呼ばれるイベント
650 public event DocumentUpdateEventHandler Update;
653 /// FireUpdateEventの値が変わったときに呼び出されるイベント
655 public event EventHandler ChangeFireUpdateEvent;
660 public const char NewLine = '\n';
665 public const char EndOfFile = '\u001a';
670 public UndoManager UndoManager
683 return this.buffer.Length;
688 /// 変更のたびにUpdateイベントを発生させるかどうか
690 public bool FireUpdateEvent
694 return this._EnableFireUpdateEvent;
698 this._EnableFireUpdateEvent = value;
699 this.ChangeFireUpdateEvent(this, null);
706 /// <param name="i">インデックス(自然数でなければならない)</param>
707 /// <returns>Char型</returns>
708 public char this[int i]
712 return this.buffer[i];
719 public MarkerCollection Markers
725 internal StringBuffer StringBuffer
736 public bool IsRequestRedraw { get; internal set; }
741 public void RequestRedraw()
743 this.IsRequestRedraw = true;
747 /// レイアウト行が再構成されたときに発生するイベント
749 public event EventHandler PerformLayouted;
751 /// レイアウト行をすべて破棄し、再度レイアウトを行う
753 public void PerformLayout()
755 //単に再構築するだけなので行ダーティフラグは更新してはいけない
756 this.LayoutLines.IsFrozneDirtyFlag = true;
757 this.FireUpdate(new DocumentUpdateEventArgs(UpdateType.Clear, -1, -1, -1));
758 this.FireUpdate(new DocumentUpdateEventArgs(UpdateType.Replace, 0, 0, this.Length));
759 this.LayoutLines.IsFrozneDirtyFlag = false;
760 if (this.PerformLayouted != null)
761 this.PerformLayouted(this, null);
765 /// オードインデントが可能になった時に通知される
768 /// FireUpdateEventの影響を受けます
770 public event AutoIndentHookerHandler AutoIndentHook;
775 public event EventHandler SelectionChanged;
780 public event EventHandler CaretChanged;
785 /// <param name="start"></param>
786 /// <param name="length"></param>
787 /// <remarks>RectSelectionの値によって動作が変わります。真の場合は矩形選択モードに、そうでない場合は行ごとに選択されます</remarks>
788 public void Select(int start, int length)
790 if (this.FireUpdateEvent == false)
791 throw new InvalidOperationException("");
792 if (start < 0 || start + length < 0 || start + length > this.Length)
793 throw new ArgumentOutOfRangeException("startかendが指定できる範囲を超えてます");
795 foreach (Selection sel in this.Selections)
796 this.LayoutLines.ClearLayoutCache(sel.start, sel.length);
797 this.Selections.Clear();
800 int oldStart = start;
802 length = oldStart - start;
804 if (this.RectSelection && length != 0)
806 TextPoint startTextPoint = this.LayoutLines.GetTextPointFromIndex(start);
807 TextPoint endTextPoint = this.LayoutLines.GetTextPointFromIndex(start + length);
808 this.SelectByRectangle(new TextRectangle(startTextPoint, endTextPoint));
809 this.LayoutLines.ClearLayoutCache(start, length);
811 else if (length != 0)
813 this.Selections.Add(Selection.Create(start, length));
814 this.LayoutLines.ClearLayoutCache(start, length);
816 this.SelectionChanged(this, null);
822 /// <param name="tp">開始位置</param>
823 /// <param name="width">桁数</param>
824 /// <param name="height">行数</param>
825 public void Select(TextPoint tp, int width, int height)
827 if (this.FireUpdateEvent == false || !this.RectSelection)
828 throw new InvalidOperationException("");
831 end.row = tp.row + height;
832 end.col = tp.col + width;
834 if (end.row > this.LayoutLines.Count - 1)
835 throw new ArgumentOutOfRangeException("");
837 this.Selections.Clear();
839 this.SelectByRectangle(new TextRectangle(tp, end));
841 this.SelectionChanged(this, null);
844 private void SelectByRectangle(TextRectangle rect)
846 if (this.FireUpdateEvent == false)
847 throw new InvalidOperationException("");
848 if (rect.TopLeft <= rect.BottomRight)
850 for (int i = rect.TopLeft.row; i <= rect.BottomLeft.row; i++)
852 int length = this.LayoutLines.GetLengthFromLineNumber(i);
853 int leftCol = rect.TopLeft.col, rightCol = rect.TopRight.col, lastCol = length;
854 if (length > 0 && this.LayoutLines[i][length - 1] == Document.NewLine)
855 lastCol = length - 1;
858 if (rect.TopLeft.col > lastCol)
860 if (rect.TopRight.col > lastCol)
863 int StartIndex = this.LayoutLines.GetIndexFromTextPoint(new TextPoint(i, leftCol));
864 int EndIndex = this.LayoutLines.GetIndexFromTextPoint(new TextPoint(i, rightCol));
867 sel = Selection.Create(StartIndex, EndIndex - StartIndex);
869 this.Selections.Add(sel);
877 /// <param name="index">探索を開始するインデックス</param>
878 /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
879 public void SelectWord(int index, bool changeAnchor = false)
881 this.SelectSepartor(index, (c) => Util.IsWordSeparator(c), changeAnchor);
887 /// <param name="index">探索を開始するインデックス</param>
888 /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
889 public void SelectLine(int index,bool changeAnchor = false)
891 this.SelectSepartor(index, (c) => c == Document.NewLine, changeAnchor);
895 /// セパレーターで囲まれた範囲内を選択する
897 /// <param name="index">探索を開始するインデックス</param>
898 /// <param name="find_sep_func">セパレーターなら真を返し、そうでないなら偽を返す</param>
899 /// <param name="changeAnchor">選択の起点となるとインデックスを変更するなら真。そうでなければ偽</param>
900 public void SelectSepartor(int index,Func<char,bool> find_sep_func, bool changeAnchor = false)
902 if (this.FireUpdateEvent == false)
903 throw new InvalidOperationException("");
905 if (find_sep_func == null)
906 throw new ArgumentNullException("find_sep_func must not be null");
908 if (this.Length <= 0 || index >= this.Length)
914 while (start > 0 && !find_sep_func(str[start]))
917 if (find_sep_func(str[start]))
921 while (end < this.Length && !find_sep_func(str[end]))
924 this.Select(start, end - start);
927 this.AnchorIndex = start;
931 /// DocumentReaderを作成します
933 /// <returns>DocumentReaderオブジェクト</returns>
934 public DocumentReader CreateReader()
936 return new DocumentReader(this.buffer);
942 /// <param name="id">マーカーID</param>
943 /// <param name="m">設定したいマーカー</param>
944 public void SetMarker(int id,Marker m)
946 if (m.start < 0 || m.start + m.length > this.Length)
947 throw new ArgumentOutOfRangeException("startもしくはendが指定できる範囲を超えています");
949 this.Markers.Add(id,m);
955 /// <param name="id">マーカーID</param>
956 /// <param name="start">開始インデックス</param>
957 /// <param name="length">削除する長さ</param>
958 public void RemoveMarker(int id,int start, int length)
960 if (start < 0 || start + length > this.Length)
961 throw new ArgumentOutOfRangeException("startもしくはendが指定できる範囲を超えています");
963 this.Markers.RemoveAll(id,start, length);
969 /// <param name="id">マーカーID</param>
970 /// <param name="type">削除したいマーカーのタイプ</param>
971 public void RemoveMarker(int id, HilightType type)
973 this.Markers.RemoveAll(id,type);
979 /// <param name="id">マーカーID</param>
980 public void RemoveAllMarker(int id)
982 this.Markers.RemoveAll(id);
986 /// インデックスに対応するマーカーを得る
988 /// <param name="id">マーカーID</param>
989 /// <param name="index">インデックス</param>
990 /// <returns>Marker構造体の列挙子</returns>
991 public IEnumerable<Marker> GetMarkers(int id, int index)
993 if (index < 0 || index > this.Length)
994 throw new ArgumentOutOfRangeException("indexが範囲を超えています");
995 return this.Markers.Get(id,index);
1001 /// <param name="index">開始インデックス</param>
1002 /// <param name="length">長さ</param>
1003 /// <returns>Stringオブジェクト</returns>
1004 public string ToString(int index, int length)
1006 return this.buffer.ToString(index, length);
1010 /// インデックスを開始位置とする文字列を返す
1012 /// <param name="index">開始インデックス</param>
1013 /// <returns>Stringオブジェクト</returns>
1014 public string ToString(int index)
1016 return this.ToString(index, this.buffer.Length - index);
1022 /// <param name="startIndex">開始インデックス</param>
1023 /// <param name="endIndex">終了インデックス</param>
1024 /// <param name="maxCharCount">最大長</param>
1025 /// <returns>行イテレーターが返される</returns>
1026 public IEnumerable<string> GetLines(int startIndex, int endIndex, int maxCharCount = -1)
1028 return this.buffer.GetLines(startIndex, endIndex, maxCharCount);
1031 internal IEnumerable<Tuple<int, int>> ForEachLines(int startIndex, int endIndex, int maxCharCount = -1)
1033 return this.buffer.ForEachLines(startIndex, endIndex, maxCharCount);
1040 /// <param name="s">追加したい文字列</param>
1041 /// <remarks>非同期操作中はこのメソッドを実行することはできません</remarks>
1042 public void Append(string s)
1044 this.Replace(this.buffer.Length, 0, s);
1050 /// <param name="index">開始インデックス</param>
1051 /// <param name="s">追加したい文字列</param>
1052 /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
1053 public void Insert(int index, string s)
1055 this.Replace(index, 0, s);
1061 /// <param name="index">開始インデックス</param>
1062 /// <param name="length">長さ</param>
1063 /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
1064 public void Remove(int index, int length)
1066 this.Replace(index, length, "");
1072 /// <param name="index">開始インデックス</param>
1073 /// <param name="length">長さ</param>
1074 /// <param name="s">文字列</param>
1075 /// <param name="UserInput">ユーザーからの入力として扱うなら真</param>
1076 /// <remarks>読み出し操作中はこのメソッドを実行することはできません</remarks>
1077 public void Replace(int index, int length, string s, bool UserInput = false)
1079 if (index < 0 || index > this.buffer.Length || index + length > this.buffer.Length || length < 0)
1080 throw new ArgumentOutOfRangeException();
1081 if (length == 0 && (s == string.Empty || s == null))
1084 foreach(int id in this.Markers.IDs)
1085 this.RemoveMarker(id,index, length);
1087 ReplaceCommand cmd = new ReplaceCommand(this.buffer, index, length, s);
1088 this.UndoManager.push(cmd);
1091 if (this.FireUpdateEvent && UserInput)
1093 var input_str = string.Empty;
1094 if (s == Document.NewLine.ToString())
1096 else if (s == string.Empty && length > 0)
1098 //入力は終わっているので空文字を渡すが処理の都合で一部文字だけはそのまま渡す
1099 if (this.AutoComplete != null)
1100 this.AutoComplete.ParseInput(input_str);
1101 if (s == Document.NewLine.ToString())
1102 this.AutoIndentHook(this, null);
1109 /// <remarks>Dirtyフラグも同時にクリアーされます</remarks>
1110 /// <remarks>非同期操作中はこのメソッドを実行することはできません</remarks>
1113 this.buffer.Clear();
1118 /// ストリームからドキュメントを非同期的に構築します
1120 /// <param name="fs">IStreamReaderオブジェクト</param>
1121 /// <param name="tokenSource">キャンセルトークン</param>
1122 /// <returns>Taskオブジェクト</returns>
1124 /// 読み取り操作は別スレッドで行われます。
1125 /// また、非同期操作中はこのメソッドを実行することはできません。
1127 public async Task LoadAsync(TextReader fs, CancellationTokenSource tokenSource = null)
1129 if (fs.Peek() == -1)
1132 if (this.LoadProgress != null)
1133 this.LoadProgress(this, new ProgressEventArgs(ProgressState.Start));
1138 this.LayoutLines.IsFrozneDirtyFlag = true;
1139 await this.buffer.LoadAsync(fs, tokenSource);
1143 this.Dirty = false; //ファイルの内容とドキュメントの中身は同じなのでダーティフラグは偽にする
1144 this.PerformLayout();
1145 //これ以降の操作にだけダーティフラグを適用しないとおかしなことになる
1146 this.LayoutLines.IsFrozneDirtyFlag = false;
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)
1163 await this.buffer.LockAsync().ConfigureAwait(false);
1164 StringBuilder line = new StringBuilder();
1165 for (int i = 0; i < this.Length; i++)
1169 if (c == Document.NewLine || i == this.Length - 1)
1171 string str = line.ToString();
1172 str = str.Replace(Document.NewLine.ToString(), fs.NewLine);
1173 await fs.WriteAsync(str).ConfigureAwait(false);
1175 if (tokenSource != null)
1176 tokenSource.Token.ThrowIfCancellationRequested();
1178 System.Threading.Thread.Sleep(10);
1186 this.buffer.UnLock();
1191 /// Find()およびReplaceAll()で使用するパラメーターをセットします
1193 /// <param name="pattern">検索したい文字列</param>
1194 /// <param name="UseRegex">正規表現を使用するなら真</param>
1195 /// <param name="opt">RegexOptions列挙体</param>
1196 public void SetFindParam(string pattern, bool UseRegex, RegexOptions opt)
1200 this.regex = new Regex(pattern, opt);
1202 this.regex = new Regex(Regex.Escape(pattern), opt);
1206 /// 現在の検索パラメーターでWatchDogを生成する
1208 /// <param name="type">ハイライトタイプ</param>
1209 /// <param name="color">色</param>
1210 /// <returns>WatchDogオブジェクト</returns>
1211 public RegexMarkerPattern CreateWatchDogByFindParam(HilightType type,Color color)
1213 if (this.regex == null)
1214 throw new InvalidOperationException("SetFindParam()を呼び出してください");
1215 return new RegexMarkerPattern(this.regex,type,color);
1221 /// <returns>見つかった場合はSearchResult列挙子を返却します</returns>
1222 /// <remarks>見つかったパターン以外を置き換えた場合、正常に動作しないことがあります</remarks>
1223 public IEnumerator<SearchResult> Find()
1225 return this.Find(0, this.Length);
1231 /// <returns>見つかった場合はSearchResult列挙子を返却します</returns>
1232 /// <param name="start">開始インデックス</param>
1233 /// <param name="length">検索する長さ</param>
1234 /// <remarks>見つかったパターン以外を置き換えた場合、正常に動作しないことがあります</remarks>
1235 public IEnumerator<SearchResult> Find(int start, int length)
1237 if (this.regex == null)
1238 throw new InvalidOperationException();
1239 if (start < 0 || start >= this.Length)
1240 throw new ArgumentOutOfRangeException();
1242 int end = start + length - 1;
1244 if(end > this.Length - 1)
1245 throw new ArgumentOutOfRangeException();
1247 StringBuilder line = new StringBuilder();
1248 int oldLength = this.Length;
1249 for (int i = start; i <= end; i++)
1253 if (c == Document.NewLine || i == end)
1255 this.match = this.regex.Match(line.ToString());
1256 while (this.match.Success)
1258 int startIndex = i - line.Length + 1 + this.match.Index;
1259 int endIndex = startIndex + this.match.Length - 1;
1261 yield return new SearchResult(this.match, startIndex, endIndex);
1263 if (this.Length != oldLength) //長さが変わった場合は置き換え後のパターンの終点+1まで戻る
1265 int delta = this.Length - oldLength;
1266 i = endIndex + delta;
1268 oldLength = this.Length;
1272 this.match = this.match.NextMatch();
1280 /// 任意のパターンですべて置き換えます
1282 /// <param name="replacePattern">置き換え後のパターン</param>
1283 /// <param name="groupReplace">グループ置き換えを行うなら真。そうでないなら偽</param>
1284 public void ReplaceAll(string replacePattern,bool groupReplace)
1286 if (this.regex == null)
1287 throw new InvalidOperationException();
1288 ReplaceAllCommand cmd = new ReplaceAllCommand(this.buffer, this.LayoutLines, this.regex, replacePattern, groupReplace);
1289 this.UndoManager.push(cmd);
1296 /// <param name="target">対象となる文字列</param>
1297 /// <param name="pattern">置き換え後の文字列</param>
1298 /// <param name="ci">大文字も文字を区別しないなら真。そうでないなら偽</param>
1300 /// 検索時に大文字小文字を区別します。また、このメソッドでは正規表現を使用することはできません
1302 public void ReplaceAll2(string target, string pattern,bool ci = false)
1304 FastReplaceAllCommand cmd = new FastReplaceAllCommand(this.buffer, this.LayoutLines, target, pattern,ci);
1305 this.UndoManager.push(cmd);
1309 #region IEnumerable<char> メンバー
1314 /// <returns>IEnumeratorオブジェクトを返す</returns>
1315 public IEnumerator<char> GetEnumerator()
1317 return this.buffer.GetEnumerator();
1322 #region IEnumerable メンバー
1324 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
1326 throw new NotImplementedException();
1331 void buffer_Update(object sender, DocumentUpdateEventArgs e)
1335 case UpdateType.Replace:
1338 this._LayoutLines.UpdateAsReplace(e.startIndex, e.removeLength, e.insertLength);
1339 this.Markers.UpdateMarkers(e.startIndex, e.insertLength, e.removeLength);
1343 this._LayoutLines.UpdateLineAsReplace(e.row.Value, e.removeLength, e.insertLength);
1344 this.Markers.UpdateMarkers(this.LayoutLines.GetIndexFromLineNumber(e.row.Value), e.insertLength, e.removeLength);
1347 case UpdateType.Clear:
1348 this._LayoutLines.Clear();
1352 if(this.FireUpdateEvent)
1353 this.Update(this, e);
1356 #region IDisposable Support
1357 private bool disposedValue = false; // 重複する呼び出しを検出するには
1359 void Dispose(bool disposing)
1365 this.buffer.Clear();
1366 this.LayoutLines.Clear();
1369 disposedValue = true;
1376 public void Dispose()
1386 public class SearchResult
1388 private Match Match;
1405 get { return this.Match.Value; }
1409 /// 指定したパターンを置き換えて返す
1411 /// <param name="replacement">置き換える文字列</param>
1412 /// <returns>置き換え後の文字列</returns>
1413 public string Result(string replacement)
1415 return this.Match.Result(replacement);
1421 /// <param name="m">Matchオブジェクト</param>
1422 /// <param name="start">開始インデックス</param>
1423 /// <param name="end">終了インデックス</param>
1424 public SearchResult(Match m, int start,int end)
1435 public class DocumentReader : TextReader
1437 StringBuffer document;
1443 /// <param name="doc"></param>
1444 internal DocumentReader(StringBuffer doc)
1447 throw new ArgumentNullException();
1448 this.document = doc;
1454 /// <returns>文字。取得できない場合は-1</returns>
1455 public override int Peek()
1457 if (this.document == null)
1458 throw new InvalidOperationException();
1459 if (this.currentIndex >= this.document.Length)
1461 return this.document[this.currentIndex];
1465 /// 文字を取得し、イテレーターを一つ進める
1467 /// <returns>文字。取得できない場合は-1</returns>
1468 public override int Read()
1470 int c = this.Peek();
1472 this.currentIndex++;
1477 /// 文字列を読み取りバッファーに書き込む
1479 /// <param name="buffer">バッファー</param>
1480 /// <param name="index">開始インデックス</param>
1481 /// <param name="count">カウント</param>
1482 /// <returns>読み取られた文字数</returns>
1483 public override int Read(char[] buffer, int index, int count)
1485 if (this.document == null)
1486 throw new InvalidOperationException();
1489 throw new ArgumentNullException();
1491 if (this.document.Length < count)
1492 throw new ArgumentException();
1494 if (index < 0 || count < 0)
1495 throw new ArgumentOutOfRangeException();
1497 if (this.document.Length == 0)
1500 int actualCount = count;
1501 if (index + count - 1 > this.document.Length - 1)
1502 actualCount = this.document.Length - index;
1504 string str = this.document.ToString(index, actualCount);
1506 for (int i = 0; i < str.Length; i++) //ToCharArray()だと戻った時に消えてしまう
1509 this.currentIndex = index + actualCount;
1517 /// <param name="disposing">真ならアンマネージドリソースを解放する</param>
1518 protected override void Dispose(bool disposing)
1520 this.document = null;