I searched a long time but haven't found anything concrete about this.
I write an Extension for Visual Studio and want to find all Variables/Properties in the ActiveDocument/Code Document in the open Project. Is there an "easy" way to get them or do I need to search for them by myself?
EDIT: I want to gather Information about the Variables in an open Document. At first I want to create a List which I bind to a ListBox where the user can see all used Variables (and method parameters - simply all with the following Syntax "Type VarName"). Later I will give the functionality of translate those variables and edit the document to change to the new language.
I hope I was specific enough about my topic.
EDIT2: Marked Cole Wu - MSFT's Answer as Solution and posted my Solution on Base of Cole Wu - MSFT's Answer.
public void FindVariablesInDoc(EnvDTE.TextDocument haystackDoc) {
var objEditPt = haystackDoc.StartPoint.CreateEditPoint();
var tree = CSharpSyntaxTree.ParseText(objEditPt.GetText(haystackDoc.EndPoint));
var Mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation", syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
var variables = tree.GetRoot().DescendantNodes().Where(v => v is FieldDeclarationSyntax || v is LocalDeclarationStatementSyntax || v is PropertyDeclarationSyntax || v is ParameterSyntax);
}
Is there an "easy" way to get them or do I need to search for them by myself?
you can use roslyn to find all variables in an EnvDTE Document at Runtime, please refer to the following sample code(please install Microsoft.CodeAnalysis via Nuget).
DTE2 dte = this.ServiceProvider.GetService(typeof(DTE)) as DTE2;
EnvDTE.Document doc = dte.ActiveDocument;
EnvDTE.TextDocument tdoc = (EnvDTE.TextDocument)doc.Object("TextDocument");
EnvDTE.EditPoint objEditPt = tdoc.StartPoint.CreateEditPoint();
string text = objEditPt.GetText(tdoc.EndPoint);
SyntaxTree tree = CSharpSyntaxTree.ParseText(text);
IEnumerable<SyntaxNode> nodes = ((CompilationUnitSyntax)tree.GetRoot()).DescendantNodes();
List<LocalDeclarationStatementSyntax> variableDeclarationList = nodes
.OfType<LocalDeclarationStatementSyntax>().ToList();