static void Format(PolicyContainer policyParent, IEnumerable <string> mimeTypeChain, TextEditor editor, DocumentContext context, int startOffset, int endOffset, bool exact, bool formatLastStatementOnly = false, OptionSet optionSet = null) { TextSpan span; if (exact) { span = new TextSpan(startOffset, endOffset - startOffset); } else { span = new TextSpan(0, endOffset); } var analysisDocument = context.AnalysisDocument; if (analysisDocument == null) { return; } using (var undo = editor.OpenUndoGroup(/*OperationType.Format*/)) { try { var syntaxTree = analysisDocument.GetSyntaxTreeAsync().WaitAndGetResult(default(CancellationToken)); var root = syntaxTree.GetRoot(); if (formatLastStatementOnly) { var token = root.FindToken(endOffset); var tokens = Microsoft.CodeAnalysis.CSharp.Utilities.FormattingRangeHelper.FindAppropriateRange(token); if (tokens.HasValue) { span = new TextSpan(tokens.Value.Item1.SpanStart, editor.CaretOffset - tokens.Value.Item1.SpanStart); } else { var parent = token.Parent; if (parent != null) { span = new TextSpan(parent.FullSpan.Start, editor.CaretOffset - parent.FullSpan.Start); } } } if (optionSet == null) { optionSet = context.GetOptionsAsync().WaitAndGetResult(default(CancellationToken)); } var rules = Formatter.GetDefaultFormattingRules(analysisDocument); var changes = Formatter.GetFormattedTextChanges(root, Roslyn.Utilities.SpecializedCollections.SingletonEnumerable(span), context.RoslynWorkspace, optionSet, rules, default(CancellationToken)); editor.ApplyTextChanges(changes.Where(c => { if (!exact) { return(true); } return(span.Contains(c.Span.Start)); })); } catch (Exception e) { LoggingService.LogError("Error in on the fly formatter", e); } } }
static CodeFixMenuEntry CreateFixAllMenuEntry(TextEditor editor, FixAllState fixState, ref int mnemonic, CancellationToken token) { var provider = fixState?.FixAllProvider; if (provider == null) { return(null); } var doc = editor.DocumentContext; var workspace = doc?.RoslynWorkspace; if (workspace == null) { return(null); } var title = fixState.GetDefaultFixAllTitle(); var label = mnemonic < 0 ? title : CreateLabel(title, ref mnemonic); var item = new CodeFixMenuEntry(label, async delegate { // Task.Run here so we don't end up binding the whole document on popping the menu, also there is no cancellation token support Microsoft.CodeAnalysis.Text.TextChange[] result = await Task.Run(async() => { var context = fixState.CreateFixAllContext(new RoslynProgressTracker(), token); var fix = await provider.GetFixAsync(context); var previewOperations = await fix.GetPreviewOperationsAsync(token); return(await Runtime.RunInMainThread(() => { var engine = Xwt.Toolkit.CurrentEngine; // NativeEngine return engine.Invoke(async() => { using (var dialog = new FixAllPreviewDialog(string.Join(", ", fixState.DiagnosticIds), doc.Name, fixState.Scope, previewOperations, editor)) { await dialog.InitializeEditor(); var parent = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow); var changes = dialog.Run(parent) == Xwt.Command.Apply ? dialog.GetApplicableChanges().ToArray() : Array.Empty <Microsoft.CodeAnalysis.Text.TextChange> (); return changes; } }); })); }); if (result.Length == 0) { return; } editor.ApplyTextChanges(result); }); return(item); }
protected async override Task CorrectIndentingImplementationAsync(TextEditor editor, DocumentContext context, int startLine, int endLine, CancellationToken cancellationToken) { if (editor.IndentationTracker == null) { return; } var startSegment = editor.GetLine(startLine); if (startSegment == null) { return; } var endSegment = startLine != endLine?editor.GetLine(endLine) : startSegment; if (endSegment == null) { return; } try { var document = context.AnalysisDocument; var formattingService = document.GetLanguageService <IEditorFormattingService> (); if (formattingService == null || !formattingService.SupportsFormatSelection) { return; } var formattingRules = new List <IFormattingRule> (); formattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); formattingRules.AddRange(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var root = await document.GetSyntaxRootAsync(cancellationToken); var options = await document.GetOptionsAsync(cancellationToken); var changes = Formatter.GetFormattedTextChanges( root, new TextSpan [] { new TextSpan(startSegment.Offset, endSegment.EndOffset - startSegment.Offset) }, workspace, options, formattingRules, cancellationToken); if (changes == null) { return; } editor.ApplyTextChanges(changes); editor.FixVirtualIndentation(); } catch (Exception e) { LoggingService.LogError("Error while indenting", e); } }
static void Apply_InsertFinalNewline( TextEditor editor, FileConfiguration config) { if (config.InsertFinalNewline == null) { return; } List <TextChange> changes = new List <TextChange>(); Apply_InsertFinalNewline(editor, config, changes); editor.ApplyTextChanges(changes); }
static void Apply_EndOfLine( TextEditor editor, FileConfiguration config) { if (config.EndOfLine == null) { return; } List <TextChange> changes = new List <TextChange>(); for (int i = 1; i < editor.LineCount; ++i) { IDocumentLine line = editor.GetLine(i); Apply_EndOfLine(editor, config, line, changes); } editor.ApplyTextChanges(changes); }
protected override async void OnTheFlyFormatImplementation(TextEditor editor, DocumentContext context, int startOffset, int length) { var doc = context.AnalysisDocument; var formattingService = doc.GetLanguageService <IEditorFormattingService> (); if (formattingService == null || !formattingService.SupportsFormatSelection) { return; } var changes = await formattingService.GetFormattingChangesAsync(doc, new TextSpan (startOffset, length), default(System.Threading.CancellationToken)); if (changes == null) { return; } editor.ApplyTextChanges(changes); editor.FixVirtualIndentation(); }
static void Apply_TrimTrailingWhitespace( TextEditor editor, FileConfiguration config) { if (config.TrimTrailingWhitespace == null) { return; } if (!config.TrimTrailingWhitespace.Value) { return; } List <TextChange> changes = new List <TextChange>(); foreach (IDocumentLine line in editor.GetLines()) { Apply_TrimTrailingWhitespace(editor, line, changes); } editor.ApplyTextChanges(changes); }
internal static void ApplyNewTree(TextEditor editor, int startOffset, bool exact, TextSpan span, Microsoft.CodeAnalysis.SyntaxTree syntaxTree, Microsoft.CodeAnalysis.SyntaxTree newTree) { editor.ApplyTextChanges(newTree.GetChanges(syntaxTree)); }
public override void HandleSpecialSelectionKey(uint unicodeKey) { string start, end; ((SelectionSurroundingProvider)this).GetSelectionSurroundings(unicodeKey, out start, out end); if (editor.SelectionMode == SelectionMode.Block) { var selection = editor.SelectionRegion; int startCol = System.Math.Min(selection.Begin.Column, selection.End.Column) - 1; int endCol = System.Math.Max(selection.Begin.Column, selection.End.Column); int minLine = System.Math.Min(selection.Begin.Line, selection.End.Line); int maxLine = System.Math.Max(selection.BeginLine, selection.End.Line); var changes = new List <TextChange> (); for (int lineNumber = minLine; lineNumber <= maxLine; lineNumber++) { var lineSegment = editor.GetLine(lineNumber); if (lineSegment.Offset + startCol < lineSegment.EndOffset) { changes.Add(new TextChange(new TextSpan(lineSegment.Offset + startCol, 0), start)); } if (lineSegment.Offset + endCol < lineSegment.EndOffset) { changes.Add(new TextChange(new TextSpan(lineSegment.Offset + endCol, 0), end)); } } editor.ApplyTextChanges(changes); // textEditorData.MainSelection = new Selection ( // new DocumentLocation (selection.Anchor.Line, endCol == selection.Anchor.Column ? endCol + start.Length : startCol + 1 + start.Length), // new DocumentLocation (selection.Lead.Line, endCol == selection.Anchor.Column ? startCol + 1 + start.Length : endCol + start.Length), // MonoDevelop.Ide.Editor.SelectionMode.Block); } else { var selectionRange = editor.SelectionRange; int anchorOffset = selectionRange.Offset; int leadOffset = selectionRange.EndOffset; var text = editor.GetTextAt(selectionRange); var formattingService = context.AnalysisDocument.GetLanguageService <IEditorFormattingService> (); if (editor.Options.GenerateFormattingUndoStep) { using (var undo = editor.OpenUndoGroup()) { editor.ReplaceText(selectionRange, start); } using (var undo = editor.OpenUndoGroup()) { editor.ReplaceText(anchorOffset, 1, start + text + end); editor.SetSelection(anchorOffset + start.Length, leadOffset + start.Length + end.Length); } if (unicodeKey == '{') { if (formattingService != null) { var changes = formattingService.GetFormattingChangesAsync(context.AnalysisDocument, TextSpan.FromBounds(anchorOffset + start.Length - 1, leadOffset + start.Length + end.Length), CancellationToken.None).WaitAndGetResult(CancellationToken.None); editor.ApplyTextChanges(changes); } } } else { using (var undo = editor.OpenUndoGroup()) { editor.InsertText(anchorOffset, start); editor.InsertText(leadOffset >= anchorOffset ? leadOffset + start.Length : leadOffset, end); if (unicodeKey == '{') { if (formattingService != null) { var changes = formattingService.GetFormattingChangesAsync(context.AnalysisDocument, TextSpan.FromBounds(anchorOffset + start.Length, leadOffset + start.Length), CancellationToken.None).WaitAndGetResult(CancellationToken.None); editor.ApplyTextChanges(changes); } } else { editor.SetSelection(anchorOffset + start.Length, leadOffset + start.Length + end.Length); } } } } }