protected override void FormatAndApply(Document document, int position, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);

            var endToken = root.FindToken(position);

            if (endToken.IsMissing)
            {
                return;
            }

            var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);

            if (ranges == null)
            {
                return;
            }

            var startToken = ranges.Value.Item1;

            if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
            {
                return;
            }

            var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var changes = Formatter.GetFormattedTextChanges(root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, document.Project.Solution.Workspace, options,
                                                            rules: null, // use default
                                                            cancellationToken: cancellationToken);

            document.ApplyTextChanges(changes.ToArray(), cancellationToken);
        }
        private async Task <IList <TextChange> > FormatRangeAsync(
            Document document, SyntaxToken endToken, IEnumerable <IFormattingRule> formattingRules,
            CancellationToken cancellationToken)
        {
            if (!IsEndToken(endToken))
            {
                return(SpecializedCollections.EmptyList <TextChange>());
            }

            var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);

            if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
            {
                return(SpecializedCollections.EmptyList <TextChange>());
            }

            if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
            {
                return(SpecializedCollections.EmptyList <TextChange>());
            }

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var formatter = new SmartTokenFormatter(document.Project.Solution.Workspace.Options, formattingRules, (CompilationUnitSyntax)root);

            var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);

            return(changes);
        }
        protected override bool TreatAsReturn(Document document, int position, CancellationToken cancellationToken)
        {
            var root = document.GetSyntaxRootSynchronously(cancellationToken);

            var endToken = root.FindToken(position);

            if (endToken.IsMissing)
            {
                return(false);
            }

            var tokenToLeft = root.FindTokenOnLeftOfPosition(position);
            var startToken  = endToken.GetPreviousToken();

            // case 1:
            //      Consider code like so: try {|}
            //      With auto brace completion on, user types `{` and `Return` in a hurry.
            //      During typing, it is possible that shift was still down and not released after typing `{`.
            //      So we've got an unintentional `shift + enter` and also we have nothing to complete this,
            //      so we put in a newline,
            //      which generates code like so : try { }
            //                                     |
            //      which is not useful as : try {
            //                                  |
            //                               }
            //      To support this, we treat `shift + enter` like `enter` here.
            var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken &&
                                 endToken.Kind() == SyntaxKind.CloseBraceToken &&
                                 tokenToLeft == startToken &&
                                 endToken.Parent.IsKind(SyntaxKind.Block) &&
                                 FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);

            return(afterOpenBrace);
        }
示例#4
0
        async void CompletionWindowManager_WindowClosed(object sender, EventArgs e)
        {
            var document = DocumentContext.AnalysisDocument;

            if (document == null)
            {
                return;
            }
            var caretPosition = Editor.CaretOffset;
            var token         = await CSharpEditorFormattingService.GetTokenBeforeTheCaretAsync(document, caretPosition, default(CancellationToken)).ConfigureAwait(false);

            if (token.IsMissing || !token.Parent.IsKind(SyntaxKind.ElseDirectiveTrivia))
            {
                return;
            }
            var tokenRange = FormattingRangeHelper.FindAppropriateRange(token);

            if (tokenRange == null || !tokenRange.HasValue || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
            {
                return;
            }

            var value = tokenRange.Value;

            using (var undo = Editor.OpenUndoGroup()) {
                OnTheFlyFormatter.Format(Editor, DocumentContext, value.Item1.SpanStart, value.Item2.Span.End, optionSet: optionSet);
            }
        }
        private static async Task <ImmutableArray <TextChange> > FormatRangeAsync(
            Document document,
            OptionSet options,
            SyntaxToken endToken,
            IEnumerable <AbstractFormattingRule> formattingRules,
            CancellationToken cancellationToken)
        {
            if (!IsEndToken(endToken))
            {
                return(ImmutableArray <TextChange> .Empty);
            }

            var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);

            if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
            {
                return(ImmutableArray <TextChange> .Empty);
            }

            if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
            {
                return(ImmutableArray <TextChange> .Empty);
            }

            var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root);

            var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);

            return(changes.ToImmutableArray());
        }
        public void TestAreTwoTokensOnSameLineFalse()
        {
            var root   = SyntaxFactory.ParseSyntaxTree("{Fizz();\nBuzz();}").GetRoot();
            var token1 = root.GetFirstToken();
            var token2 = root.GetLastToken();

            Assert.False(FormattingRangeHelper.AreTwoTokensOnSameLine(token1, token2));
        }
示例#7
0
            protected override AdjustNewLinesOperation GetAdjustNewLinesOperationBetweenMembersAndUsings(
                SyntaxToken token1,
                SyntaxToken token2
                )
            {
                var previousToken = token1;
                var currentToken  = token2;

                // We are not between members or usings if the last token wasn't the end of a statement or if the current token
                // is the end of a scope.
                if (
                    (
                        previousToken.Kind() != SyntaxKind.SemicolonToken &&
                        previousToken.Kind() != SyntaxKind.CloseBraceToken
                    ) ||
                    currentToken.Kind() == SyntaxKind.CloseBraceToken
                    )
                {
                    return(null);
                }

                SyntaxNode previousMember = FormattingRangeHelper.GetEnclosingMember(previousToken);
                SyntaxNode nextMember     = FormattingRangeHelper.GetEnclosingMember(currentToken);

                // Is the previous statement an using directive? If so, treat it like a member to add
                // the right number of lines.
                if (
                    previousToken.Kind() == SyntaxKind.SemicolonToken &&
                    previousToken.Parent.Kind() == SyntaxKind.UsingDirective
                    )
                {
                    previousMember = previousToken.Parent;
                }

                if (previousMember == null || nextMember == null || previousMember == nextMember)
                {
                    return(null);
                }

                // If we have two members of the same kind, we won't insert a blank line
                if (previousMember.Kind() == nextMember.Kind())
                {
                    return(FormattingOperations.CreateAdjustNewLinesOperation(
                               1,
                               AdjustNewLinesOption.ForceLines
                               ));
                }

                // Force a blank line between the two nodes by counting the number of lines of
                // trivia and adding one to it.
                var triviaList = token1.TrailingTrivia.Concat(token2.LeadingTrivia);

                return(FormattingOperations.CreateAdjustNewLinesOperation(
                           GetNumberOfLines(triviaList) + 1,
                           AdjustNewLinesOption.ForceLines
                           ));
            }
        async void FormatOnReturn(CancellationToken cancellationToken = default(CancellationToken))
        {
            var document = DocumentContext.AnalysisDocument;

            if (document == null)
            {
                return;
            }
            var caretPosition = Editor.CaretOffset;
            var token         = await CSharpEditorFormattingService.GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);

            if (token.IsMissing)
            {
                return;
            }

            string text = null;

            if (service.IsInvalidToken(token, ref text))
            {
                return;
            }
            // Check to see if the token is ')' and also the parent is a using statement. If not, bail
            if (CSharpEditorFormattingService.TokenShouldNotFormatOnReturn(token))
            {
                return;
            }
            var tokenRange = FormattingRangeHelper.FindAppropriateRange(token);

            if (tokenRange == null || !tokenRange.HasValue || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
            {
                return;
            }
            var value = tokenRange.Value;

            using (var undo = Editor.OpenUndoGroup()) {
                OnTheFlyFormatter.Format(Editor, DocumentContext, value.Item1.SpanStart, value.Item2.Span.End, optionSet: optionSet);
            }
        }
示例#9
0
 public static bool IsColonInSwitchLabel(this SyntaxToken token)
 {
     return(FormattingRangeHelper.IsColonInSwitchLabel(token));
 }
示例#10
0
        protected void AddBraceSuppressOperations(List <SuppressOperation> list, SyntaxNode node, SyntaxToken lastToken)
        {
            var bracePair = node.GetBracePair();

            if (!bracePair.IsValidBracePair())
            {
                return;
            }

            var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true);

            if (node is MemberDeclarationSyntax memberDeclNode)
            {
                var firstAndLastTokens = memberDeclNode.GetFirstAndLastMemberDeclarationTokensAfterAttributes();
                firstTokenOfNode = firstAndLastTokens.Item1;
            }

            if (node.IsLambdaBodyBlock())
            {
                // include lambda itself.
                firstTokenOfNode = node.Parent.GetFirstToken(includeZeroWidth: true);
            }

            // We may think we have a complete set of braces, but that may not actually be the case
            // due incomplete code.  i.e. we have something like:
            //
            // class C
            // {
            //      int Blah {
            //          get { return blah
            // }
            //
            // In this case the parse will think that the get-accessor is actually on two lines
            // (because it will consume the close curly that more accurately belongs to the class.
            //
            // Now there are different behaviors we want depending on what the user is doing
            // and what we are formatting.  For example, if the user hits semicolon at the end of
            // "blah", then we want to keep the accessor on a single line.  In this scenario we
            // effectively want to ignore the following close curly as it may not be important to
            // this construct in the mind of the user.
            //
            // However, say the user hits semicolon, then hits enter, then types a close curly.
            // In this scenario we would actually want the get-accessor to be formatted over multiple
            // lines.  The difference here is that because the user just hit close-curly here we can
            // consider it as being part of the closest construct and we can consider its placement
            // when deciding if the construct is on a single line.

            var endToken = bracePair.Item2;

            if (lastToken.Kind() != SyntaxKind.CloseBraceToken &&
                lastToken.Kind() != SyntaxKind.EndOfFileToken &&
                !endToken.IsMissing)
            {
                // The user didn't just type the close brace.  So any close brace we have may
                // actually belong to a containing construct.  See if any containers are missing
                // a close brace, and if so, act as if our own close brace is missing.

                if (SomeParentHasMissingCloseBrace(node.Parent))
                {
                    if (node.IsKind(SyntaxKind.Block) && ((BlockSyntax)node).Statements.Count >= 1)
                    {
                        // In the case of a block, see if the first statement is on the same line
                        // as the open curly.  If so then we'll want to consider the end of the
                        // block as the end of the first statement.  i.e. if you have:
                        //
                        //  try { }
                        //  catch { return;     // <-- the end of this block is the end of the return statement.
                        //  Method();
                        var firstStatement = ((BlockSyntax)node).Statements[0];
                        if (FormattingRangeHelper.AreTwoTokensOnSameLine(firstTokenOfNode, firstStatement.GetFirstToken()))
                        {
                            endToken = firstStatement.GetLastToken();
                        }
                    }
                    else
                    {
                        endToken = endToken.GetPreviousToken();
                    }
                }
            }

            // suppress wrapping on whole construct that owns braces and also brace pair itself if
            // it is on same line
            AddSuppressWrappingIfOnSingleLineOperation(list, firstTokenOfNode, endToken);
            AddSuppressWrappingIfOnSingleLineOperation(list, bracePair.Item1, endToken);
        }
        private AdjustNewLinesOperation GetAdjustNewLinesOperationBetweenMembers(SyntaxToken previousToken, SyntaxToken currentToken)
        {
            if (!FormattingRangeHelper.InBetweenTwoMembers(previousToken, currentToken))
            {
                return(null);
            }

            var previousMember = FormattingRangeHelper.GetEnclosingMember(previousToken);
            var nextMember     = FormattingRangeHelper.GetEnclosingMember(currentToken);

            if (previousMember == null || nextMember == null)
            {
                return(null);
            }

            // see whether first non whitespace trivia after before the current member is a comment or not
            var triviaList = currentToken.LeadingTrivia;
            var firstNonWhitespaceTrivia = triviaList.FirstOrDefault(trivia => !IsWhitespace(trivia));

            if (firstNonWhitespaceTrivia.IsRegularOrDocComment())
            {
                // the first one is a comment, add two more lines than existing number of lines
                var numberOfLines = GetNumberOfLines(triviaList);
                var numberOfLinesBeforeComment = GetNumberOfLines(triviaList.Take(triviaList.IndexOf(firstNonWhitespaceTrivia)));
                var addedLines = (numberOfLinesBeforeComment < 1) ? 2 : 1;
                return(CreateAdjustNewLinesOperation(numberOfLines + addedLines, AdjustNewLinesOption.ForceLines));
            }

            // If we have two members of the same kind, we won't insert a blank line if both members
            // have any content (e.g. accessors bodies, non-empty method bodies, etc.).
            if (previousMember.Kind() == nextMember.Kind())
            {
                // Easy cases:
                if (previousMember.Kind() == SyntaxKind.FieldDeclaration ||
                    previousMember.Kind() == SyntaxKind.EventFieldDeclaration)
                {
                    // Ensure that fields and events are each declared on a separate line.
                    return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines));
                }

                // Don't insert a blank line between properties, indexers or events with no accessors
                if (previousMember is BasePropertyDeclarationSyntax previousProperty)
                {
                    var nextProperty = (BasePropertyDeclarationSyntax)nextMember;

                    if (previousProperty?.AccessorList?.Accessors.All(a => a.Body == null) == true &&
                        nextProperty?.AccessorList?.Accessors.All(a => a.Body == null) == true)
                    {
                        return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
                    }
                }

                // Don't insert a blank line between methods with no bodies
                if (previousMember is BaseMethodDeclarationSyntax previousMethod)
                {
                    var nextMethod = (BaseMethodDeclarationSyntax)nextMember;

                    if (previousMethod.Body == null &&
                        nextMethod.Body == null)
                    {
                        return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
                    }
                }
            }

            return(FormattingOperations.CreateAdjustNewLinesOperation(2 /* +1 for member itself and +1 for a blank line*/, AdjustNewLinesOption.ForceLines));
        }
        private static SyntaxNode SimplifyBlock(
            BlockSyntax node,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            if (node.Statements.Count != 1)
            {
                return(node);
            }

            if (!CanHaveEmbeddedStatement(node.Parent))
            {
                return(node);
            }

            switch (optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value)
            {
            case PreferBracesPreference.Always:
            default:
                return(node);

            case PreferBracesPreference.WhenMultiline:
                // Braces are optional in several scenarios for 'when_multiline', but are only automatically removed
                // in a subset of cases where all of the following are met:
                //
                // 1. This is an 'if' statement
                // 1. The 'if' statement does not have an 'else' clause and is not part of a larger 'if'/'else if'/'else' sequence
                // 2. The 'if' statement is not considered multiline
                if (!node.Parent.IsKind(SyntaxKind.IfStatement))
                {
                    // Braces are only removed for 'if' statements
                    return(node);
                }

                if (node.Parent.IsParentKind(SyntaxKind.IfStatement, SyntaxKind.ElseClause))
                {
                    // Braces are not removed from more complicated 'if' sequences
                    return(node);
                }

                if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Statements[0].GetFirstToken(), node.Statements[0].GetLastToken()))
                {
                    // Braces are not removed when the embedded statement is multiline
                    return(node);
                }

                if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Parent.GetFirstToken(), node.GetFirstToken().GetPreviousToken()))
                {
                    // Braces are not removed when the part of the 'if' statement preceding the embedded statement
                    // is multiline.
                    return(node);
                }

                break;

            case PreferBracesPreference.None:
                break;
            }

            return(node.Statements[0]);
        }
        public void TestAreTwoTokensOnSameLineWithEqualTokensWithoutSyntaxTree()
        {
            var token = SyntaxFactory.ParseToken("else");

            Assert.True(FormattingRangeHelper.AreTwoTokensOnSameLine(token, token));
        }
        public void TestAreTwoTokensOnSameLineWithEqualTokens()
        {
            var token = SyntaxFactory.ParseSyntaxTree("else\nFoo();").GetRoot().GetFirstToken();

            Assert.True(FormattingRangeHelper.AreTwoTokensOnSameLine(token, token));
        }