Export custom EditorFormatDefinition at runtime
Asked Answered
B

1

5

In a Visual Studio extension I've built I need to highlight method invocations within the Visual Studio editor. For example:

enter image description here

I would like to use HSV colors to divide up the color spectrum according to to the number of unique invocations.

I can achieve the highlighting if I export each color as its own EditorFormatDefinition:

[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = "red-background")]
[Name("red-background")]
[UserVisible(true)]
[Order(After = Priority.High)]
public sealed class RedBackground : ClassificationFormatDefinition
{
    public RedBackground()
    {
        DisplayName = "red-background";
        BackgroundColor = Colors.Red;
    }
}

However, this requires me to manually set up all the colors I'd like to use ahead of time. Is there a way to export EditorFormatDefinitions at runtime?

Certain registries such at the IContentTypeRegistryService and the IClassificationTypeRegistryService allow one to create new content types and classifications at runtime. Does a similar API exist for EditorFormatDefinitions.

Alternatively, is it possible to dynamically MEF export an EditorFormatDefinition within Visual Studio?

Beerbohm answered 16/9, 2014 at 4:33 Comment(0)
B
7

The solution is to use the IClassificationFormatMapService to request a specific IClassificationFormatMap. We can then request the TextFormattingRunProperties and create a new set of text formatting properties which we can add to the IClassificationFormatMap.

//No reason to use identifier, just a default starting point that works for me.
var identiferClassificationType = registryService.GetClassificationType("identifier");
var classificationType = registryService.CreateClassificationType(name, SpecializedCollections.SingletonEnumerable(identiferClassificationType));
var classificationFormatMap = ClassificationFormatMapService.GetClassificationFormatMap(category: "text");
var identifierProperties = classificationFormatMap
    .GetExplicitTextProperties(identiferClassificationType);

//Now modify the properties
var color = System.Windows.Media.Colors.Yellow;
var newProperties = identifierProperties.SetForeground(color);
classificationFormatMap.AddExplicitTextProperties(classificationType, newProperties);

//Now you can use or return classificationType...

Thanks to Kevin Pilch-Bisson for his help on this one.

Beerbohm answered 18/9, 2014 at 19:33 Comment(3)
Is it possible to change the order at runtime? I mean the functionality that the OrderAttribute provides.Schaeffer
I found this second overload that enables setting priority: IClassificationFormatMap.AddExplicitTextProperties(IClassificationType, TextFormattingRunProperties, IClassificationType)Tandy
Thanks JoshVarty for sharing this. I tested your code and modified your answer to include some context..Detest

© 2022 - 2024 — McMap. All rights reserved.