12

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)?

andyp
  • 6,229
  • 3
  • 38
  • 55
Pratik Mehta
  • 1,310
  • 4
  • 15
  • 37

3 Answers3

11

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();
andyp
  • 6,229
  • 3
  • 38
  • 55
  • 2
    You can simply use `MSBuildWorkspace.create()` to format it with the standard settings. You only need the relevant workspace if you want workspace specific formatting settings. – Jeroen Vannevel May 13 '14 at 12:43
  • 1
    Thank you so much andyp and Jeroen for your quick reply. I am using following code: var workspace = MSBuildWorkspace.Create(); var newSyntaxNode = Formatter.Format(syntaxNode, workspace); But getting following error: A first chance exception of type 'System.NotSupportedException' occurred in Microsoft.CodeAnalysis.Workspaces.dll Additional information: The language 'C#' is not supported. – Pratik Mehta May 13 '14 at 21:31
  • Sorry, I've never encountered that error. In what environment are you trying to create the workspace? Console application, Diagnostic..? Did you solve the problem hindering you from creating a workspace mentioned in your earlier [question](http://stackoverflow.com/questions/23624019/msbuildworkspace-create-seems-to-be-not-working-properly)? – andyp May 14 '14 at 18:37
  • 2
    Try `new AdhocWorkspace()` – Pavel Savara Sep 16 '19 at 15:18
3

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.

Contango
  • 76,540
  • 58
  • 260
  • 305
  • 2
    Still relatively straightforward: `using (var workspace = new AdhocWorkspace()) { var syntaxTree = CSharpSyntaxTree.ParseText(myOriginalCode); var formattedNode = Formatter.Format(syntaxTree.GetRoot(), workspace); return formattedNode.ToFullString(); }` – Sören Kuklau Oct 05 '20 at 12:08
0

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);