c# - 使用 Visual Studio SDK 确定插入符号是否位于注释 block 中

标签 c# .net vb.net visual-studio-extensions visual-studio-sdk

场景


仅当插入符号位于 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/

相关文章:

c# - (C#) 如何根据name字段存值?

c# - Bing map 与 C# 和 MVVM 信息框和图钉绑定(bind)

c# - 如何无异常(exception)地指示失败的操作(多个应用程序域)?

.net - 使用规则集文件引用自定义代码分析规则库

c# - .NET 中是否可以进行被动日志记录?

vb.net - VB.NET 中 TabControl 对齐问题

c# - 建立一个安全库,我想我过度 build 了

c# - 无法将 Excel 文件上传到 Azure 存储 Blob

mysql - 当@variable 被添加到 mysql 查询时,Vb.net/Mysql 抛出 fatal error

c# - 如何在 IntelliSense 中对 Visual Studio 中的函数进行注释?