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?
Asked
Active
Viewed 3,344 times
3 Answers
8
Yes - it is possible, using Microsoft.CodeAnalysis.Formatting.Formatter
:
var formattedResult = Formatter.Format(syntaxNode, workspace);

Wai Ha Lee
- 8,598
- 83
- 57
- 92

pg0xC
- 1,226
- 10
- 20
3
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;
}
0
If you don't have a "workspace", you can use this:
public static string FormatCode(string code, CancellationToken cancelToken = default)
{
return CSharpSyntaxTree.ParseText(code, cancellationToken: cancelToken)
.GetRoot(cancelToken)
.NormalizeWhitespace()
.SyntaxTree
.GetText(cancelToken)
.ToString();
}
If the compiler can't find CSharpSyntaxTree
, add the Microsoft.CodeAnalysis.CSharp NuGet package.

Anders Carstensen
- 2,949
- 23
- 23