Пример #1
0
        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);
                }
            }
        }
        async void HandleTextOptionsChanged(object sender, EventArgs e)
        {
            optionSet = await DocumentContext.GetOptionsAsync();

            IStateMachineIndentEngine indentEngine;

            try {
                var csharpIndentEngine = new ICSharpCode.NRefactory6.CSharp.CSharpIndentEngine(optionSet);
                //csharpIndentEngine.EnableCustomIndentLevels = true;
                foreach (var symbol in GetDefinedSymbols(DocumentContext.Project))
                {
                    csharpIndentEngine.DefineSymbol(symbol);
                }
                indentEngine = csharpIndentEngine;
            } catch (Exception ex) {
                LoggingService.LogError("Error while creating the c# indentation engine", ex);
                indentEngine = new ICSharpCode.NRefactory6.CSharp.NullIStateMachineIndentEngine();
            }

            await Runtime.RunInMainThread(delegate {
                try {
                    var editor = Editor;
                    if (editor == null)                     // disposed
                    {
                        return;
                    }
                    stateTracker = new ICSharpCode.NRefactory6.CSharp.CacheIndentEngine(indentEngine);
                    if (DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.Auto)
                    {
                        editor.IndentationTracker = null;
                    }
                    else
                    {
                        editor.IndentationTracker = new CSharpIndentationTracker(editor, DocumentContext);
                    }

                    indentationDisabled = DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.Auto || DefaultSourceEditorOptions.Instance.IndentStyle == IndentStyle.None;
                    if (indentationDisabled)
                    {
                        editor.SetTextPasteHandler(null);
                    }
                    else
                    {
                        editor.SetTextPasteHandler(new CSharpTextPasteHandler(this, optionSet));
                    }
                } catch (Exception ex) {
                    LoggingService.LogError("Error while handling text option change.", ex);
                }
            });
        }
Пример #3
0
        public async Task <string> OutputNode(SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = await DocumentContext.GetOptionsAsync(cancellationToken);

            node = Formatter.Format(node, TypeSystemService.Workspace, options, cancellationToken);

            var    text     = Editor.Text;
            string nodeText = node.ToString();

            text = text.Insert(offset, nodeText);

            var backgroundDocument = DocumentContext.AnalysisDocument.WithText(SourceText.From(text));

            var currentRoot = await backgroundDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            // add formatter & simplifier annotations
            var oldNode = currentRoot.FindNode(TextSpan.FromBounds(offset, offset + nodeText.Length));

            currentRoot = currentRoot.ReplaceNode(oldNode, oldNode.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation));

            // get updated node
            node        = currentRoot.FindNode(TextSpan.FromBounds(offset, offset + nodeText.Length));
            currentRoot = currentRoot.TrackNodes(node);

            backgroundDocument = backgroundDocument.WithSyntaxRoot(currentRoot);
            backgroundDocument = await Formatter.FormatAsync(backgroundDocument, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false);

            backgroundDocument = await Simplifier.ReduceAsync(backgroundDocument, Simplifier.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false);

            var newRoot = await backgroundDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var formattedNode = newRoot.GetCurrentNode(node);

            if (formattedNode == null)
            {
                LoggingService.LogError("Fatal error: Can't find current formatted node in code generator document.");
                return(nodeText);
            }
            return(formattedNode.ToString());
        }
Пример #4
0
 public static OptionSet GetFormattingOptions(this DocumentContext doc)
 {
     return(doc.GetOptionsAsync().WaitAndGetResult(default(CancellationToken)));
 }