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

时间:2013-09-27 21:47:06

标签: c++ syntax-highlighting visual-studio-sdk

我有一个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();

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

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

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

第3 即可。我可以尝试(以某种方式)获得标准分类类型的分类器(例如,“注释”)。


所以我的问题是:是否可以通过分类类型名称获取IClassifier?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以导入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的替代方法,您可以从ITagAggregator<IClassificationTag>获得IBufferTagAggregatorFactoryService。如果您想根据以前的分类添加分类,请特别有用(请参阅this answer)。