Pratik Mehta
Pratik Mehta

Reputation: 1352

Code Formatting in Roslyn SDK Preview

In an earlier version (Roslyn CTP), I was using following code to format my generated code and it was working perfectly fine:

SyntaxNode.Format(FormattingOptions.GetDefaultOptions()).GetFormattedRoot()

With the new Roslyn version it no longer does, so what is the equivalent for the above code in the new version (SDK Preview)?

Upvotes: 12

Views: 5283

Answers (3)

Yogesh Sonawane
Yogesh Sonawane

Reputation: 53

I think this will work for you.

            var syntaxTree = CSharpSyntaxTree.ParseText(finalProgramText);
            var compilationRoot = syntaxTree.GetCompilationUnitRoot();

            /*
            MSBuildLocator.RegisterDefaults();
            var workspace = MSBuildWorkspace.Create(); 
            var sharpTree = CSharpSyntaxTree.ParseText(programText);
            var formattedNode = Formatter.Format(sharpTree.GetRoot(), workspace);
            var fullText = formattedNode.ToFullString();
            */
            var nameSpaces = from n in compilationRoot.DescendantNodes().OfType<UsingDirectiveSyntax>() select n;
            var usings = compilationRoot.Usings.AddRange(nameSpaces);
            var propertyNodes = (from field in compilationRoot.DescendantNodes().OfType<PropertyDeclarationSyntax>() select field).ToList();
            var st = new SyntaxTrivia();
            var withoutProperty = compilationRoot.ReplaceNodes(propertyNodes, (syntax, declarationSyntax) => null).NormalizeWhitespace();
            var withoutPropText = withoutProperty.GetText().ToString();
            var tree = CSharpSyntaxTree.ParseText(withoutPropText);
            var root = tree.GetCompilationUnitRoot();
            var commentTrivia = from t in root.DescendantTrivia()
                                where t.IsKind(SyntaxKind.SingleLineCommentTrivia)
                                      || t.IsKind(SyntaxKind.MultiLineCommentTrivia)
                                      || t.IsKind(SyntaxKind.EndRegionDirectiveTrivia)
                                      || t.IsKind(SyntaxKind.RegionDirectiveTrivia)
                                      || t.IsKind(SyntaxKind.PragmaChecksumDirectiveTrivia)
                                      || t.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia)
                                      || t.IsKind(SyntaxKind.PragmaKeyword)
                                      || t.IsKind(SyntaxKind.EmptyStatement)
                                      || t.IsKind(SyntaxKind.XmlComment)
                                      || t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)
                                      || t.IsKind(SyntaxKind.AttributeList)
                                select t;
            var newRoot = root.ReplaceTrivia(commentTrivia, (t1, t2) => st).NormalizeWhitespace();
            var text = newRoot.GetText().ToString();

            var attrTree = CSharpSyntaxTree.ParseText(text);
            var attrRoot = attrTree.GetCompilationUnitRoot();
            var attrList = from a in attrRoot.DescendantNodes().OfType<AttributeListSyntax>() select a;
            var methodList = (from m in attrRoot.DescendantNodes().OfType<MethodDeclarationSyntax>()
                              where m.ExpressionBody != null
                              select m).ToList();
            var normalMethods = (from m in attrRoot.DescendantNodes().OfType<MethodDeclarationSyntax>()
                                 where m.ExpressionBody == null
                                 select m).ToList();
            Console.WriteLine(normalMethods.Count);
            var withoutAttrList = attrRoot.ReplaceNodes(attrList, (syntax, listSyntax) => null).NormalizeWhitespace()
                .GetText().ToString();
            var fieldTree = CSharpSyntaxTree.ParseText(withoutAttrList);
            var fieldRoot = fieldTree.GetCompilationUnitRoot();
            var fieldsList = (from field in fieldRoot.DescendantNodes().OfType<FieldDeclarationSyntax>() select field).ToList();
            var withoutFields = fieldRoot.ReplaceNodes(fieldsList, (syntax, declarationSyntax) => null);

            var plainTextLines = withoutFields.NormalizeWhitespace().GetText().ToString().Split('\n')
                .Where(d => !usings.Any(u => d.Trim('\r', ' ').Equals(u.ToString())) && !string.IsNullOrEmpty(d.Trim('\r', ' '))
                            && !Regex.IsMatch(d.Trim('\r', ' '), @"^([;()\[\]]+)$")
                            ).Select(s => Regex.Replace(s.TrimEnd('\r', '\n', ' '), "\\s+", " ")).ToList();
            Console.WriteLine(plainTextLines); 

Upvotes: 0

Contango
Contango

Reputation: 80282

Roslyn has changed quite a lot since the CTP.

Documentation is now here: https://roslyn.codeplex.com/

Follow the link to https://roslyn.codeplex.com/documentation, click on "Samples and Walkthroughs", then open up the demo solution "FormatSolution - A console application that formats all C# and VB source files in a solution.".

Unfortunately, I don't think its possible to quickly get formatting working any more, as you have to add the code to a new solution.

Upvotes: 3

andyp
andyp

Reputation: 6269

You can format SyntaxNodes using the Microsoft.CodeAnalysis.Formatting.Formatter like this (if you have a workspace):

using Microsoft.CodeAnalysis.Formatting;

var formattedResult = Formatter.Format(syntaxNode, workspace);

EDIT: As Jeroen wrote in a comment, if you don't have a workspace and don't need workspace-specific formatting settings, you can just create one:

var workspace = MSBuildWorkspace.Create();

Upvotes: 12

Related Questions