static void ValidateCommonOptions(SyntaxFormattingOptions formattingOptions) { Assert.True(formattingOptions.UseTabs); Assert.Equal(5, formattingOptions.TabSize); Assert.Equal(7, formattingOptions.IndentationSize); Assert.Equal("\r", formattingOptions.NewLine); }
private static async Task TokenFormatWorkerAsync(TestWorkspace workspace, ITextBuffer buffer, int indentationLine, char ch) { var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().First(); var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(); var line = root.GetText().Lines[indentationLine]; var index = line.ToString().LastIndexOf(ch); Assert.InRange(index, 0, int.MaxValue); // get token var position = line.Start + index; var token = root.FindToken(position); var formattingRuleProvider = workspace.Services.GetService <IHostDependentFormattingRuleFactoryService>(); var rules = ImmutableArray.Create(formattingRuleProvider.CreateRule(document, position)).AddRange(Formatter.GetDefaultFormattingRules(document)); var options = new IndentationOptions( await SyntaxFormattingOptions.FromDocumentAsync(document, CancellationToken.None).ConfigureAwait(false), AutoFormattingOptions.Default); var formatter = new CSharpSmartTokenFormatter(options, rules, root); var changes = await formatter.FormatTokenAsync(token, CancellationToken.None); ApplyChanges(buffer, changes); }
public override async Task <Document> RemoveUnnecessaryImportsAsync( Document document, Func <SyntaxNode, bool> predicate, SyntaxFormattingOptions formattingOptions, CancellationToken cancellationToken) { predicate ??= Functions <SyntaxNode> .True; using (Logger.LogBlock(FunctionId.Refactoring_RemoveUnnecessaryImports_CSharp, cancellationToken)) { var unnecessaryImports = await GetCommonUnnecessaryImportsOfAllContextAsync( document, predicate, cancellationToken).ConfigureAwait(false); if (unnecessaryImports == null || unnecessaryImports.Any(import => import.OverlapsHiddenPosition(cancellationToken))) { return(document); } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var oldRoot = (CompilationUnitSyntax)root; var newRoot = (CompilationUnitSyntax) new Rewriter(document, unnecessaryImports, cancellationToken).Visit(oldRoot); cancellationToken.ThrowIfCancellationRequested(); #if CODE_STYLE var provider = GetSyntaxFormatting(); #else var provider = document.Project.Solution.Workspace.Services; #endif var spans = new List <TextSpan>(); AddFormattingSpans(newRoot, spans, cancellationToken); var formattedRoot = Formatter.Format(newRoot, spans, provider, formattingOptions, rules: null, cancellationToken); return(document.WithSyntaxRoot(formattedRoot)); } }
public static async Task <RemoveSuppressionCodeAction> CreateAsync( SuppressionTargetInfo suppressionTargetInfo, Document documentOpt, Project project, Diagnostic diagnostic, AbstractSuppressionCodeFixProvider fixer, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var attribute = diagnostic.GetSuppressionInfo(compilation).Attribute; if (attribute != null) { return(AttributeRemoveAction.Create(attribute, project, diagnostic, fixer)); } else if (documentOpt != null && !SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(diagnostic)) { var options = await SyntaxFormattingOptions.FromDocumentAsync(documentOpt, cancellationToken).ConfigureAwait(false); return(PragmaRemoveAction.Create(suppressionTargetInfo, documentOpt, options, diagnostic, fixer)); } else { return(null); } }
protected override async Task <Document> GetChangedSuppressionDocumentAsync(CancellationToken cancellationToken) { var suppressionsDoc = await GetOrCreateSuppressionsDocumentAsync(cancellationToken).ConfigureAwait(false); var services = suppressionsDoc.Project.Solution.Workspace.Services; var suppressionsRoot = await suppressionsDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var addImportsService = suppressionsDoc.GetRequiredLanguageService <IAddImportsService>(); var options = await SyntaxFormattingOptions.FromDocumentAsync(suppressionsDoc, cancellationToken).ConfigureAwait(false); foreach (var(targetSymbol, diagnostics) in _diagnosticsBySymbol) { foreach (var diagnostic in diagnostics) { Contract.ThrowIfFalse(!diagnostic.IsSuppressed); suppressionsRoot = Fixer.AddGlobalSuppressMessageAttribute( suppressionsRoot, targetSymbol, _suppressMessageAttribute, diagnostic, services, options, addImportsService, cancellationToken); } } var result = suppressionsDoc.WithSyntaxRoot(suppressionsRoot); var final = await CleanupDocumentAsync(result, cancellationToken).ConfigureAwait(false); return(final); }
public async Task <(Document document, SyntaxToken invocationNameToken)> GetFormattedDocumentAsync(CancellationToken cancellationToken) { if (DocumentWithoutFinalFormatting is null) { throw new InvalidOperationException(); } var annotation = new SyntaxAnnotation(); var root = await DocumentWithoutFinalFormatting.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); root = root.ReplaceToken(InvocationNameToken, InvocationNameToken.WithAdditionalAnnotations(annotation)); var annotatedDocument = DocumentWithoutFinalFormatting.WithSyntaxRoot(root); var simplifiedDocument = await Simplifier.ReduceAsync(annotatedDocument, Simplifier.Annotation, optionSet : null, cancellationToken).ConfigureAwait(false); var simplifiedRoot = await simplifiedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var options = await SyntaxFormattingOptions.FromDocumentAsync(DocumentWithoutFinalFormatting, cancellationToken).ConfigureAwait(false); var services = DocumentWithoutFinalFormatting.Project.Solution.Workspace.Services; var formattedDocument = simplifiedDocument.WithSyntaxRoot( Formatter.Format(simplifiedRoot, Formatter.Annotation, services, options, FormattingRules, cancellationToken)); var formattedRoot = await formattedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return(formattedDocument, formattedRoot.GetAnnotatedTokens(annotation).Single()); }
internal static async Task <Document> CleanupDocumentAsync( Document document, CancellationToken cancellationToken) { if (document.SupportsSyntaxTree) { var addImportOptions = await AddImportPlacementOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); document = await ImportAdder.AddImportsFromSymbolAnnotationAsync( document, Simplifier.AddImportsAnnotation, addImportOptions, cancellationToken).ConfigureAwait(false); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); // format any node with explicit formatter annotation document = await Formatter.FormatAsync(document, Formatter.Annotation, formattingOptions, cancellationToken).ConfigureAwait(false); // format any elastic whitespace document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, formattingOptions, cancellationToken).ConfigureAwait(false); document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false); } return(document); }
private static async Task <Document> AddUsingDirectivesAsync( Document document, SyntaxNode root, BaseNamespaceDeclarationSyntax namespaceDeclaration, CancellationToken cancellationToken) { var addImportsService = document.GetRequiredLanguageService <IAddImportsService>(); var removeImportsService = document.GetRequiredLanguageService <IRemoveUnnecessaryImportsService>(); var annotation = new SyntaxAnnotation(); using var _ = ArrayBuilder <UsingDirectiveSyntax> .GetInstance(out var directives); AddUsingDirectives(namespaceDeclaration.Name, annotation, directives); var generator = document.GetRequiredLanguageService <SyntaxGenerator>(); var addImportOptions = await AddImportPlacementOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); var documentWithImportsAdded = document.WithSyntaxRoot(addImportsService.AddImports( compilation: null !, root, contextLocation: null, directives, generator, addImportOptions, cancellationToken)); return(await removeImportsService.RemoveUnnecessaryImportsAsync( documentWithImportsAdded, n => n.HasAnnotation(annotation), formattingOptions, cancellationToken).ConfigureAwait(false)); }
private static async Task <Document> RemoveSortUsingsAsync( Document document, OrganizeUsingsSet organizeUsingsSet, SyntaxFormattingOptions formattingOptions, CancellationToken cancellationToken) { if (organizeUsingsSet.IsRemoveUnusedImportEnabled) { var removeUsingsService = document.GetLanguageService <IRemoveUnnecessaryImportsService>(); if (removeUsingsService != null) { using (Logger.LogBlock(FunctionId.CodeCleanup_RemoveUnusedImports, cancellationToken)) { document = await removeUsingsService.RemoveUnnecessaryImportsAsync(document, formattingOptions, cancellationToken).ConfigureAwait(false); } } } if (organizeUsingsSet.IsSortImportsEnabled) { using (Logger.LogBlock(FunctionId.CodeCleanup_SortImports, cancellationToken)) { document = await Formatter.OrganizeImportsAsync(document, cancellationToken).ConfigureAwait(false); } } return(document); }
/// <summary> /// Clean up the provided spans in the node. /// This will only cleanup stuff that doesn't require semantic information. /// </summary> public static Task <SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray <TextSpan> spans, OptionSet options, HostWorkspaceServices services, ImmutableArray <ICodeCleanupProvider> providers = default, CancellationToken cancellationToken = default) { var cleanupService = services.GetLanguageServices(root.Language).GetRequiredService <ICodeCleanerService>(); var formattingOptions = SyntaxFormattingOptions.Create(options, services, root.Language); return(cleanupService.CleanupAsync(root, spans, formattingOptions, services, providers, cancellationToken)); }
private async Task <Solution> RemoveUnnecessaryImportsAsync( Solution solution, DocumentId sourceDocumentId, DocumentId documentWithMovedTypeId) { var documentWithMovedType = solution.GetRequiredDocument(documentWithMovedTypeId); var documentWithMovedTypeFormattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(documentWithMovedType, CancellationToken).ConfigureAwait(false); var syntaxFacts = documentWithMovedType.GetRequiredLanguageService <ISyntaxFactsService>(); var removeUnnecessaryImports = documentWithMovedType.GetRequiredLanguageService <IRemoveUnnecessaryImportsService>(); // Remove all unnecessary imports from the new document we've created. documentWithMovedType = await removeUnnecessaryImports.RemoveUnnecessaryImportsAsync(documentWithMovedType, documentWithMovedTypeFormattingOptions, CancellationToken).ConfigureAwait(false); solution = solution.WithDocumentSyntaxRoot( documentWithMovedTypeId, await documentWithMovedType.GetRequiredSyntaxRootAsync(CancellationToken).ConfigureAwait(false)); // See which imports we kept around. var rootWithMovedType = await documentWithMovedType.GetRequiredSyntaxRootAsync(CancellationToken).ConfigureAwait(false); var movedImports = rootWithMovedType.DescendantNodes() .Where(syntaxFacts.IsUsingOrExternOrImport) .ToImmutableArray(); // Now remove any unnecessary imports from the original doc that moved to the new doc. var sourceDocument = solution.GetRequiredDocument(sourceDocumentId); var sourceDocumentFormattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(sourceDocument, CancellationToken).ConfigureAwait(false); sourceDocument = await removeUnnecessaryImports.RemoveUnnecessaryImportsAsync( sourceDocument, n => movedImports.Contains(i => syntaxFacts.AreEquivalent(i, n)), sourceDocumentFormattingOptions, CancellationToken).ConfigureAwait(false); return(solution.WithDocumentSyntaxRoot( sourceDocumentId, await sourceDocument.GetRequiredSyntaxRootAsync(CancellationToken).ConfigureAwait(false))); }
/// <summary> /// Clean up the provided spans in the document. /// Optionally you can provide your own options and code cleaners. Otherwise, the default will be used. /// </summary> public static async Task <Document> CleanupAsync(Document document, ImmutableArray <TextSpan> spans, ImmutableArray <ICodeCleanupProvider> providers = default, CancellationToken cancellationToken = default) { var cleanupService = document.GetRequiredLanguageService <ICodeCleanerService>(); var options = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); return(await cleanupService.CleanupAsync(document, spans, options, providers, cancellationToken).ConfigureAwait(false)); }
public static async Task <Document> AddSourceToAsync(Document document, Compilation symbolCompilation, ISymbol symbol, CancellationToken cancellationToken) { var service = document.GetRequiredLanguageService <IMetadataAsSourceService>(); var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); return(await service.AddSourceToAsync(document, symbolCompilation, symbol, formattingOptions, cancellationToken).ConfigureAwait(false)); }
protected override SyntaxNode AddGlobalSuppressMessageAttribute( SyntaxNode newRoot, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic, HostSolutionServices services, SyntaxFormattingOptions options, IAddImportsService addImportsService, CancellationToken cancellationToken) { var compilationRoot = (CompilationUnitSyntax)newRoot; var isFirst = !compilationRoot.AttributeLists.Any(); var attributeName = suppressMessageAttribute.GenerateNameSyntax() .WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); compilationRoot = compilationRoot.AddAttributeLists( CreateAttributeList( targetSymbol, attributeName, diagnostic, isAssemblyAttribute: true, leadingTrivia: default)); if (isFirst && !newRoot.HasLeadingTrivia) { compilationRoot = compilationRoot.WithLeadingTrivia(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)); } return(compilationRoot); }
public static async Task <ImmutableArray <TextChange> > GetFormattingChangesAsync( Document document, char typedChar, int position, DocumentOptionSet documentOptions, CancellationToken cancellationToken) { Contract.ThrowIfFalse(document.Project.Language is LanguageNames.CSharp); var formattingService = document.GetRequiredLanguageService <ISyntaxFormattingService>(); if (!await formattingService.ShouldFormatOnTypedCharacterAsync(document, typedChar, position, cancellationToken).ConfigureAwait(false)) { return(ImmutableArray <TextChange> .Empty); } var services = document.Project.Solution.Workspace.Services; var globalOptions = document.Project.Solution.Workspace.Services.GetRequiredService <ILegacyGlobalOptionsWorkspaceService>(); var indentationOptions = new IndentationOptions( SyntaxFormattingOptions.Create(documentOptions, services, document.Project.Language), globalOptions.GlobalOptions.GetAutoFormattingOptions(document.Project.Language)); return(await formattingService.GetFormattingChangesOnTypedCharacterAsync(document, position, indentationOptions, cancellationToken).ConfigureAwait(false)); }
public async Task <ImmutableArray <TextChange> > GetFormattingChangesOnPasteAsync( Document document, TextSpan textSpan, DocumentOptionSet?documentOptions, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan); var service = document.GetRequiredLanguageService <ISyntaxFormattingService>(); var rules = new List <AbstractFormattingRule>() { new PasteFormattingRule() }; rules.AddRange(service.GetDefaultFormattingRules()); if (documentOptions == null) { var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService <IInferredIndentationService>(); documentOptions = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat : false, cancellationToken : cancellationToken).ConfigureAwait(false); } var formattingOptions = SyntaxFormattingOptions.Create(documentOptions, document.Project.Solution.Workspace.Services, document.Project.Language); var result = service.GetFormattingResult(root, SpecializedCollections.SingletonEnumerable(formattingSpan), formattingOptions, rules, cancellationToken); return(result.GetTextChanges(cancellationToken).ToImmutableArray()); }
private static async Task <SyntaxFormattingOptions> GetOptionsAsync(Document document, CancellationToken cancellationToken) { var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var analyzerConfigOptions = document.Project.AnalyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(tree); return(SyntaxFormattingOptions.Create(analyzerConfigOptions)); }
private static async Task <Document> RemoveUnnecessaryImportsAsync( Document document, CancellationToken cancellationToken) { var service = document.GetLanguageService <IRemoveUnnecessaryImportsService>(); var syntaxFormattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); return(await service.RemoveUnnecessaryImportsAsync(document, syntaxFormattingOptions, cancellationToken).ConfigureAwait(false)); }
// TODO: move to LSP layer public static async Task <IndentationOptions> GetIndentationOptionsAsync(this IGlobalOptionService globalOptions, Document document, CancellationToken cancellationToken) { var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); var autoFormattingOptions = globalOptions.GetAutoFormattingOptions(document.Project.Language); var indentStyle = globalOptions.GetOption(SmartIndent, document.Project.Language); return(new(formattingOptions, autoFormattingOptions, indentStyle)); }
protected SyntaxWrappingOptions( SyntaxFormattingOptions formattingOptions, int wrappingColumn, OperatorPlacementWhenWrappingPreference operatorPlacement) { FormattingOptions = formattingOptions; WrappingColumn = wrappingColumn; OperatorPlacement = operatorPlacement; }
private static void AssertFormat(string expected, SyntaxTree tree, SyntaxFormattingOptions options) { using var workspace = new AdhocWorkspace(); var formattedRoot = Formatter.Format(tree.GetRoot(), workspace.Services, options, CancellationToken.None); var actualFormattedText = formattedRoot.ToFullString(); Assert.Equal(expected, actualFormattedText); }
protected abstract SyntaxNode AddGlobalSuppressMessageAttribute( SyntaxNode newRoot, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic, HostWorkspaceServices services, SyntaxFormattingOptions options, IAddImportsService addImportsService, CancellationToken cancellationToken);
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var newOptions = options as CSharpSyntaxFormattingOptions ?? CSharpSyntaxFormattingOptions.Default; if (_options.NewLines == newOptions.NewLines) { return(this); } return(new BraceCompletionFormattingRule(_indentStyle, newOptions)); }
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var newOptions = options as CSharpSyntaxFormattingOptions ?? CSharpSyntaxFormattingOptions.Default; if (_options.NewLines.HasFlag(NewLinePlacement.BetweenQueryExpressionClauses) == newOptions.NewLines.HasFlag(NewLinePlacement.BetweenQueryExpressionClauses)) { return(this); } return(new QueryExpressionFormattingRule(newOptions)); }
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var newOptions = options as CSharpSyntaxFormattingOptions ?? CSharpSyntaxFormattingOptions.Default; if (_options.Indentation.HasFlag(IndentationPlacement.Braces) == newOptions.Indentation.HasFlag(IndentationPlacement.Braces)) { return(this); } return(new IndentUserSettingsFormattingRule(newOptions)); }
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var newOptions = options as CSharpSyntaxFormattingOptions ?? CSharpSyntaxFormattingOptions.Default; if (_options.SeparateImportDirectiveGroups == newOptions.SeparateImportDirectiveGroups) { return(this); } return(new TokenBasedFormattingRule(newOptions)); }
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var cachedOptions = new CachedOptions(options.Options); if (cachedOptions == _options) { return(this); } return(new TokenBasedFormattingRule(cachedOptions)); }
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var newOptions = options as CSharpSyntaxFormattingOptions ?? CSharpSyntaxFormattingOptions.Default; if (_options.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInObjectCollectionArrayInitializers) == newOptions.NewLines.HasFlag(NewLinePlacement.BeforeOpenBraceInObjectCollectionArrayInitializers)) { return(this); } return(new BraceCompletionFormattingRule(_indentStyle, newOptions)); }
public override AbstractFormattingRule WithOptions(SyntaxFormattingOptions options) { var cachedOptions = new CachedOptions(options.Options); if (cachedOptions == _options) { return(this); } return(new BraceCompletionFormattingRule(_indentStyle, cachedOptions)); }
private CodeShapeAnalyzer(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList) { _context = context; _options = context.Options; _triviaList = triviaList; _indentation = 0; _hasTrailingSpace = false; _lastLineBreakIndex = firstTriviaInTree ? 0 : -1; _touchedNoisyCharacterOnCurrentLine = false; }