Create Visual Studio Theme Specific Syntax Highlig

2020-07-06 04:47发布

I would like to create a Syntax Highlighter in Visual Studio 2012 (and above) that supports different themes (Dark, Light, Blue).

Visual Studio's Editor Classifier project template explains how to create your own colors in the environment using Microsoft.VisualStudio.Text.Classification.ClassificationFormatDefinition. It works fine...

... until you realize that there are different themes in Visual Studio 2012 (and above) and you don't really support them. Your pretty dark blue colored identifiers on the light theme becomes unreadable in a dark themed environment.

To my understanding if you change your ClassificationFormatDefinition in the Tools/Options/Fonts & Colors in a given theme (e.g.: Light) it won't affect the same ClassificationFormatDefinition in a different theme (e.g.: Dark). The colors seem to be independent across different themes.

That is good. But how do I achieve defining the same ClassificationFormatDefinition (e.g.: MyKeywords) that has the same name in all the themes, but provides different colors for them? Just like Visual Studio's own "Identifier", which is default black on the Light theme and default while on the Black theme.

I know about the Microsoft.VisualStudio.PlatformUI.VSColorTheme.ThemeChanged event that allows me to get notified when the color themes are changed. Do I have to use this and somehow get hold of my existing ClassificationFormatDefinition and assign new colors to them based on the new theme? But that also pops a question: will these modified colors be persisted to the environment, i.e. if I restart Visual Studio, will my changes be there the next time in all the different themes.

I haven't found any attribute that would state which theme the ClassificationFormatDefinition supports nor found much helpful article on the subject.

Any help appreciated.

4条回答
beautiful°
2楼-- · 2020-07-06 05:16

This might help you, code from F# Power Tools, seems to be listening to the ThemeChanged event and updating the classifiers - https://github.com/fsprojects/VisualFSharpPowerTools/blob/a7d7aa9dd3d2a90f21c6947867ac7d7163b9f99a/src/FSharpVSPowerTools/SyntaxConstructClassifierProvider.cs

查看更多
仙女界的扛把子
3楼-- · 2020-07-06 05:22

Ok, here's a workaround I've found. It is far from perfect, but it is as good as it gets.

The trick is to use another base definition when you define your own classification type. This will use their default color for the different themes. The important thing is that you must not define your own color in MyKeywordsFormatDefinition because that disables the default behavior when switching between themes. So try to find a base definition that matches your color. Look for predefined Classificatoin Types here: Microsoft.VisualStudio.Language.StandardClassification.PredefinedClassificationTypeNames

internal static class Classifications
{
    // ...
    public const string MyKeyword = "MyKeyword";
    // ...
}

[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = Classifications.MyKeyword)]
[Name("MyKeywords")]
[DisplayName("My Keywords")]
[UserVisible(true)]
internal sealed class MyKeywordsFormatDefinition: ClassificationFormatDefinition
{
    // Don't set the color here, as it will disable the default color supporting themes
}

[Export(typeof(ClassificationTypeDefinition))]
[Name(Classifications.MyKeyword)]
[BaseDefinition(PredefinedClassificationTypeNames.Keyword)]
internal static ClassificationTypeDefinition MyKeywordsTypeDefinition;

I hope it will be useful for some of you. Even maybe help to refine a proper solution when you can actually set your own color without reusing existing color definitions.

查看更多
小情绪 Triste *
4楼-- · 2020-07-06 05:32

I had a similar problem. I've developed a syntax highlighter for the DSL at work. It has two sets of colors - for light and dark themes. I needed a way to switch between these two sets of colors at runtime when VS theme changes.

After some search I found a solution in the F# github in the code responsible for the integration with VS: https://github.com/majocha/visualfsharp/blob/bcd1929828a3c424b464fe2275590f11446b288e/vsintegration/src/FSharp.Editor/Classification/ClassificationDefinitions.fs

The code in F# repo is quite similar to the code from Omer Raviv’s answer. I translated it into C# and get something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Media;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

using DefGuidList = Microsoft.VisualStudio.Editor.DefGuidList;
using VSConstants =  Microsoft.VisualStudio.VSConstants;

//...

internal abstract class EditorFormatBase : ClassificationFormatDefinition, IDisposable
{
    private const string textCategory = "text";
    private readonly string classificationTypeName; 

    protected EditorFormatBase()
    {          
        VSColorTheme.ThemeChanged += VSColorTheme_ThemeChanged;

        //Get string ID which has to be attached with NameAttribute for ClassificationFormatDefinition-derived classes
        Type type = this.GetType();
        classificationTypeName = type.GetCustomAttribute<NameAttribute>()?.Name;      

        if (classificationTypeName != null)
        {
                ForegroundColor = VSColors.GetThemedColor(classificationTypeName);   //Call to my class VSColors which returns correct color for the theme
        }              
    }

    private void VSColorTheme_ThemeChanged(ThemeChangedEventArgs e)
    {


     //Here MyPackage.Instance is a singleton of my extension's Package derived class, it contains references to
     // IClassificationFormatMapService and  
     // IClassificationTypeRegistryService objects
        if (MyPackage.Instance?.ClassificationFormatMapService == null || MyPackage.Instance.ClassificationRegistry == null || classificationTypeName == null)
        {
            return;
        }

        var fontAndColorStorage = 
            ServiceProvider.GlobalProvider.GetService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage;
        var fontAndColorCacheManager = 
            ServiceProvider.GlobalProvider.GetService(typeof(SVsFontAndColorCacheManager)) as IVsFontAndColorCacheManager;

        if (fontAndColorStorage == null || fontAndColorCacheManager == null)
            return;

        Guid guidTextEditorFontCategory = DefGuidList.guidTextEditorFontCategory;
        fontAndColorCacheManager.CheckCache(ref guidTextEditorFontCategory, out int _ );

        if (fontAndColorStorage.OpenCategory(ref guidTextEditorFontCategory, (uint) __FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK)
        {
            //Possibly log warning/error, in F# source it’s ignored           
        }

        Color? foregroundColorForTheme =  VSColors.GetThemedColor(classificationTypeName);  //VSColors is my class which stores colors, GetThemedColor returns color for the theme

        if (foregroundColorForTheme == null)
            return;

        IClassificationFormatMap formatMap = MyPackage.Instance.ClassificationFormatMapService
                              .GetClassificationFormatMap(category: textCategory);

        if (formatMap == null)
            return;

        try
        {
            formatMap.BeginBatchUpdate();
            ForegroundColor = foregroundColorForTheme;
            var myClasType = MyPackage.Instance.ClassificationRegistry
                                                                  .GetClassificationType(classificationTypeName);

            if (myClasType == null)
                return;

            ColorableItemInfo[] colorInfo = new ColorableItemInfo[1];

            if (fontAndColorStorage.GetItem(classificationTypeName, colorInfo) != VSConstants.S_OK)    //comment from F# repo: "we don't touch the changes made by the user"
            {
                var properties = formatMap.GetTextProperties(myClasType);
                var newProperties = properties.SetForeground(ForegroundColor.Value);

                formatMap.SetTextProperties(myClasType, newProperties);
            }                                                                           
        }
        catch (Exception)
        {
            //Log error here, in F# repo there are no catch blocks, only finally block       
        }
        finally
        {
            formatMap.EndBatchUpdate();
        }          
    }

    void IDisposable.Dispose()
    {
        VSColorTheme.ThemeChanged -= VSColorTheme_ThemeChanged;
    }
}

I’ve used the class above as the base class for all my ClassificationFormatDefinition classes.

查看更多
倾城 Initia
5楼-- · 2020-07-06 05:32

There's another, cleaner way using the VsixColorCompiler that ships with the VS SDK.

First, create a ClassificationTypeDefinition and ClassificationFormatDefinition as usual. This will define the default colour in all themes:

public static class MyClassifications
{
    public const string CustomThing = "MyClassifications/CustomThing";

    [Export]
    [Name(CustomThing)]
    public static ClassificationTypeDefinition CustomThingType = null;

    [Export(typeof(EditorFormatDefinition))]
    [ClassificationType(ClassificationTypeNames = CustomThing)]
    [UserVisible(true)]  // Note: must be user-visible to be themed!
    [Name(CustomThing)]
    public sealed class CustomThingFormatDefinition : ClassificationFormatDefinition
    {
        public CustomThingFormatDefinition()
        {
            ForegroundColor = Color.FromRgb(0xFF, 0x22, 0x22);  // default colour in all themes
            DisplayName = "Custom Thing";  // appears in Fonts and Colors options
        }
    }
}

Next, create a colours.xml file. This will allow us to override the colour for specific themes:

<!-- Syntax described here: https://docs.microsoft.com/en-us/visualstudio/extensibility/internals/vsix-color-compiler -->
<Themes>
  <Theme Name="Light" GUID="{de3dbbcd-f642-433c-8353-8f1df4370aba}">
  </Theme>
  <Theme Name="Dark" GUID="{1ded0138-47ce-435e-84ef-9ec1f439b749}">
    <!-- MEF colour overrides for dark theme -->
    <Category Name="MEFColours" GUID="{75A05685-00A8-4DED-BAE5-E7A50BFA929A}">
      <Color Name="MyClassifications/CustomThing">
        <Foreground Type="CT_RAW" Source="FF2222FF" />
      </Color>
    </Category>
  </Theme>
</Themes>

Now edit your .csproj to include a post-build command to compile the XML to a .pkgdef next to your normal package's .pkgdef (VS2015 SDK shown here):

<Target Name="AfterBuild">
  <Message Text="Compiling themed colours..." Importance="high" />
  <Exec Command="&quot;$(VSSDK140Install)\VisualStudioIntegration\Tools\Bin\VsixColorCompiler.exe&quot; /noLogo &quot;$(ProjectDir)colours.xml&quot; &quot;$(OutputPath)\MyPackage.Colours.pkgdef&quot;" />
</Target>

Whenever you make a change, be sure to clear the MEF cache between builds to force it to update. Additionally, the following registry keys may need to be deleted as well:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\FontAndColors\Cache\{75A05685-00A8-4DED-BAE5-E7A50BFA929A}
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0Exp\FontAndColors\Cache\{75A05685-00A8-4DED-BAE5-E7A50BFA929A}
查看更多
登录 后发表回答