Create Visual Studio Theme Specific Syntax Highlighting - visual-studio

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.

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.

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

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://learn.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=""$(VSSDK140Install)\VisualStudioIntegration\Tools\Bin\VsixColorCompiler.exe" /noLogo "$(ProjectDir)colours.xml" "$(OutputPath)\MyPackage.Colours.pkgdef"" />
</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}

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/dotnet/fsharp/blob/main/vsintegration/src/FSharp.Editor/Classification/ClassificationDefinitions.fs#L121
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.
EDIT: After upgrade to AsyncPackage for newer versions of VS the previous code stopped working. You need to declare MEF imports somewhere else, for example, directly in the inheritor of ClassificationFormatDefinition. Moreover, as was pointed out by #Alessandro there is a subtle bug in the code. If you switch the VS theme and then immediately go to the VS settings "Fonts and colors" section you will see that the default colors values didn't change. They will change after the restart of VS but that's still not ideal. Fortunately, there is a solution (thanks again #Alessandro). You need to call IVsFontAndColorCacheManager's either ClearCache or RefreshCache with a correct guid 75A05685-00A8-4DED-BAE5-E7A50BFA929A which corresponds to MefItems category in Fonts and Colors cache in the registry.
Here is a reference to an article which describes this a bit:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivsfontandcolorcachemanager?view=visualstudiosdk-2019
Unfortunately I can't find any documentation for the guid constant.
UPDATE: After some more research, debugging and adding logging of bad error codes to VS Activity Log I found out the following:
Theme changed handler is called multiple times for a single change
of VS theme
ClearCache returns 0 for the first few calls but after that starts returning bad error codes
RefreshCache always return 0 (at least in my case)
Therefore I replaced the call to ClearCache with the call to RefreshCache.
So, here is an updated example:
internal abstract class EditorFormatBase : ClassificationFormatDefinition, IDisposable
{
private const string TextCategory = "text";
private readonly string _classificationTypeName;
private const string MefItemsGuidString = "75A05685-00A8-4DED-BAE5-E7A50BFA929A";
private Guid _mefItemsGuid = new Guid(MefItemsGuidString);
[Import]
internal IClassificationFormatMapService _classificationFormatMapService = null; //Set via MEF
[Import]
internal IClassificationTypeRegistryService _classificationRegistry = null; // Set via MEF
protected EditorFormatBase()
{
VSColorTheme.ThemeChanged += VSColorTheme_ThemeChanged;
Type type = this.GetType();
_classificationTypeName = type.GetCustomAttribute<NameAttribute>()?.Name;
if (_classificationTypeName != null)
{
ForegroundColor = VSColors.GetThemedColor(_classificationTypeName);
}
}
private void VSColorTheme_ThemeChanged(ThemeChangedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (_classificationFormatMapService == null || _classificationRegistry == null || _classificationTypeName == null)
return;
var fontAndColorStorage = ServiceProvider.GlobalProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>();
var fontAndColorCacheManager = ServiceProvider.GlobalProvider.GetService<SVsFontAndColorCacheManager, IVsFontAndColorCacheManager>();
if (fontAndColorStorage == null || fontAndColorCacheManager == null)
return;
fontAndColorCacheManager.CheckCache(ref _mefItemsGuid, out int _);
if (fontAndColorStorage.OpenCategory(ref _mefItemsGuid, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK)
{
//TODO Log error
}
Color? foregroundColorForTheme = VSColors.GetThemedColor(_classificationTypeName);
if (foregroundColorForTheme == null)
return;
IClassificationFormatMap formatMap = _classificationFormatMapService.GetClassificationFormatMap(category: TextCategory);
if (formatMap == null)
return;
try
{
formatMap.BeginBatchUpdate();
ForegroundColor = foregroundColorForTheme;
var classificationType = _classificationRegistry.GetClassificationType(_classificationTypeName);
if (classificationType == 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(classificationType);
var newProperties = properties.SetForeground(ForegroundColor.Value);
formatMap.SetTextProperties(classificationType, newProperties);
}
}
catch (Exception)
{
//TODO Log error here
}
finally
{
formatMap.EndBatchUpdate();
if (fontAndColorCacheManager.RefreshCache(ref _mefItemsGuid) != VSConstants.S_OK)
{
//TODO Log error here
}
fontAndColorStorage.CloseCategory();
}
}
void IDisposable.Dispose()
{
VSColorTheme.ThemeChanged -= VSColorTheme_ThemeChanged;
}
}
You can determine if you need to use a color suited for the light or dark theme by checking the current background of the code editor. Here is the link to the code I use:
https://github.com/Acumatica/Acuminator/blob/dev/src/Acuminator/Acuminator.Vsix/Coloriser/Constants/VSColors.cs#L82
And here is a more concise snippet from #Alessandro (thanks again!):
var colorBackground = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
Color color = (colorBackground != null && colorBackground.B < 64) ? lightcolor : darkcolor;
You may also create a separate shared ThemeUpdater class which will subscribe to the ThemeChanged event and all ClassificationFormatDefinition derived classes will subscribe to it to make their specific changes on the theme change. This has a performance benefit that you can update all format definitions in a batch and call EndBatchUpdate and RefreshCache/ClearCache only once on theme change.

For Visual Studio 2022, the answer by SENya only works partially or "sometimes": Changing the VS theme will not properly change the colors immediately like 10% of the time. Also, changing the theme from dark to light will quite often appear to work, but after restarting Visual Studio the dark instead of the light colors get used quite often (more than half the time). All of this is non-deterministic.
After some debugging, I understood the problem as follows: Calling IVsFontAndColorCacheManager.ClearCache() deletes the registry key
"Software\Microsoft\VisualStudio\17.0_4d51a943Exp\FontAndColors\Cache\{75A05685-00A8-4DED-BAE5-E7A50BFA929A}\ItemAndFontInfo"
which is the cache of the font and colors. After the custom theme-change function finishes, some other Visual Studio component
sometimes (but not always) immediately updates the font and color cache. I.e. it calls something like fontAndColorStorage.OpenCategory(ref mFontAndColorCategoryGUID, (uint)__FCSTORAGEFLAGS.FCSF_READONLY | (uint)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS).
Note the FCSF_LOADDEFAULTS. This causes Visual Studio to re-create the registry key. However, apparently it does not use the colors from the updated IClassificationFormatMap, but instead the colors set on the ClassificationFormatDefinition itself,
which were not updated. Thus, changing the theme, changes the displayed colors immediately (because the IClassificationFormatMap got updated), but the registry cache ends up with the wrong colors. After a restart of VS, it uses the cached values and therefore ends up with the wrong colors.
By changing the colors also on the ClassificationFormatDefinition instances, the issue appears to be fixed.
Details
In my VSDoxyHighlighter (Github) I adapted the answer by SENya as follows:
First, some helper class to store the default text format:
public class TextProperties
{
public readonly Color? Foreground;
public readonly Color? Background;
public readonly bool IsBold;
public readonly bool IsItalic;
public TextProperties(Color? foreground, Color? background, bool isBold, bool isItalic)
{
Foreground = foreground;
Background = background;
IsBold = isBold;
IsItalic = isItalic;
}
}
Then the main class handling the theme stuff, called DefaultColors:
/// <summary>
/// Manages the default colors and formatting of our classifications, suitable for the current Visual Studio's color theme.
/// Thus, it provides access to the default formatting for the current theme, and also updates them if the theme
/// of Visual Studio is changed by the user.
///
/// Note that the user settings are stored per theme in the registry.
///
/// An instance should be created via MEF.
/// </summary>
[Export]
public class DefaultColors : IDisposable
{
DefaultColors()
{
VSColorTheme.ThemeChanged += VSThemeChanged;
mCurrentTheme = GetCurrentTheme();
}
public void Dispose()
{
if (mDisposed) {
return;
}
mDisposed = true;
VSColorTheme.ThemeChanged -= VSThemeChanged;
}
/// <summary>
/// Returns the default colors for our extension's classifications, as suitable for the current color theme.
/// </summary>
public Dictionary<string, TextProperties> GetDefaultFormattingForCurrentTheme()
{
return GetDefaultFormattingForTheme(mCurrentTheme);
}
public void RegisterFormatDefinition(IFormatDefinition f)
{
mFormatDefinitions.Add(f);
}
private enum Theme
{
Light,
Dark
}
static private Dictionary<string, TextProperties> GetDefaultFormattingForTheme(Theme theme)
{
switch (theme) {
case Theme.Light:
return cLightColors;
case Theme.Dark:
return cDarkColors;
default:
throw new System.Exception("Unknown Theme");
}
}
// Event called by Visual Studio multiple times (!) when the user changes the color theme of Visual Studio.
private void VSThemeChanged(ThemeChangedEventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
var newTheme = GetCurrentTheme();
if (newTheme != mCurrentTheme) {
mCurrentTheme = newTheme; // Important: We indirectly access mCurrentTheme during the update, so set it before.
ThemeChangedImpl();
}
}
// Called when the Visual Studio theme changes. Responsible for switching out the default colors
// of the classifications.
//
// Based on:
// - https://stackoverflow.com/a/48993958/3740047
// - https://github.com/dotnet/fsharp/blob/main/vsintegration/src/FSharp.Editor/Classification/ClassificationDefinitions.fs#L133
// - https://github.com/fsprojects-archive/zzarchive-VisualFSharpPowerTools/blob/master/src/FSharpVSPowerTools/Commands/SymbolClassifiersProvider.cs
private void ThemeChangedImpl()
{
ThreadHelper.ThrowIfNotOnUIThread();
var fontAndColorStorage = ServiceProvider.GlobalProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>();
var fontAndColorCacheManager = ServiceProvider.GlobalProvider.GetService<SVsFontAndColorCacheManager, IVsFontAndColorCacheManager>();
fontAndColorCacheManager.CheckCache(ref mFontAndColorCategoryGUID, out int _);
if (fontAndColorStorage.OpenCategory(ref mFontAndColorCategoryGUID, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK) {
throw new System.Exception("Failed to open font and color registry.");
}
IClassificationFormatMap formatMap = mClassificationFormatMapService.GetClassificationFormatMap(category: "text");
try {
formatMap.BeginBatchUpdate();
ColorableItemInfo[] colorInfo = new ColorableItemInfo[1];
foreach (var p in GetDefaultFormattingForTheme(mCurrentTheme)) {
string classificationTypeId = p.Key;
TextProperties newColor = p.Value;
if (fontAndColorStorage.GetItem(classificationTypeId, colorInfo) != VSConstants.S_OK) { //comment from F# repo: "we don't touch the changes made by the user"
IClassificationType classificationType = mClassificationTypeRegistryService.GetClassificationType(classificationTypeId);
var oldProp = formatMap.GetTextProperties(classificationType);
var oldTypeface = oldProp.Typeface;
var foregroundBrush = newColor.Foreground == null ? null : new SolidColorBrush(newColor.Foreground.Value);
var backgroundBrush = newColor.Background == null ? null : new SolidColorBrush(newColor.Background.Value);
var newFontStyle = newColor.IsItalic ? FontStyles.Italic : FontStyles.Normal;
var newWeight = newColor.IsBold ? FontWeights.Bold : FontWeights.Normal;
var newTypeface = new Typeface(oldTypeface.FontFamily, newFontStyle, newWeight, oldTypeface.Stretch);
var newProp = TextFormattingRunProperties.CreateTextFormattingRunProperties(
foregroundBrush, backgroundBrush, newTypeface, null, null,
oldProp.TextDecorations, oldProp.TextEffects, oldProp.CultureInfo);
formatMap.SetTextProperties(classificationType, newProp);
}
}
// Also update all of our ClassificationFormatDefinition values with the new values.
// Without this, changing the theme does not reliably update the colors: Sometimes after restarting VS, we get
// the wrong colors. For example, when switching from the dark to the light theme, we often end up with the colors
// of the dark theme after a VS restart.
// From what I could understand: The call fontAndColorCacheManager.ClearCache() below deletes the registry key
// "Software\Microsoft\VisualStudio\17.0_4d51a943Exp\FontAndColors\Cache\{75A05685-00A8-4DED-BAE5-E7A50BFA929A}\ItemAndFontInfo"
// which is the cache of the font and colors. After our function here finishes, some Visual Studio component
// sometimes (but not always) immediately updates the font and color cache. I.e. it calls something like
// fontAndColorStorage.OpenCategory(ref mFontAndColorCategoryGUID, (uint)__FCSTORAGEFLAGS.FCSF_READONLY | (uint)__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS).
// Note the "FCSF_LOADDEFAULTS". This causes Visual Studio to re-create the registry key. However, apparently
// it does not use the colors from the updated formatMap, but instead the colors set on the ClassificationFormatDefinition,
// which were not yet updated so far. Thus, changing the theme, changes the displayed colors immediately (because we update
// the formatMap), but the registry cache ends up with the wrong colors. After a restart of VS, it uses the cached values
// and therefore we get the wrong colors.
// By changing the colors also on the ClassificationFormatDefinition, the issue appears to be fixed.
foreach (IFormatDefinition f in mFormatDefinitions) {
f.Reinitialize();
}
}
finally {
formatMap.EndBatchUpdate();
fontAndColorStorage.CloseCategory();
if (fontAndColorCacheManager.ClearCache(ref mFontAndColorCategoryGUID) != VSConstants.S_OK) {
throw new System.Exception("Failed to clear cache of FontAndColorCacheManager.");
}
}
}
private Theme GetCurrentTheme()
{
// We need to figure out if our extension should choose the default colors suitable for light or dark themes.
// In principle we could explicitly retrieve the color theme currently active in Visual Studio. However, that
// approach is fundamentally flawed: We could check if the theme is one of the default ones (dark, light, blue,
// etc.), but Visual Studio supports installing additional themes. It is impossible to know all themes existing
// out there. So, what we really want is to check if the dark or the light defaults are more suitable given the
// text editor's background color.
// However, the EnvironmentColors does not seem to contain an element for the text editor's background. So we
// simply use the tool windows' background, as suggested also here: https://stackoverflow.com/a/48993958/3740047
// The simplistic heuristic of just checking the blue color seems to work reasonably well. The magic threshold
// was chosen to (hopefully) select the better value for the themes shown at https://devblogs.microsoft.com/visualstudio/custom-themes/
var referenceColor = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
return (referenceColor != null && referenceColor.B < 100) ? Theme.Dark : Theme.Light;
}
// Default colors for light color themes.
static readonly Dictionary<string, TextProperties> cLightColors = new Dictionary<string, TextProperties> {
{ IDs.ID_command, new TextProperties(foreground: Color.FromRgb(0, 75, 0), background: null, isBold: true, isItalic: false) },
{ IDs.ID_parameter1, new TextProperties(foreground: Color.FromRgb(0, 80, 218), background: null, isBold: true, isItalic: false) },
// ... further custom classifications
};
// Default colors for dark color themes.
static readonly Dictionary<string, TextProperties> cDarkColors = new Dictionary<string, TextProperties> {
{ IDs.ID_command, new TextProperties(foreground: Color.FromRgb(140, 203, 128), background: null, isBold: true, isItalic: false) },
{ IDs.ID_parameter1, new TextProperties(foreground: Color.FromRgb(86, 156, 214), background: null, isBold: true, isItalic: false) },
// ... further custom classifications
};
private Theme mCurrentTheme;
// GUID of the category in which our classification items are placed (i.e. of the elements in the
// fonts and colors settings of Visual Studio). Not just ours but all sorts of other items exist
// in this category, too.
// Can be found by installing our extension, modifying some of the colors of the classifications in
// the Visual Studio's settings dialog, then exporting the settings and checking the resulting file.
// The section about the modified entries contains the proper GUID.
private const string cFontAndColorCategory = "75A05685-00A8-4DED-BAE5-E7A50BFA929A";
Guid mFontAndColorCategoryGUID = new Guid(cFontAndColorCategory);
[Import]
private IClassificationFormatMapService mClassificationFormatMapService = null;
[Import]
private IClassificationTypeRegistryService mClassificationTypeRegistryService = null;
private List<IFormatDefinition> mFormatDefinitions = new List<IFormatDefinition>();
private bool mDisposed = false;
}
A few points to notice here:
An instance of DefaultColors should not be created by hand, but rather only a single instance should get created by MEF (e.g. via an Import attribute). See below.
The current VS theme is identified by checking some currently active background color, as in this answer. It is in principle possible to check whether the light, blue, blue (high contrast), dark, etc. VS themes are active. However, since the user can install additional themes, the list is endless. Thus, simply checking the background color is more generic and robust.
The ClassificationFormatDefinition definitions (which represent the text format used by Visual Studio for the various classifications) are expected to register themselves on the DefaultColors instance via RegisterFormatDefinition().
To get notified about a theme change of Visual Studio, we subscribe to VSColorTheme.ThemeChanged. Also note that the event gets fired multiple times per theme change. Since it unnecessary to execute all the update code in ThemeChangedImpl() multiple times, we check whether the new and old themes are different.
The reaction to the theme change is in ThemeChangedImpl(). This is the code that is mainly based on the answer by SENya, but with the addition that the ClassificationFormatDefinitions registered previously via RegisterFormatDefinition() get a call to Reinitialize().
For completeness sake, ID_command and ID_parameter1 are some self defined identifiers that are used to identify the ClassificationFormatDefinitions (see below):
/// <summary>
/// Identifiers for the classifications. E.g., Visual Studio will use these strings as keys
/// to store the classification's configuration in the registry.
/// </summary>
public static class IDs
{
public const string ID_command = "VSDoxyHighlighter_Command";
public const string ID_parameter1 = "VSDoxyHighlighter_Parameter1";
// ... further IDs for further classifications
}
Now, the actual ClassificationFormatDefinitions are defined like this:
They inherit from an interface IFormatDefinition (which can be passed to the DefaultColors.RegisterFormatDefinition() function)
public interface IFormatDefinition
{
void Reinitialize();
}
All ClassificationFormatDefinitions are mostly the same: They set the text properties (color, bold, italic, etc) that are appropriate for the current color theme upon construction. This is done by querying the DefaultColors.GetDefaultFormattingForCurrentTheme() function. Moreover, they register themselves on the DefaultColors and implement the Reinitialize() method (which is called by DefaultColors). Since it is always the same, I define a base class FormatDefinitionBase for them:
internal abstract class FormatDefinitionBase : ClassificationFormatDefinition, IFormatDefinition
{
protected FormatDefinitionBase(DefaultColors defaultColors, string ID, string displayName)
{
if (defaultColors == null) {
throw new System.ArgumentNullException("VSDoxyHighlighter: The 'DefaultColors' to a FormatDefinition is null");
}
mID = ID;
mDefaultColors = defaultColors;
mDefaultColors.RegisterFormatDefinition(this);
DisplayName = displayName;
Reinitialize();
}
public virtual void Reinitialize()
{
TextProperties color = mDefaultColors.GetDefaultFormattingForCurrentTheme()[mID];
ForegroundColor = color.Foreground;
BackgroundColor = color.Background;
IsBold = color.IsBold;
IsItalic = color.IsItalic;
}
protected readonly DefaultColors mDefaultColors;
protected readonly string mID;
}
Finally, the actual definitions look like this:
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = IDs.ID_command)]
[Name(IDs.ID_command)]
[UserVisible(true)]
[Order(After = /*Whatever is appropriate for your extension*/)]
internal sealed class CommandFormat : FormatDefinitionBase
{
[ImportingConstructor]
public CommandFormat(DefaultColors defaultColors)
: base(defaultColors, IDs.ID_command, "VSDoxyHighlighter - Command")
{
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = IDs.ID_parameter1)]
[Name(IDs.ID_parameter1)]
[UserVisible(true)]
[Order(After = /*Whatever is appropriate for your extension*/)]
internal sealed class ParameterFormat1 : FormatDefinitionBase
{
[ImportingConstructor]
public ParameterFormat1(DefaultColors defaultColors)
: base(defaultColors, IDs.ID_parameter1, "VSDoxyHighlighter - Parameter 1")
{
}
}
//... Further format definitions
Notice that the constructor is marked as ImportingConstructor, so that MEF automatically create a single instance of the DefaultColors class and passes it to the constructors.
So, to summarize:
The ClassificationFormatDefinition gets created by MEF. At the same time, MEF also creates an instance of DefaultColors and passes it to the ClassificationFormatDefinition. The ClassificationFormatDefinition sets the default colors and provides a function to allow it to get reinitialized upon theme change. To make this possible, it also registers itself on the DefaultColors instance.
DefaultColors figures out the current theme and contains the default colors for each theme.
DefaultColors listens for the VSColorTheme.ThemeChanged event, and if fired, clears the Visual Studio's font and color cache, updates the current classification format map (to display the new colors) and also updates all custom ClassificationFormatDefinition instances with the new colors (so that upon recreation of the font and color cache by VS the correct colors are used for the cache).

Related

How to tell if the active document is a text document?

I'm developing a Visual Studio extension in which one of the implemented commands needs to be available only when the active document is a text document (like e.g. the Visual Studio's "Toggle Bookmark" does). The problem is that I can't figure out how to tell when that's the case.
Right now I have a half working solution. In the package's Initialize method I subscribe to DTE's WindowActivated event, and then whenever a window is activated I check if the window DocumentData property is of type TextDocument:
protected override void Initialize()
{
base.Initialize();
var dte = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
dte.Events.WindowEvents.WindowActivated += WindowEventsOnWindowActivated;
//More initialization here...
}
//This is checked from command's BeforeQueryStatus
public bool ActiveDocumentIsText { get; private set; } = false;
private void WindowEventsOnWindowActivated(Window gotFocus, Window lostFocus)
{
if (gotFocus.Kind != "Document")
return; //It's not a document (e.g. it's a tool window)
TextDocument textDoc = gotFocus.DocumentData as TextDocument;
ActiveDocumentIsText = textDoc != null;
}
The problem with this approach is that 1) Window.DocumentData is documented as ".NET Framework internal use only", and 2) this gives a false positive when a document that has both a code view and a design view (e.g. a .visxmanifest file) is open in design mode.
I have tried to use IVsTextManager.GetActiveView as well, but this is returning the last active text view opened - so if I open a .txt file and then a .png file, it returns data for the .txt file even if it's not the active document anymore.
So, how do I check if the active document is a text document, or the code view of a document that can have a designer... and if possible, not using "undocumented" classes/members?
UPDATE: I found a slightly better solution. Inside the window activated handler:
ActiveDocumentIsText = gotFocus.Document.Object("TextDocument") != null;
At least this one is properly documented, but I still have the problem of false positives with designers.
I finally got it. It's somewhat tricky, but it works and is 100% "legal". Here's the recipe:
1- Make the package class implement IVsRunningDocTableEvents. Make all the methods just return VSConstants.S_OK;
2- Add the following field and the following auxiliary method to the package class:
private IVsRunningDocumentTable runningDocumentTable;
private bool DocIsOpenInLogicalView(string path, Guid logicalView, out IVsWindowFrame windowFrame)
{
return VsShellUtilities.IsDocumentOpen(
this,
path,
VSConstants.LOGVIEWID_TextView,
out var dummyHierarchy2, out var dummyItemId2,
out windowFrame);
}
3- Add the following to the Initialize method of the package class:
runningDocumentTable = GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
runningDocumentTable.AdviseRunningDocTableEvents(this, out var dummyCookie);
4- Don't blink, here comes the magic! Implement the IVsRunningDocTableEvents.OnBeforeDocumentWindowShow method as follows:
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
runningDocumentTable.GetDocumentInfo(docCookie,
out var dummyFlags, out var dummyReadLocks, out var dummyEditLocks,
out string path,
out var dummyHierarchy, out var dummyItemId, out var dummyData);
IVsWindowFrame windowFrameForTextView;
var docIsOpenInTextView =
DocIsOpenInLogicalView(path, VSConstants.LOGVIEWID_Code, out windowFrameForTextView) ||
DocIsOpenInLogicalView(path, VSConstants.LOGVIEWID_TextView, out windowFrameForTextView);
//Is the document open in the code/text view,
//AND the window for that view is the one that has been just activated?
ActiveDocumentIsText = docIsOpenInTextView && pFrame == logicalViewWindowFrame;
return VSConstants.S_OK;
}

Visual Studio code coloring - static const variables

I was wondering if there is a way in a visual studio (default or via plugin) to assign a specific text color to static const type of variable.
Example where bold text is special color:
int test = 0;
bool isFinished = false;
static const int variable = 0;
I know this can be done for constants, numbers, method etc. but not sure about static const combination.
Visual Studio Code just came up with this functionality for TypeScript and JavaScript. Their documentation can be found here: https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide#theming
I actually found your post because I wanted to turn off const different coloring in TypeScript.
To restore the color in Default Dark+ to the previous color, use this code in your "settings.json" (Preferences: Open Settings (JSON))
"editor.semanticTokenColorCustomizations": {
"[Default Dark+]": {
"rules": {
"variable.readonly": {
"foreground": "#9CDCFE"
}
}
}
}
Based on your exact requirement. It might be possible in your language to do something like [variable.readonly.static] when your language will be supported.
More info also here:
https://github.com/Microsoft/vscode-extension-samples/tree/master/semantic-tokens-sample

Is there a Xamarin Mvvmcross Android Shared Element Navigation example?

I'm trying to get this animation/transition working in my Xamarin Android application with Mvx.
I have a recyclerview with cards. When tapping on a card, I now call:
private void TimeLineAdapterOnItemClick(object sender, int position)
{
TimeLineAdapter ta = (TimeLineAdapter) sender;
var item = ta.Items[position];
int photoNum = position + 1;
Toast.MakeText(Activity, "This is photo number " + photoNum, ToastLength.Short).Show();
ViewModel.ShowDetails(item.Id);
}
I'm trying to find out how to translate this java navigation with transition to Xamarin with Mvvmcross:
ActivityOptionsCompat options =
ActivityOptionsCompat.MakeSceneTransitionAnimation(this, imageView, getString(R.string.activity_image_trans));
startActivity(intent, options.toBundle());
I know that within Mvx you can make use of custom presenters, but how do I get hold of, for example, the ImageView of the tapped Card within the RecyclerView which I would like to 'transform' to the new ImageView on the new Activity?
Thanks!
.
Is there a Xamarin Mvvmcross Android Shared Element Navigation
example?
I do not believe so.
I know that within Mvx you can make use of custom presenters, but how
do I get hold of, for example, the ImageView of the tapped Card within
the RecyclerView which I would like to 'transform' to the new
ImageView on the new Activity?
The easiest way that I can think of to achieve the sharing of control elements you want to transition is via the use of view tags and a presentation bundle when using ShowViewModel.
I would suggest making some changes to your Adapter Click handler to include the view of the ViewHolder being selected (See GitHub repo for example with EventArgs). That way you can interact with the ImageView and set a tag that can be used later to identity it.
private void TimeLineAdapterOnItemClick(object sender, View e)
{
var imageView = e.FindViewById<ImageView>(Resource.Id.imageView);
imageView.Tag = "anim_image";
ViewModel.ShowDetails(imageView.Tag.ToString());
}
Then in your ViewModel, send that tag via a presentationBundle.
public void ShowDetails(string animationTag)
{
var presentationBundle = new MvxBundle(new Dictionary<string, string>
{
["Animate_Tag"] = animationTag
});
ShowViewModel<DetailsViewModel>(presentationBundle: presentationBundle);
}
Then create a custom presenter to pickup the presentationBundle and handle the creating of new activity with the transition. The custom presenter which makes use of the tag to find the element that you want to transition and include the ActivityOptionsCompat in the starting of the new activity. This example is using a MvxFragmentsPresenter but if you are not making use of fragments and using MvxAndroidViewPresenter the solution would be almost identical (Override Show instead and no constructor required).
public class SharedElementFragmentsPresenter : MvxFragmentsPresenter
{
public SharedElementFragmentsPresenter(IEnumerable<Assembly> AndroidViewAssemblies)
: base(AndroidViewAssemblies)
{
}
protected override void ShowActivity(MvxViewModelRequest request, MvxViewModelRequest fragmentRequest = null)
{
if (InterceptPresenter(request))
return;
Show(request, fragmentRequest);
}
private bool InterceptPresenter(MvxViewModelRequest request)
{
if ((request.PresentationValues?.ContainsKey("Animate_Tag") ?? false)
&& request.PresentationValues.TryGetValue("Animate_Tag", out var controlTag))
{
var intent = CreateIntentForRequest(request);
var control = Activity.FindViewById(Android.Resource.Id.Content).FindViewWithTag(controlTag);
control.Tag = null;
var transitionName = control.GetTransitionNameSupport();
if (string.IsNullOrEmpty(transitionName))
{
Mvx.Warning($"A {nameof(transitionName)} is required in order to animate a control.");
return false;
}
var activityOptions = ActivityOptionsCompat.MakeSceneTransitionAnimation(Activity, control, transitionName);
Activity.StartActivity(intent, activityOptions.ToBundle());
return true;
}
return false;
}
}
GetTransitionNameSupport is an extension method that just does a platform API check when getting the TransitionName.
public static string GetTransitionNameSupport(this ImageView imageView)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
return imageView.TransitionName;
return string.Empty;
}
The final step would be to register the custom presenter in you Setup.cs
protected override IMvxAndroidViewPresenter CreateViewPresenter()
{
var mvxPresenter = new SharedElementFragmentsPresenter(AndroidViewAssemblies);
Mvx.RegisterSingleton<IMvxAndroidViewPresenter>(mvxPresenter);
return mvxPresenter;
}
You can check the repo on GitHub which demonstrates this example. The solution is designed so that the presenter does not have to care about the type of the control that is being transitioned. A control only requires a tag used to identify it. The example in the repo also allows for specifying multiple control elements that you want to transition (I did not want to include more complexity in the example above).

Adding a custom editor to visual studio editor list

I am in the process of writing a custom editor for visual studio. I have implemented some basic functionality for the new language e.g. syntax highlighting and I succesfully installed tha package by using the generated .vsix file. All works just nice, however my custom editor needs to be able to be associated with different file extensions.
I thought, mistakenly, that since I installed the editor it would appear under
Tools->Options..->Text Editor->File Extension->Editors list:
However it does not appear there. So the question is: how do you add a custom editor to this list?
Thanks for any help!
Well at least I got the tumbleweed badge for this question.
After a lot of reverse engineering I found the solution... which is not documented.. Anywhere..
Step number 1:
First you need to create an editor factory with all the bells and whistles it comes with - MSVS has an extension for it.
Step number 2:
Then you have to create such a class
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
class ProvideFileExtensionMapping : RegistrationAttribute
{
private readonly string _name, _id, _editorGuid, _package;
private readonly int _sortPriority;
public ProvideFileExtensionMapping(string id, string name, object editorGuid, string package, int sortPriority)
{
_id = id;
_name = name;
if (editorGuid is Type)
{
_editorGuid = ((Type)editorGuid).GUID.ToString("B");
}
else
{
_editorGuid = editorGuid.ToString();
}
_package = package;
_sortPriority = sortPriority;
}
public override void Register(RegistrationContext context)
{
using (Key mappingKey = context.CreateKey("FileExtensionMapping\\" + _id))
{
mappingKey.SetValue("", _name);
mappingKey.SetValue("DisplayName", _name);
mappingKey.SetValue("EditorGuid", _editorGuid);
mappingKey.SetValue("Package", _package);
mappingKey.SetValue("SortPriority", _sortPriority);
}
}
public override void Unregister(RegistrationAttribute.RegistrationContext context)
{
}
}
Step 3:
Then you need to add this class as an attribute to your editor factory (which you created in step 1):
[ProvideFileExtensionMapping("{E23E32ED-3467-4401-A364-1352666A3502}", "RText Editor", typeof(EditorFactory), GuidList.guidRTextEditorPluginEditorFactoryString, 100)]
public sealed class EditorFactory : IVsEditorFactory, IDisposable{...}
That's it. You should now be able to see your editor in the list of editors in visual studio.
Your editor shall be invoked when the file mapping is right.
Hopefully this post saves a lot of time for someone else..

C# - Is there any OnShapeMoved or OnShapeDeleted event in Visio?

I think the title or the question is clear enough. I saw something about the EventSink, but I found it difficult to use. Any hint?
The Visio Primary Interop Assembly exposes these events as C# events therefore you can simply hook the event with a delegate.
See this simple example:
namespace VisioEventsExample
{
using System;
using Microsoft.Office.Interop.Visio;
class Program
{
public static void Main(string[] args)
{
Application app = new Application();
Document doc = app.Documents.Add("");
Page page = doc.Pages[1];
// Setup event handles for the events you are intrested in.
// Shape deleted is easy.
page.BeforeShapeDelete +=
new EPage_BeforeShapeDeleteEventHandler(onBeforeShapeDelete);
// To find out if a shape has moved hook the cell changed event
// and then check to see if PinX or PinY changed.
page.CellChanged +=
new EPage_CellChangedEventHandler(onCellChanged);
// In C# 4 for you can simply do this:
//
// page.BeforeShapeDelete += onBeforeShapeDelete;
// page.CellChanged += onCellChanged;
// Now wait for the events.
Console.WriteLine("Wait for events. Press any key to stop.");
Console.ReadKey();
}
// This will be called when a shape sheet cell for a
// shape on the page is changed. To know if the shape
// was moved see of the pin was changed. This will
// fire twice if the shape is moved horizontally and
// vertically.
private static void onCellChanged(Cell cell)
{
if (cell.Name == "PinX" || cell.Name == "PinY")
{
Console.WriteLine(
string.Format("Shape {0} moved", cell.Shape.Name));
}
}
// This will be called when a shape is deleted from the page.
private static void onBeforeShapeDelete(Shape shape)
{
Console.WriteLine(string.Format("Shape deleted {0}", shape.Name));
}
}
}
If you haven't already downloaded the Visio SDK you should do so. Recent versions of the SDK it contains many useful examples include one called "Shape Add\Delete Event". If you have the 2010 version can browse the examples by going to Start Menu\Programs\Microsoft Office 2010 Developer Resources\Microsoft Visio 2010 SDK\Microsoft Visio Code Samples Library.
I believe that you have to implement EvenSink to get access to "ShapesDeleted", i.e.
(short)Microsoft.Office.Interop.Visio.VisEventCodes.visEvtCodeShapeDelete
the code above will help you if you are looking for the event "BeforeShapeDelete" not the "after"ShapeDelete ;)

Resources