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?

JoshVarty
  • 9,066
  • 4
  • 52
  • 80

1 Answers1

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.

JoshVarty
  • 9,066
  • 4
  • 52
  • 80
  • Is it possible to change the order at runtime? I mean the functionality that the OrderAttribute provides. – TDenis Aug 26 '15 at 19:48
  • I found this second overload that enables setting priority: IClassificationFormatMap.AddExplicitTextProperties(IClassificationType, TextFormattingRunProperties, IClassificationType) – sean Aug 07 '17 at 05:24
  • Thanks JoshVarty for sharing this. I tested your code and modified your answer to include some context.. – Goodies Nov 02 '20 at 23:48