/// <summary> /// Indent according to bracket hierarchy /// </summary> /// <param name="textDocument">The text document to cleanup.</param> internal void InsertIndent(TextDocument textDocument) { TextPoint cursor = textDocument.StartPoint.CreateEditPoint(); IndentSquareBracket bracket = new IndentSquareBracket(cursor.Parent.StartPoint, cursor.Parent.EndPoint, null); bracket.FindBracket(); bracket.Execute(); }
public void FindBracket() { EditPoint EndPoint = null; TextRanges dummy = null; EditPoint StartPoint = Start.CreateEditPoint(); StartPoint.LineDown(); //FindPattern 不能指定结束位置 while (StartPoint.FindPattern(MaximumBracketPattern, StandardFindOptions, ref EndPoint, ref dummy)) { //所以,需要 判读匹配的开始位置是否在,被包含的区间外 if (StartPoint.Line >= End.Line) { break;//在外面,则跳出,转入数组的下一个 } if (StartPoint != null && EndPoint != null) { IndentSquareBracket Child = new IndentSquareBracket(StartPoint, EndPoint, this); StartPoint.StartOfLine(); int LineIndentCount; //当父节区间为空时,取父区间的缩进,否则在父区间的基础上+1,逐级实现缩进 if (Parent == null) { string LineText = StartPoint.GetText(StartPoint.LineLength); string textTemp = LineText.TrimStart('\t'); LineIndentCount = LineText.Length - textTemp.Length;//获取当前的缩进深度 } else { LineIndentCount = IndentCount + 1; } Child.IndentCount = LineIndentCount; Children.Add(Child); //子Bracket递归查找 Child.FindBracket(); } //再从区间的结束位置向后在下一个最大的包含区间 StartPoint = EndPoint; } }
/// <summary> /// 处理缩进 /// </summary> /// <param name="Bracket">一对方括号内容</param> /// <param name="CurrentEditLintPoint">当前行的编辑点</param> private static void HandleIndent(IndentSquareBracket Bracket, EditPoint CurrentEditLintPoint) { //把处理点移动到一行的开始位置 CurrentEditLintPoint.StartOfLine(); //是不是最后的右中括号 ] bool IsEndRightBracket = CurrentEditLintPoint.Line == Bracket.End.Line; string LineText = CurrentEditLintPoint.GetText(CurrentEditLintPoint.LineLength); //整行从开头就被注释,则退出 if (LineText.StartsWith("//")) { return; } //如果这行是以#开头,则退出,针对#if之类的 if (LineText.StartsWith("#")) { return; } //剔除这行最前面的制表符 string CurrentLineText = LineText.TrimStart('\t'); //未处理该行的缩进个数 int OldIndentCount = LineText.Length - CurrentLineText.Length; //中括号之间的内容,应该缩进的个数 int ContentIndentCount = Bracket.IndentCount + (IsEndRightBracket ? 0 : 1); //待处理缩进个数 int IndentCountAbs = Math.Abs(OldIndentCount - ContentIndentCount); //如果小于应该缩进的个数,则添加 if (OldIndentCount < ContentIndentCount) { CurrentEditLintPoint.Indent(null, IndentCountAbs); } //否则取消相应个数 else if (OldIndentCount > ContentIndentCount) { CurrentEditLintPoint.Unindent(null, IndentCountAbs); } }
public IndentSquareBracket(TextPoint start, TextPoint end, IndentSquareBracket parent) { Start = start.CreateEditPoint();//需要创建一个新的,相当于复制,不然后面操作,会影响到其他的 End = end.CreateEditPoint(); Parent = parent; }