question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Formatter ignores NewLine option

See original GitHub issue

Run the code below and notice that neither \r\n is removed, nor that \n is being used.

using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.MSBuild;

namespace Formatting
{
    class Program
    {
        static void Main(string[] args)
        {

            var unformattedCode = @"using System\r\n; namespace HelloWorld{class Program{static void Main(string[]args){Console.WriteLine(""Hello,World!"");}}}";

            var cu = CSharpSyntaxTree.ParseText(unformattedCode);

            var normalizedNode = cu.GetRoot().NormalizeWhitespace("    ");
            var value = normalizedNode.GetText().ToString();
            if (value.IndexOf("\r\n") >= 0)
            {
                Console.WriteLine("normalized? nope");
            }

            var cw = MSBuildWorkspace.Create();
            var options = cw.Options
                .WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, "\n")
                .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, false)
                .WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, 8);

            var formattedNode = Formatter.Format(cu.GetRoot(), cw, options);
            value = formattedNode.GetText().ToString();
            if (value.IndexOf("\r\n") >= 0)
            {
                Console.WriteLine("formatted? nope");
            }

            Console.ReadLine();

        }
    }
}

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:17 (14 by maintainers)

github_iconTop GitHub Comments

2reactions
nosamicommented, Feb 3, 2015

So, we simply need to write a 700 line class to support \n. I see.

0reactions
sonawane-yogeshcommented, Mar 21, 2021

or you could do this:

var newRoot = root.ReplaceTrivia(
    root.DescendantTrivia().Where(t => t.IsKind(SyntaxKind.EndOfLineTrivia)), 
    (t, _) => SyntaxFactory.LineFeed);

That should get most of them, except possibly inside multi-line comments.

Another way from above example.

public static string ReplaceFieldsAndProperties(string programText)
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(programText);
            var compilationRoot = syntaxTree.GetCompilationUnitRoot();
            var propertyNodes = (from field in compilationRoot.DescendantNodes().OfType<PropertyDeclarationSyntax>() select field).ToList();
            if (!propertyNodes.Any()) return programText;
            var syntaxTriviaList = SyntaxFactory.TriviaList(SyntaxFactory.Tab, SyntaxFactory.ElasticTab);
            var withoutProperty = compilationRoot.ReplaceNodes(propertyNodes, (syntax, declarationSyntax) =>
                declarationSyntax.ReplaceTrivia(declarationSyntax.DescendantTrivia()
                        .Where(t => t.IsKind(SyntaxKind.EndOfLineTrivia)
                                    || t.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)
                                    || t.IsKind(SyntaxKind.SingleLineCommentTrivia)), (t, _) => SyntaxFactory.Space)
                    .WithoutLeadingTrivia()
                    .WithLeadingTrivia(syntaxTriviaList)
                    // .WithLeadingTrivia(SyntaxTriviaList.Create(SyntaxFactory.ElasticTab))
                    .WithTrailingTrivia(SyntaxTriviaList.Create(SyntaxFactory.CarriageReturnLineFeed)));
            var formattedPropertyText = withoutProperty.GetText().ToString();
            return formattedPropertyText;
        }
Read more comments on GitHub >

github_iconTop Results From Across the Web

Java Formatter not allowing new line character?
Java Formatter not allowing new line character? ... Only problem is, the output doesn't have newline characters. Doesn't work if I replace "\n" ......
Read more >
a way to ensure formatted code ends with a newline
Is it possible to modify the formatter config file to ensure that the formatter ... Most have options to ignore whitespace (or newlines...
Read more >
C# formatting options - .NET
Learn about the code style options for formatting C# code files. ... The new-line options concern the use of new lines to format...
Read more >
Line Formats (Comparing and Merging Files)
This format ignores whether the line is incomplete; See Incomplete Lines. ' %L '. stands for the contents of the line, including its...
Read more >
Options
Prettier ships with a handful of format options. ... JSX quotes ignore this option – see jsx-single-quote. If the number of quotes outweighs...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found