给定一个 SyntaxNode
实例,如何打开适当的源代码文件并将光标放在节点所在的位置?
我正在编写一些简单的分析器。我可以按需启动它并从当前光标位置获取语法节点。但我不知道如何从结果语法节点返回编辑器。我看到该节点有一个 Span
属性,但除此之外我没有看到任何信息。我想要显示的节点可能位于其他一些甚至可能未打开的文件中。
我希望搜索结果具有类似于“转到...”命令的行为。
最佳答案
我花了一整天的时间,但终于明白了。
private void selectNodeInEditor(SyntaxNode n) {
var cm = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var tm = (IVsTextManager)Package.GetGlobalService(typeof(SVsTextManager));
var ws = (Workspace)cm.GetService<VisualStudioWorkspace>();
var did = ws.CurrentSolution.GetDocumentId(n.SyntaxTree);
ws.OpenDocument(did);
tm.GetActiveView(1, null, out var av);
var sp = n.GetLocation().GetMappedLineSpan().StartLinePosition;
var ep = n.GetLocation().GetMappedLineSpan().EndLinePosition;
av.SetSelection(sp.Line, sp.Character, ep.Line, ep.Character);
}
关于c# - 如何在给定的 Roslyn SyntaxNode 打开 Visual Studio 代码编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326091/