ElektroStudios ElektroStudios - 1 year ago 115
Vb.net Question

Determine if the caret is in a comment block with Visual Studio SDK


I would like to enable a command in a custom menu only if the caret is in a Xml comment block

''' ... If caret is here, in a Vb.Net Xml comment block.


/// ... If caret is here, in a C# Xml comment block.

Then, a pseudo-code of the expecting results:


private void CmdExample_BeforeQueryStatus(object sender, EventArgs e) {
// Enable this command only if the caret is in a Xml comment block.
((OleMenuCommand)sender).Enabled = IsCaretInXmlComment?();


Private Sub CmdExample_BeforeQueryStatus(ByVal sender As Object, ByVal e As EventArgs) _
Handles cmdExample.BeforeQueryStatus

' Enable this command only if the caret is in a Xml comment block.
DirectCast(sender, OleMenuCommand).Enabled = IsCaretInXmlComment?()

End Sub


Just, how I could do it?. In Vb.Net or C#.


I'm not sure how to do this, so I was in a trial-and-error with the values of the
enum because I seen something similar here, but the
property always throw a


TextPoint tp =

CodeElement2 ce =
CodeElementFromPoint(tp, vsCMElement.vsCMElementOther);


Dim tp As TextPoint =
CType(MyDte.ActiveDocument.Selection, TextSelection).ActivePoint

Dim ce As CodeElement2 =
CodeElementFromPoint(tp, vsCMElement.vsCMElementOther)

I also found this question, however without an illustrative code-example I'm very lost about this.

Answer Source

If you're targeting Visual Studio 2015 or higher, the best way to do this is with Roslyn. With it you can get a syntax tree and then figure out if you're in a comment. If you look at our implementation of IsEntirelyWithinSingleLineDocComment you can see how we do it today. There are already existing questions out there to help you get a syntax tree if you're new to Roslyn.

If you're needing to target versions lower than that, then you're in trouble since Roslyn first shipped in 2012. One common approach is to instead ask for classification information to figure out if something is a comment or not. Classifications are what drives the text coloring you see in the editor. If you get an ITextBuffer for your file, then you can MEF import IClassifierAggregatorService and ask for classifications, and then filter to the doc comment types. Noah Richard's original spell check sample is a good example of how to do this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download