Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an ITextBuffer out of an EnvDTE.Window?

I have a managed syntax highlighter using the new VS extensibility API's and it gives me an ITextBuffer, which is great.

In another part of my extension I am getting a DTE object and attaching to the active window changed event, which gives me an EnvDTE.Window object.

var dte = (EnvDTE.DTE)this.GetService(typeof(EnvDTE.DTE));
dte.Events.WindowEvents.WindowActivated += WindowEvents_WindowActivated;
// ...

private void WindowEvents_WindowActivated(EnvDTE.Window GotFocus, EnvDTE.Window LostFocus)
{
  // ???
  // Profit
}

I would like to get the ITextBuffer out of Window in this method. Can anyone tell me a straight forward way to do that?

like image 819
justin.m.chase Avatar asked Aug 25 '11 03:08

justin.m.chase


1 Answers

The solution I used was to get the Windows path then use it in conjuction with IVsEditorAdaptersFactoryService and VsShellUtilities.

var openWindowPath = Path.Combine(window.Document.Path, window.Document.Name);
var buffer = GetBufferAt(openWindowPath);

and

internal ITextBuffer GetBufferAt(string filePath)
{
  var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
  var editorAdapterFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
  var serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(MetaSharpPackage.OleServiceProvider);

  IVsUIHierarchy uiHierarchy;
  uint itemID;
  IVsWindowFrame windowFrame;
  if (VsShellUtilities.IsDocumentOpen(
    serviceProvider,
    filePath,
    Guid.Empty,
    out uiHierarchy,
    out itemID,
    out windowFrame))
  {
    IVsTextView view = VsShellUtilities.GetTextView(windowFrame);
    IVsTextLines lines;
    if (view.GetBuffer(out lines) == 0)
    {
      var buffer = lines as IVsTextBuffer;
      if (buffer != null)
        return editorAdapterFactoryService.GetDataBuffer(buffer);
    }
  }

  return null;
}
like image 115
justin.m.chase Avatar answered Oct 23 '22 18:10

justin.m.chase