Exemplo n.º 1
0
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);

            InitializerExpressionSyntax initializer = root
                                                      .FindNode(context.Span, getInnermostNodeForTie: true)?
                                                      .FirstAncestorOrSelf <InitializerExpressionSyntax>();

            if (initializer == null)
            {
                return;
            }

            if (initializer.IsKind(SyntaxKind.ComplexElementInitializerExpression) &&
                initializer.Parent?.IsKind(SyntaxKind.CollectionInitializerExpression) == true)
            {
                initializer = (InitializerExpressionSyntax)initializer.Parent;
            }

            if (initializer.Expressions.Count > 0 &&
                !initializer.IsKind(SyntaxKind.ComplexElementInitializerExpression) &&
                initializer.Parent?.IsAnyKind(
                    SyntaxKind.ArrayCreationExpression,
                    SyntaxKind.ImplicitArrayCreationExpression,
                    SyntaxKind.ObjectCreationExpression,
                    SyntaxKind.CollectionInitializerExpression) == true)
            {
                if (initializer.IsSingleline(includeExteriorTrivia: false))
                {
                    context.RegisterRefactoring(
                        "Format initializer on multiple lines",
                        cancellationToken => FormatInitializerOnMultipleLinesAsync(
                            context.Document,
                            initializer,
                            cancellationToken));
                }
                else if (initializer.Expressions.All(expression => expression.IsSingleline()))
                {
                    context.RegisterRefactoring(
                        "Format initializer on a single line",
                        cancellationToken => FormatInitializerOnSingleLineAsync(
                            context.Document,
                            initializer,
                            cancellationToken));
                }
            }

            ExpandInitializerRefactoring.Register(context, initializer);
        }