在自定义 Visual Studio 编辑器中重写字体

本文关键字:重写 字体 编辑器 Studio 自定义 Visual | 更新日期: 2023-09-27 18:32:32

问题在于使VS扩展中的自定义编辑器看起来与当前主题不同。编辑器托管在对话框中,并且应具有与托管对话框定义的相同字体。

编辑器的内容类型定义如下:

[Export]
[Name("MyContent")]
[BaseDefinition("code")]
public static readonly ContentTypeDefinition ExportContentTypeDefinition = null;

并且有一个分类类型定义:

[Export]
[Name("MyContentText")]
[BaseDefinition("text")]
public static readonly ClassificationTypeDefinition MyTextDefinition = null;

分类器提供程序定义如下:

[Export(typeof(IClassifierProvider))]
[ContentType("MyContent")]
public class ClassifierProvider : IClassifierProvider
{
    [Import]
    public IClassificationTypeRegistryService ClassificationTypesRegistry { get; set; }
    public IClassifier GetClassifier(ITextBuffer textBuffer)
    {
        return new Classifier(
            ClassificationTypesRegistry.GetClassificationType("MyContentText"));
    }
}

虽然分类器只为任何快照提供相同的格式:

public class Classifier : IClassifier
{
    private readonly IClassificationType _classificationType;
    public Classifier(IClassificationType classificationType)
    {
        _classificationType = classificationType;
    }
    public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
    {
        return new [] { new ClassificationSpan(span, _classificationType)};
    }
    public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
}
现在,在

代码中,在创建编辑器时,我正在尝试覆盖匹配IClassificationFormatMap的属性:

var contentType = contentTypeRegistryService.GetContentType("MyContent");
var textBuffer = textBufferFactoryService.CreateTextBuffer(initialText, contentType);
var textView = textEditorFactoryService.CreateTextView(textBuffer);
...
var formatMap = classificationFomatMapService
    .GetClassificationFormatMap("MyContentText");
formatMap.DefaultTextProperties = formatMap.DefaultTextProperties
    .SetFontRenderingEmSize(dialog.FontSize)
    .SetTypeface(
        new Typeface(
            dialog.FontFamily,
            dialog.FontStyle,
            dialog.FontWeight,
            dialog.FontStretch));

但是,此更改不会影响我的编辑器实例。

此外,从classificationFomatMapService.GetClassificationFormatMap(ITextView)重载返回的格式图与我上面使用的重载返回的格式图不同。更改另一个格式实例也会影响正在运行的 Visual Studio 实例中的所有代码编辑器,因此我不得不得出结论,尽管我做出了努力,但 textView 以某种方式映射到默认编辑器的分类。

我的问题是:为了控制为自定义内容类型指定的自定义编辑器的文本外观,我应该怎么做?

在自定义 Visual Studio 编辑器中重写字体

我认为你走在正确的道路上,但你需要做一些类似于斜体注释扩展的ViewCreationListener的事情。具体而言,对视图使用 GetClassificationFormatMap(使用基于内容类型的视图创建侦听器(,而不是设置默认文本属性,而是设置分类类型的属性。如您所观察的,格式映射确实会在视图之间共享,因此您不想更改默认值。

您可能需要为该类型提供分类格式定义。也许无论如何都想这样做,只是为了让一些东西出现在字体和颜色中。


对于后代:我不认为GetClassificationFormatMap(String(方法采用ContentType。我手边没有代码了,我根本不记得这是如何工作的,但我认为"外观类别"与内容类型无关。