public virtual void IndentLine(TextEditor editor, DocumentLine line) { var document = editor.Document; var lineNumber = line.LineNumber; if (lineNumber > 1) { var previousLine = document.GetLineByNumber(lineNumber - 1); var indentation = DocumentUtilities.GetWhitespaceAfter(document, previousLine.Offset); // copy indentation to line var newIndentation = DocumentUtilities.GetWhitespaceAfter(document, line.Offset); document.Replace(line.Offset, newIndentation.Length, indentation); } }
static void TryIndent(TextEditor editor, int begin, int end) { var currentIndentation = ""; var tagStack = new Stack <string>(); var document = editor.Document; var tab = editor.Options.IndentationString; var nextLine = begin; // in #dev coordinates var wasEmptyElement = false; var lastType = XmlNodeType.XmlDeclaration; using (var stringReader = new StringReader(document.Text)) { var r = new XmlTextReader(stringReader) { XmlResolver = null }; // prevent XmlTextReader from loading external DTDs while (r.Read()) { if (wasEmptyElement) { wasEmptyElement = false; currentIndentation = tagStack.Count == 0 ? "" : tagStack.Pop(); } if (r.NodeType == XmlNodeType.EndElement) { currentIndentation = tagStack.Count == 0 ? "" : tagStack.Pop(); } while (r.LineNumber >= nextLine) { if (nextLine > end) { break; } if (lastType == XmlNodeType.CDATA || lastType == XmlNodeType.Comment) { nextLine++; continue; } // set indentation of 'nextLine' var line = document.GetLineByNumber(nextLine); var lineText = document.GetText(line); string newText; // special case: opening tag has closing bracket on extra line: remove one indentation level if (lineText.Trim() == ">") { newText = tagStack.Peek() + lineText.Trim(); } else { newText = currentIndentation + lineText.Trim(); } document.SmartReplaceLine(line, newText); nextLine++; } if (r.LineNumber > end) { break; } wasEmptyElement = r.NodeType == XmlNodeType.Element && r.IsEmptyElement; string attribIndent = null; if (r.NodeType == XmlNodeType.Element) { tagStack.Push(currentIndentation); if (r.LineNumber < begin) { currentIndentation = DocumentUtilities.GetIndentation(editor.Document, r.LineNumber); } if (r.Name.Length < 16) { attribIndent = currentIndentation + new string(' ', 2 + r.Name.Length); } else { attribIndent = currentIndentation + tab; } currentIndentation += tab; } lastType = r.NodeType; if (r.NodeType == XmlNodeType.Element && r.HasAttributes) { var startLine = r.LineNumber; r.MoveToAttribute(0); // move to first attribute if (r.LineNumber != startLine) { attribIndent = currentIndentation; // change to tab-indentation } r.MoveToAttribute(r.AttributeCount - 1); while (r.LineNumber >= nextLine) { if (nextLine > end) { break; } // set indentation of 'nextLine' var line = document.GetLineByNumber(nextLine); var newText = attribIndent + document.GetText(line).Trim(); document.SmartReplaceLine(line, newText); nextLine++; } } } //r.Close(); } }