Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export custom EditorFormatDefinition at runtime

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?

like image 826
JoshVarty Avatar asked Sep 16 '14 04:09

JoshVarty


1 Answers

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.

like image 59
JoshVarty Avatar answered Oct 05 '22 12:10

JoshVarty