Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open Visual Studio code editor at given Roslyn SyntaxNode?

Given a SyntaxNode instance, how can I open appropriate source code file and place cursor at position where the node resides?

I'm writing some simple analyzer. I'm able start it on demand and get a syntax node from current cursor position. But I can't figure out how do I get back to editor from result syntax node. I see the node has a Span property but other than that I don't see any info. The Node I want to show can be in some other file that may not be even opened.

I would like to have behavior similar to "go to..." command for the result of my search.

like image 370
Pawcio Avatar asked Jan 20 '26 06:01

Pawcio


1 Answers

I spend whole day on this but finally got it.

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);
}
like image 59
Pawcio Avatar answered Jan 23 '26 01:01

Pawcio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!