Reputation: 20474
With Visual Studio SDk 2013, I'm trying to develop a simple extension that intends to modify the selected text to enclose it in a specific XML documentation tag, then, for this task I need to difference whether the programming language of the current project is VB.Net, or it's C#, but ...how?.
But I think is more than that, note that under a C# project we could load an .vb file and its syntax will be recognized by the IDE, and vice versa, then... maybe detecting the current file language instead of the current project language will be better, maybe that complicates the logic to accomplish this?.
Upvotes: 1
Views: 274
Reputation: 23719
First, to be very precise, languages are not associated with projects. By C# project, people mean that the main language is C# and so those CS files are compiled using the C# compiler. Other languages that require different compilers might be used in the project such as XAML. So programmatically speaking, there is no such a thing as the language of a project. Only documents are associated with languages. A document can have at most one language.
The question is now how to get the programming language of a given document? One way is to use the file extension. This does not work because a resource file with extension CS is not a C# file even though it has the same extension.
You suggested using IWpfTextViewHost.TextView.TextDataModel.ContentType.DisplayName
. First of all, the TextView
object could be null
even if a solution is currently open. This happens when first opening a solution but no document gets opened. Second, the TextView
object maintains a history of all open documents and represents the last document that is still open. It does not say anything about the currently active window which may not even contain a document or it may contain a document that does not have a language.
Here is how to get the language of the currently open document if exists:
if (applicationObject.ActiveWindow.Document != null)
{
Document activeDoc = applicationObject.ActiveDocument;
if (activeDoc.Language != null)
{
// The currently active window contains a document that has a language.
}
}
Note that ActiveWindow
and ActiveDocument
are never null
. However, if the currently open window does not contain a document, accessing ActiveDocument
causes an exception to be thrown. That's why you have to perform the null
check. Also note that Intellisense is not provided for infrastructure programming constructs such as Language
used above in the code snippet.
You can get applicationObject
as follows:
applicationObject = (DTE2)GetService(typeof(DTE));
Upvotes: 1