How do I replace C # keywords with string lists using Roslyn?
3 answers
I don't know how well this will work, but you can replace the token with ForKeyword
another token ForKeyword
, but this time with your custom text. To do this, you can use CSharpSyntaxRewriter
:
class KeywordRewriter : CSharpSyntaxRewriter
{
public override SyntaxToken VisitToken(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.ForKeyword)
{
return SyntaxFactory.Token(
token.LeadingTrivia, SyntaxKind.ForKeyword, "foobar", "foobar",
token.TrailingTrivia);
}
return token;
}
}
With this rewriter, you can write code like this:
string code = "for (int i=0; i<10; i++){}";
var statement = SyntaxFactory.ParseStatement(code);
var rewrittenStatement = new KeywordRewriter().Visit(statement);
Console.WriteLine(rewrittenStatement);
Which prints what you wanted:
foobar (int i=0; i<10; i++){}
+6
source to share
Just for the record - the following code also worked, but the accepted answer is much more elegant.
foreach (var t in tree.GetCompilationUnitRoot().DescendantTokens())
{
if (t.HasLeadingTrivia)
{
file.Write(t.LeadingTrivia);
}
file.Write(t.IsKind(SyntaxKind.ForKeyword)? "foobar" : t.ToString());
if (t.HasTrailingTrivia)
{
file.Write(t.TrailingTrivia);
}
}
+1
source to share