To perform syntax highlighting, you follow a workflow of initializing a Registry, loading a grammar, and then tokenizing lines while maintaining a ruleStack to handle multi-line state.
- Initialize the Registry: Create a
Registry.Registry instance with RegistryOptions (e.g., specifying a ThemeName). - Load a Grammar: Use
registry.LoadGrammar(string filename) to get an IGrammar instance. - Tokenize Lines: Iterate through your text lines. For each line, call
grammar.TokenizeLine(line, ruleStack, timeout). - Maintain State: The
ITokenizeLineResult returned by TokenizeLine contains a RuleStack. You must pass this RuleStack back into the next call to TokenizeLine to ensure correct multi-line parsing (e.g., for comments or strings). - Apply Themes: Use
registry.GetTheme() to get the current theme and call theme.Match(token.Scopes) to find the matching visual rules for a token's scopes.
using TextMateSharp.Grammars;
using TextMateSharp.Themes;
// 1. Initialize Registry
var registry = new Registry.Registry(new RegistryOptions(ThemeName.DarkPlus));
// 2. Load Grammar
IGrammar grammar = registry.LoadGrammar("source.cs");
// 3. Tokenize and maintain state
IStateStack? ruleStack = null;
string line = "using static System; /* comment */";
ITokenizeLineResult result = grammar.TokenizeLine(line, ruleStack, TimeSpan.MaxValue);
ruleStack = result.RuleStack; // Crucial for next line
// 4. Apply Theme
Theme theme = registry.GetTheme();
foreach (var token in result.Tokens)
{
foreach (var themeRule in theme.Match(token.Scopes))
{
var fg = theme.GetColor(themeRule.foreground);
// Use fg color for rendering
}
}