The existing Roslyn documentation is very thin so I'm hoping someone knows how to do this, or at least point me in the right direction. I tried a number of things, including the following to format the sourceCode but it didn't work:
var tree = CSharpSyntaxTree.ParseText(soureCode);
var root = (CSharpSyntaxNode)tree.GetRoot();
return root.ToFullString();
Any help in this regard would be greatly appreciated....
If you're just trying to get a pretty-print version of your SyntaxTree
, you can call root.NormalizeWhitespace().ToFullString();
.
NormalizeWhitespace()
is an extension method, so you'll have to add:
using Microsoft.CodeAnalysis;
If you're looking to format the tree in memory, you're probably looking for the Formatter
class. This class has a few different overloads depending on whether you want to format the entire document or just certain spans.
Unfortunately, it requires either a Document
or a Workspace
to format the whitespace. It might be nice if there was an overload that just applied generic formatting rules to a tree.
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