views:

10

answers:

1

I'm new to building addins for Visual Studio, but have managed to build a simpe tool for VS2010 that does a little text manipulation in the currently active code window. I've got to the point where I need to know the language (VB.Net, C# or whatever) of the current text view.

I have tried to get the filename (so I can look at the extension to determine the language) using the the following code:

IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
int mustHaveFocus = 1;//means true
txtMgr.GetActiveView(mustHaveFocus, null, out currentTextView);

userData = currentTextView as IVsUserData;
if (userData == null)// no text view 
{
    Console.WriteLine("No text view is currently open");
    return;
}

object pathAsObject;
Guid monikerGuid = typeof(IVsUserData).GUID;
userData.GetData(ref monikerGuid, out pathAsObject);
string docPath = (string)pathAsObject;

Unfortunately pathAsObject always returns null. Is there any other way to get the filename / language?

A: 

Looks like this works:

// Get the current text view.
IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
int mustHaveFocus = 1;//means true
txtMgr.GetActiveView(mustHaveFocus, null, out currentTextView);

userData = currentTextView as IVsUserData;
if (userData == null)// no text view 
{
    Console.WriteLine("No text view is currently open");
    return;
}

// In the next 4 statments, I am trying to get access to the editor's view 
object holder;
Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidViewHost, out holder);
viewHost = (IWpfTextViewHost)holder;

// Get a snapshot of the current editor's text.
allText = viewHost.TextView.TextSnapshot.GetText();

// Get the language for the current editor.
string language = viewHost.TextViewtextView.TextDataModel.ContentType.TypeName;

This returns "Basic" for VB.Net, which is exactly what I need to know.

Kramii
Just FYI, you should try to avoid snapshot.GetText(). It's relatively expensive for the buffer to turn itself into one big string (it's stored in a "piece tree", not as a single string under the covers).
Noah Richards
@Noah: Thanks - that's good to know.
Kramii