Puppy
Puppy

Reputation: 146998

Go to code location in VS extension

I've got a VS editor extension, and when the user performs a certain action, I'd like to send them to a specific location in the code- not unlike Go To Definition or what happens when you click on a stack frame in the debugger.

So far, I used dte.ItemOperations.OpenFile to open the actual file, and I have the relevant ITextDocument, but I don't know how to set the view to the relevant place in the file. It seems like ITextView and IVsTextView and friends have the methods that I need but I'm unsure how to get the instances I need from my ITextDocument.

How can I go to the file and location I want from a VS extension?

Upvotes: 0

Views: 228

Answers (1)

JaredPar
JaredPar

Reputation: 755269

The easiest way to do this is to take the return of ItemOperations.OpenFile and navigate from it to the IWpfTextView

IWpfTextView GetWpfTextViewForDteWindow(
    Window window,
    System.IServiceProvider serviceProvider,
    IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService)
{
    var path = Path.Combine(window.Document.Path, window.Document.Name);

    IVsUIHierarchy vsuiHierarchy;
    uint itemID;
    IVsWindowFrame vsWindowFrame;
    if (VsShellUtilities.IsDocumentOpen(
        serviceProvider,
        path,
        Guid.Empty,
        out vsuiHierarchy,
        out itemID,
        out vsWindowFrame))
    {
        // Note this may have multiple IVsTextView instances associated with it in a split window but 
        // this will retrieve at least one 
        var vsTextView = VsShellUtilities.GetTextView(vsWindowFrame);
        var wpfTextView = vsEditorAdaptersFactoryService.GetWpfTextView(vsTextView);

        return wpfTextView;
    }

    return null;
}

Do note that there is not necessarily a 1-1 mapping between a DTE Window object and ITextView instance. The Window object essentially represents what is visually displayed as a tab and a given tab can contain many ITextView instances. The most common case is when there is a horizontal split in the window. Probably doesn't matter too much for this scenario but wanted to make sure that it got called out

Upvotes: 1

Related Questions