TextMate Highlighting
The most modern and robust way to handle syntax highlighting in AvaloniaEdit is using the AvaloniaEdit.TextMate package. This allows you to use VS Code compatible grammars and themes.
Setup
- Ensure you have installed the
AvaloniaEdit.TextMateNuGet package. - In your code-behind, initialize the TextMate installation.
using AvaloniaEdit;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
private RegistryOptions _registryOptions;
private TextMate.Installation _textMateInstallation;
public MainWindow()
{
InitializeComponent();
var editor = this.FindControl<TextEditor>("Editor");
// 1. Initialize RegistryOptions with a default theme (e.g., DarkPlus)
_registryOptions = new RegistryOptions(ThemeName.DarkPlus);
// 2. Install TextMate support onto the editor
_textMateInstallation = editor.InstallTextMate(_registryOptions);
// 3. Set the grammar for a specific language (e.g., C#)
var csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textMateInstallation.SetGrammar(scopeName);
}
}
Changing Themes
You can switch themes at runtime by setting the theme on the installation object.
// Change to Light+ Theme
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(ThemeName.LightPlus));
Custom Grammars
Because AvaloniaEdit.TextMate is built on top of TextMateSharp, you can implement IRegistryOptions to provide custom grammar files (.json or .plist) if the built-in ones do not suffice.