I am using Roslyn to modify the syntax of C# files. Using CSharpSyntaxRewriter, it is very easy to find and replace nodes in the syntax tree. However, the generated code is very ugly and won't even parse in all cases because the syntax nodes I create (using SyntaxFactory) lack even a minimal amount of whitespace trivia. Does Roslyn provide some basic formatting functionality to avoid this or do I have to add trivia manually to each node I create?
Yes - it is possible, using Microsoft.CodeAnalysis.Formatting.Formatter
:
var formattedResult = Formatter.Format(syntaxNode, workspace);
You can see the usage of different Roslyn formatters here in Roslyn source code: https://sourceroslyn.io/#Microsoft.CodeAnalysis.Workspaces/CodeActions/CodeAction.cs,329
internal static async Task<Document> CleanupDocumentAsync(
Document document, CancellationToken cancellationToken)
{
if (document.SupportsSyntaxTree)
{
document = await ImportAdder.AddImportsFromSymbolAnnotationAsync(
document, Simplifier.AddImportsAnnotation, cancellationToken: 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, cancellationToken: cancellationToken).ConfigureAwait(false);
// format any elastic whitespace
document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);
document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false);
}
return document;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With