Access current code pane in Visual Studio Extension
Asked Answered
L

1

14

Im writing a visual studio (2010) extension with a right click menu whilst in a code view. I want to be able to examine the current code from my menu item event handler but havent been able to find somewhere in the object model to do this.

How do i access the code in the current window in a visual studio extension?

EDIT

Heres the code i used to get the current document text

 DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE ;
 TextDocument activeDoc = dte.ActiveDocument.Object() as TextDocument;

 var text = activeDoc.CreateEditPoint(activeDoc.StartPoint).GetText(activeDoc.EndPoint);
Lambency answered 28/1, 2012 at 0:25 Comment(5)
Are you starting from a MEF component? If so do you have an ITextView or do you want to grab the active one?Holograph
@Holograph I think its MPF, i couldn't work out how to use MEF to connect to VS, i just started from the VSPackage template.Lambency
@Holograph Is there an easy 2020 way to get the active view when starting with MEF?Sonorant
Update: It seems like it's possible to implement IWpfTextViewConnectionListener and export it as another interface with IWpfTextView ActiveDocument { get; } property. This property can be set in SubjectBuffersConnected and unset in SubjectBuffersDisconnected.Sonorant
I've created another question and posted a possible solution in the Update 1: How to get active IWpfTextView in VS2019 extension (MEF)Sonorant
P
12

You may be looking for

Document doc = DTE.ActiveDocument;
TextDocument txt = doc.Object() as TextDocument;

You should then be able to edit work with the TextDocument as needed.

Propaedeutic answered 28/1, 2012 at 2:42 Comment(2)
Ok ive gotten the TextDocument, but i cant work out how to get the current code from the documentLambency
There's not much room in comments so I'll just point you to what on MSDN you should be looking at. Look up StartPoint on the Document object, It's a TextPoint which has methods to access CodeElement's. And if you look at CodeElement on MSDN. This example might be useful.Propaedeutic

© 2022 - 2024 — McMap. All rights reserved.