如何获得标准分类类型的IClassifier

How to get IClassifier for the standard classification type?

本文关键字:类型 IClassifier 分类 标准分 何获得 标准      更新时间:2023-10-16

我有一个MS Visual Studio编辑器的扩展,它为C++添加了一些语法突出显示。

我想确保提供的 SnapshotSpan 具有标准的分类类型("注释")。有几种方法可以做到这一点:

1.我可以手动解析C++代码以查找注释范围。这是我想要使用的最后一个选项:)

2. 我可以使用黑客:

this.colorer = buffer.Properties.PropertyList // <-- buffer is a ITextBuffer
    .Select(p => p.Value as IClassifier) // Get all classifiers someone put into the properies of the current text buffer
    .Where(i => i != null)
    .Where(i => i.GetType().FullName == "Microsoft.VisualC.CppColorer") // <-- Hack
    .FirstOrDefault();

现在我可以通过以下方式使用此着色器(它是C++分类器的内部Microsoft实现):

this.colorer.GetClassificationSpans(span)
    .Where(s => s.ClassificationType.Classification == FormatNames.Comment ||
                s.ClassificationType.Classification == FormatNames.XmlDocComment)

哒哒!我有关于文本缓冲区中注释的信息。如您所知,这是一个黑客,我想避免这种:)

3.我可以尝试(以某种方式)获取标准分类类型的分类器(例如,用于"评论")。


所以我的问题是:这有可能通过分类类型名称获得 IClassifier 吗?

您可以导入IClassifierAggregatorService

[Import]
internal IClassifierAggregatorService classifierAggregatorService = null;

然后遍历ClassificationSpan以检查每个分类范围是否属于 "comment" 类型:

IClassifier classifier = classifierAggregatorService.GetClassifier(textBuffer);
IList<ClassificationSpan> classificationSpanList = _classifier.GetClassificationSpans(span);
foreach (ClassificationSpan classificationSpan in classificationSpanList)
{
    if (classificationSpan.ClassificationType.IsOfType("comment"))
    {
        // ...
    }
}

作为获得IClassifierAggregatorService的替代方法,您可以从IBufferTagAggregatorFactoryService获得ITagAggregator<IClassificationTag>。如果要根据以前的分类添加分类,则特别有用(请参阅此答案)。

看起来没有官方的方法可以做到这一点。所以我自己实现了代码注释的分类器。