How to prevent _loosing_ indentation (WhiteSpaceTrivia) when rewriting identifier name with CSharpSyntaxRewriter using Roslyn

StackOverflow https://stackoverflow.com/questions/23560089

  •  18-07-2023
  •  | 
  •  

Question

I am implementing a CSharpSyntaxRewriter to rename variable identifiers using Roslyn.

(Please note: the rewrites will run in a context of a command line utility and not a Visual Studio CodeAction)

Please do not recommend to format the whole Document as this is not an option for me: I would like to keep all formatting what was applied in the original document. I would like to "just" rename the identifier and leave all other aspect intact.

The problem with the following code that it completely trims the leading indentation from the lines like this:(to be more correct: I am loosing some parents leading and trailing trivias:

    x = 3;

became to

y= 3;

Note the indentation has gone and the trailing whitespace between the identifier and the assignment operator also.

Here is the code, and the four thing I've tried (inline as comment) without success:

public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax name)
{
    if (someCondition)
    {
        name = name.WithIdentifier(SyntaxFactory.Identifier(GetChangedName(name.Identifier.ValueText)));

        // Try #1: Does the same
        //name = name.Update(SyntaxFactory.Identifier(GetChangedName(name.Identifier.ValueText)));

        // Additional correction tries:
        //name.NormalizeWhitespace(); // Try #2: does nothing
        //name = (IdentifierNameSyntax) Formatter.Format(name, _workspace); // Try #3: does nothing
        //name = name.WithAdditionalAnnotations(Formatter.Annotation); // Try #4: does nothing I suppose because we are not in a VS codeaction
    }

    return name;
}

Thanks in advance

Was it helpful?

Solution

It was easy...

After try #59458 the result arrive:

  name = name
       .WithIdentifier(SyntaxFactory.Identifier(GetChangedName(name.Identifier.ValueText)))
       .WithLeadingTrivia(name.GetLeadingTrivia())
       .WithTrailingTrivia(name.GetTrailingTrivia());

Thanks for all who tried this figure out...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top