public static void HandleAutoformat(ITextView textView, char typedChar) { if (!REditorSettings.AutoFormat) { return; } if (!REditorSettings.FormatScope && typedChar == '}') { return; } SnapshotPoint?rPoint = GetCaretPointInBuffer(textView); if (!rPoint.HasValue) { return; } var document = REditorDocument.FromTextBuffer(textView.TextBuffer); var ast = document.EditorTree.AstRoot; // Make sure we are not formatting damaging the projected range in R Markdown // which looks like ```{r. 'r' should not separate from {. var host = ContainedLanguageHost.GetHost(textView, document.TextBuffer); if (host != null && !host.CanFormatLine(textView, document.TextBuffer, document.TextBuffer.CurrentSnapshot.GetLineNumberFromPosition(rPoint.Value))) { return; } // We don't want to auto-format inside strings if (ast.IsPositionInsideString(rPoint.Value.Position)) { return; } ITextBuffer subjectBuffer = rPoint.Value.Snapshot.TextBuffer; if (typedChar.IsLineBreak()) { // Special case for hitting caret after } and before 'else'. We do want to format // the construct as '} else {' but if user types Enter after } and we auto-format // it will look as if the editor just eats the Enter. Instead, we will not be // autoformatting in this specific case. User can always format either the document // or select the block and reformat it. if (!IsBetweenCurlyAndElse(subjectBuffer, rPoint.Value.Position)) { var scopeStatement = GetFormatScope(textView, subjectBuffer, ast); // Do not format large scope blocks for performance reasons if (scopeStatement != null && scopeStatement.Length < 200) { FormatOperations.FormatNode(textView, subjectBuffer, scopeStatement); } else { FormatOperations.FormatCurrentLine(textView, subjectBuffer); } } } else if (typedChar == ';') { // Verify we are at the end of the string and not in a middle // of another string or inside a statement. ITextSnapshotLine line = subjectBuffer.CurrentSnapshot.GetLineFromPosition(rPoint.Value.Position); int positionInLine = rPoint.Value.Position - line.Start; string lineText = line.GetText(); if (positionInLine >= lineText.TrimEnd().Length) { FormatOperations.FormatCurrentLine(textView, subjectBuffer); } } else if (typedChar == '}') { FormatOperations.FormatCurrentStatement(textView, subjectBuffer, limitAtCaret: true, caretOffset: -1); } }