场景
仅当插入符号位于 Xml 注释 block 中时,我才想在自定义菜单中启用命令
''' ... If caret is here, in a Vb.Net Xml comment block.
或
/// ... If caret is here, in a C# Xml comment block.
然后,预期结果的伪代码:
C#:
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?();
}
VB:
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
问题
只是,我该怎么做呢?在 Vb.Net 或 C# 中。
研究
我不确定如何执行此操作,因此我对 vsCMElement
枚举的值进行了反复试验,因为我看到了类似的内容 here ,但 CodeElement2.Kind
属性始终抛出 NullReferenceException
。
C#:
TextPoint tp =
((TextSelection)MyDte.ActiveDocument.Selection).ActivePoint;
CodeElement2 ce =
MyDte.ActiveDocument.ProjectItem.FileCodeModel.
CodeElementFromPoint(tp, vsCMElement.vsCMElementOther);
VB:
Dim tp As TextPoint =
CType(MyDte.ActiveDocument.Selection, TextSelection).ActivePoint
Dim ce As CodeElement2 =
MyDte.ActiveDocument.ProjectItem.FileCodeModel.
CodeElementFromPoint(tp, vsCMElement.vsCMElementOther)
我还发现了这个 question ,但是如果没有说明性的代码示例,我对此感到非常困惑。
最佳答案
如果您的目标是 Visual Studio 2015 或更高版本,则最好的方法是使用 Roslyn。有了它,你可以获得一个语法树,然后判断你是否在评论中。如果你看看我们的 IsEntirelyWithinSingleLineDocComment 的实现你可以看看我们今天是如何做到的。如果您是 Roslyn 新手,已经存在一些问题可以帮助您获取语法树。
如果您需要定位低于该版本的版本,那么您就会遇到麻烦,因为 Roslyn 于 2012 年首次发布。一种常见的方法是询问分类信息来确定某些内容是否是评论。分类是驱动您在编辑器中看到的文本着色的因素。如果您获得文件的 ITextBuffer
,那么您可以 MEF import IClassifierAggregatorService
并请求分类,然后过滤到文档注释类型。 Noah Richard's original spell check sample这是如何执行此操作的一个很好的示例。
关于c# - 使用 Visual Studio SDK 确定插入符号是否位于注释 block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34222467/