You're looking for Roslyn's semantic rename engine.
Rename multiple variables in 1 click
Question
I've made a CodeFix who rename a variable if its name doesn't correspond to some laws. By exemple, "int" variable need to begin with an "i". I've made this CodeFix and it works:
public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan
span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var token = root.FindToken(span.Start);
var node = root.FindNode(span);
if (node.IsKind(SyntaxKind.VariableDeclarator))
{
if (node.Parent.Parent is LocalDeclarationStatementSyntax)
{
var Verify = (LocalDeclarationStatementSyntax)node.Parent.Parent;
var Verify2 = (VariableDeclarationSyntax)node.Parent;
if (!Verify.Modifiers.Any(SyntaxKind.ConstKeyword))
{
if (Verify2.Type.ToString() == "int")
{
if (token.IsKind(SyntaxKind.IdentifierToken))
{
var variable = (VariableDeclaratorSyntax)node;
string newName = variable.Identifier.ValueText;
if (newName.Length > 1)
{
newName = char.ToUpper(newName[0]) + newName.Substring(1);
}
var leading = variable.Identifier.LeadingTrivia;
var trailing = variable.Identifier.TrailingTrivia;
VariableDeclaratorSyntax newVariable = variable.WithIdentifier(SyntaxFactory.Identifier(leading, "i" + newName, trailing));
var newRoot = root.ReplaceNode(variable, newVariable);
return new[] { CodeAction.Create("Add 'i'", document.WithSyntaxRoot(newRoot)) };
}
}
}
}
}
return null;
}
So, if I have a code like this one:
int variable = 0;
variable++;
I have a warning and a way to rename the declaration in one click. So the code change like that:
int iVariable = 0;
variable++;
But all the variable who had the name "variable" are not renamed! Visual Studio already have a CodeFix to rename the others variables who were called "variable", but it requires a second operation for the user.
Do you know how a code that I can implement who will rename all the variables directly? If not, is there a way to call the CodeFix that Visual Studio offer?
La solution
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow