Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top