### Complete Syntax Highlighting Application in C# Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md This example demonstrates how to use TextMateSharp to create a complete syntax highlighter. It includes setup for the registry, grammar loading, theme application, and line-by-line tokenization and console output. Ensure the necessary TextMateSharp packages are installed. ```csharp using TextMateSharp.Registry; using TextMateSharp.Grammars; using TextMateSharp.Themes; class SyntaxHighlighter { private readonly Registry _registry; private readonly IGrammar _grammar; private readonly Theme _theme; public SyntaxHighlighter(string languageScope) { var options = new RegistryOptions(ThemeName.DarkPlus); _registry = new Registry(options); _grammar = _registry.LoadGrammar(languageScope); _theme = _registry.GetTheme(); } public void HighlightFile(string filePath) { var lines = File.ReadAllLines(filePath); IStateStack state = null; foreach (var line in lines) { var result = _grammar.TokenizeLine(line, state, TimeSpan.MaxValue); state = result.RuleStack; foreach (var token in result.Tokens) { var rules = _theme.Match(token.Scopes); var rule = rules.FirstOrDefault(); if (rule != null) { var fg = _theme.GetColor(rule.foreground); Console.ForegroundColor = HexToConsoleColor(fg); } var text = line.Substring(token.StartIndex, token.Length); Console.Write(text); } Console.WriteLine(); Console.ResetColor(); } } private static ConsoleColor HexToConsoleColor(string hex) { // Convert hex to console color return ConsoleColor.White; } } // Usage var highlighter = new SyntaxHighlighter("source.cs"); highlighter.HighlightFile("program.cs"); ``` -------------------------------- ### Support Modules - Configuration Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/MANIFEST.txt Guide to configuration options for Registry, TMModel, grammar loading, theme configuration, and performance settings. Includes setup guides for RegistryOptions and IModelLines implementation, along with best practices for configuration and performance. ```APIDOC ## Registry Configuration ### Description Options for configuring the `Registry` class, including paths to grammars and themes. ## RegistryOptions Setup Guide ### Description Step-by-step instructions on how to instantiate and configure `RegistryOptions`. ## TMModel Configuration ### Description Settings related to the `TMModel` document model. ## Grammar Loading Configuration ### Description Options that affect how grammars are loaded and resolved. ## Theme Configuration ### Description Settings for specifying and loading themes. ## Performance Configuration ### Description Options to tune the performance of TextMateSharp, such as caching strategies. ## IModelLines Implementation Guide ### Description Guidance on implementing the `IModelLines` interface for custom line data providers. ## Configuration Best Practices ### Description Recommended practices for managing and applying configuration settings. ## Performance Considerations ### Description Discussion of performance implications related to various configuration choices. ``` -------------------------------- ### TMToken Constructor Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Example of creating a new TMToken with a start index and a list of scope names. ```csharp public TMToken(int startIndex, List scopes) ``` ```csharp var token = new TMToken(0, new List { "source.cs", "keyword.control" }); ``` -------------------------------- ### StateStack Example Usage Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Demonstrates how to initialize a state stack and use it with the TokenizeLine method. ```csharp IStateStack state = StateStack.NULL; var result = grammar.TokenizeLine(line, state, TimeSpan.MaxValue); ``` -------------------------------- ### Token Scope Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Demonstrates how to access and print the scopes associated with a token. Scopes are hierarchical, starting with the grammar scope. ```csharp // Token "using" might have scopes: // ["source.cs", "keyword.other.directive.using.cs"] var token = result.Tokens[0]; Console.WriteLine($"Token '{line.Substring(token.StartIndex, token.Length)}' has scopes:"); foreach (var scope in token.Scopes) { Console.WriteLine($" - {scope}"); } ``` -------------------------------- ### Get Theme Styling Rules Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/START_HERE.md Retrieve the theme from the registry and match token scopes to styling rules to get the foreground color. ```csharp var theme = registry.GetTheme(); var rules = theme.Match(token.Scopes); var color = theme.GetColor(rules[0].foreground); ``` -------------------------------- ### Example Trigger for FileNotFoundException Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/errors.md Demonstrates loading a grammar from a non-existent file path, which will trigger a FileNotFoundException. ```csharp var grammar = registry.LoadGrammarFromPathSync( "/nonexistent/grammar.tmLanguage.json", 0, null); ``` -------------------------------- ### Single Line Tokenization Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Tokenizes a single line of code using a specified grammar and theme. Displays the start index, end index, and scopes for each token. ```csharp var registry = new Registry(new RegistryOptions(ThemeName.DarkPlus)); var grammar = registry.LoadGrammar("source.cs"); var result = grammar.TokenizeLine("int x = 5;"); foreach (var token in result.Tokens) { Console.WriteLine($"{token.StartIndex}-{token.EndIndex}: {token.Scopes}"); } ``` -------------------------------- ### Instantiate Range Objects Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Example of creating Range objects for both single-line and multi-line scenarios. ```csharp var singleLine = new Range(5); var multiLine = new Range(5, 10); ``` -------------------------------- ### Install TextMateSharp Packages Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/START_HERE.md Add the necessary TextMateSharp packages to your .NET project using the dotnet CLI. ```bash dotnet add package TextMateSharp dotnet add package TextMateSharp.Grammars ``` -------------------------------- ### Add TextMateSharp NuGet Packages Source: https://github.com/danipen/textmatesharp/blob/master/README.md Install the core TextMateSharp library and the bundled grammars package using the .NET CLI. ```bash dotnet add package TextMateSharp dotnet add package TextMateSharp.Grammars ``` -------------------------------- ### Line Tokenization Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Shows how to tokenize a line and then use the resulting state stack to tokenize the next line, maintaining parser state across lines. ```csharp IStateStack state = null; var result = grammar.TokenizeLine("line 1", state, TimeSpan.MaxValue); state = result.RuleStack; // Now tokenize the next line using the state from line 1 result = grammar.TokenizeLine("line 2", state, TimeSpan.MaxValue); ``` -------------------------------- ### Example Token Scope for C# 'using' directive Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/types.md Illustrates the scope names applied to the C# keyword 'using' when it functions as a directive. ```json ["source.cs", "keyword.other.directive.using.cs"] ``` -------------------------------- ### ThemeTrieElementRule AcceptOverwrite Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Demonstrates how to use the AcceptOverwrite method to update a rule's font style and other properties. ```csharp var rule = new ThemeTrieElementRule("keyword", 2, null, FontStyle.Bold, 1, 0); rule.AcceptOverwrite("keyword.control", 3, FontStyle.Bold | FontStyle.Italic, 2, 0); Console.WriteLine(rule.fontStyle); // Bold | Italic ``` -------------------------------- ### Styling Tokens with Theme Matching Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Shows how to style tokens by retrieving a theme, matching token scopes against theme rules, and getting the corresponding color. This process is essential for rendering syntax-highlighted code. ```csharp Theme theme = registry.GetTheme(); List rules = theme.Match(token.Scopes); string color = theme.GetColor(rule.foreground); ``` -------------------------------- ### Complete Syntax Highlighter Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/START_HERE.md This C# class demonstrates how to use TextSharp to tokenize and highlight a file based on a specified language scope and theme. It reads lines from a file, tokenizes them, matches scopes to theme rules, and prints the highlighted text to the console. Ensure the language scope is valid and the theme is loaded correctly. ```csharp class SyntaxHighlighter { private readonly IGrammar _grammar; private readonly Theme _theme; public SyntaxHighlighter(string languageScope) { var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); _grammar = registry.LoadGrammar(languageScope); _theme = registry.GetTheme(); } public void HighlightFile(string path) { IStateStack state = null; foreach (var line in File.ReadLines(path)) { var result = _grammar.TokenizeLine(line, state, TimeSpan.MaxValue); state = result.RuleStack; foreach (var token in result.Tokens) { var rules = _theme.Match(token.Scopes); var color = _theme.GetColor(rules[0]?.foreground ?? 0); var text = line.Substring(token.StartIndex, token.Length); Console.ForegroundColor = HexToColor(color); Console.Write(text); } Console.WriteLine(); } } } ``` -------------------------------- ### Configure Tokenization Timeout Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Provides examples of setting tokenization timeouts, differentiating between real-time UI needs and batch processing requirements. ```csharp // Real-time editor: use short timeout var uiTimeout = TimeSpan.FromMilliseconds(50); // Batch processing: use no timeout var batchTimeout = TimeSpan.MaxValue; // Configurable based on use case var timeout = isRealTime ? uiTimeout : batchTimeout; var result = grammar.TokenizeLine(line, state, timeout); ``` -------------------------------- ### LineText Usage Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Demonstrates implicit conversions for creating LineText from a string and converting it to ReadOnlyMemory for tokenization. ```csharp LineText line = "int x = 5;"; // Implicit from string var result = grammar.TokenizeLine(line); ReadOnlyMemory memory = line; // Implicit to memory ``` -------------------------------- ### FontStyle Example Usage Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Demonstrates how to apply and check for individual or combined font styles using the FontStyle enumeration. ```csharp // Single style FontStyle style = FontStyle.Bold; // Combined styles style = FontStyle.Bold | FontStyle.Italic; // Check if style includes bold if ((style & FontStyle.Bold) == FontStyle.Bold) { Console.WriteLine("Text should be bold"); } ``` -------------------------------- ### Create Registry with Default Locator Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Creates a new Registry instance using the default locator implementation. This is useful for basic setup. ```csharp var registry = new Registry(); ``` -------------------------------- ### Multi-line Tokenization Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Tokenizes multiple lines of code, maintaining the state between lines. Processes tokens for each line and updates the rule stack. ```csharp var state = StateStack.NULL; foreach (var line in document.Split('\n')) { var result = grammar.TokenizeLine(line, state, TimeSpan.MaxValue); state = result.RuleStack; ProcessTokens(result.Tokens); } ``` -------------------------------- ### Get Theme from Registry Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Retrieves the current active theme from the registry. Allows access to theme properties like GUI color dictionaries. ```csharp var theme = registry.GetTheme(); var colors = theme.GetGuiColorDictionary(); ``` -------------------------------- ### IToken Properties Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Details the properties of an IToken, such as its start index, end index, length, and assigned scopes. ```csharp int StartIndex { get; set; } ``` ```csharp int EndIndex { get; } ``` ```csharp int Length { get; } ``` ```csharp List Scopes { get; } ``` -------------------------------- ### Build and Run TextMateSharp Demo Source: https://github.com/danipen/textmatesharp/blob/master/README.md Instructions for building and running the TextMateSharp demo project from the command line. ```bash cd src/TextMateSharp.Demo dotnet build dotnet run -- ./testdata/samplefiles/sample.cs ``` -------------------------------- ### Map Scopes to Theme Rules Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Get the theme and match token scopes to styling rules. Used to determine visual styling for tokens. ```csharp var theme = registry.GetTheme(); var token = result.Tokens[0]; var rules = theme.Match(token.Scopes); foreach (var rule in rules) { Console.WriteLine($"Color: {theme.GetColor(rule.foreground)}"); } ``` -------------------------------- ### Basic Tokenization with Registry Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Demonstrates the basic steps for tokenizing text using the Registry, loading a grammar, and tokenizing a single line. Ensure a ThemeName is provided during RegistryOptions creation. ```csharp Registry registry = new Registry(new RegistryOptions(ThemeName)); IGrammar grammar = registry.LoadGrammar(scopeName); Grammar.TokenizeLine(text, state, timeout); ``` -------------------------------- ### TokenizeLine Method Example Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Tokenizes a single line of text using the grammar. This method is suitable for basic line tokenization without needing to manage state across lines. ```csharp var grammar = registry.LoadGrammar("source.cs"); var result = grammar.TokenizeLine("int x = 5;"); foreach (var token in result.Tokens) { Console.WriteLine($"{token.StartIndex}-{token.EndIndex}: {string.Join(",", token.Scopes)}"); } ``` -------------------------------- ### Initialize RegistryOptions with ThemeName Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Demonstrates how to create RegistryOptions instances using specific themes from the ThemeName enumeration. This is useful for setting up syntax highlighting with predefined themes. ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var lightOptions = new RegistryOptions(ThemeName.LightPlus); ``` -------------------------------- ### Document Model Initialization and Tokenization Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Explains how to create and manage a document model for tokenization. The model can be configured with a grammar, and tokenization can be forced for specific lines. Listeners can be added to track changes. ```csharp TMModel model = new TMModel(lines); model.SetGrammar(grammar); model.AddModelTokensChangedListener(listener); model.ForceTokenization(index); ``` -------------------------------- ### Get Color ID Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Gets the numeric ID for a color string, creating one if it doesn't exist. Accepts a hex color string or null. ```csharp public int GetId(string color) ``` -------------------------------- ### Get Language and Scope by File Extension Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Determines the language and scope identifier for a given file extension. Loads the appropriate grammar based on the scope. ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var language = options.GetLanguageByExtension(".cs"); var scope = options.GetScopeByExtension(".cs"); var grammar = registry.LoadGrammar(scope); ``` -------------------------------- ### IModelLines.GetLineLength(int) Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the length of a line. ```APIDOC ## IModelLines.GetLineLength(int) ### Description Gets the length of a line. ### Method Signature `int GetLineLength(int lineIndex)` ### Parameters #### Path Parameters - **lineIndex** (int) - Required - Zero-based line index ### Returns - **int**: Length of the line in characters (including terminators if present). ``` -------------------------------- ### IModelLines.GetNumberOfLines() Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the total count of document lines. ```APIDOC ## IModelLines.GetNumberOfLines() ### Description Gets the total count of document lines. ### Method Signature `int GetNumberOfLines()` ### Returns - **int**: Number of actual document lines (may differ from GetSize). ``` -------------------------------- ### Initialize Document Model Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Create and configure a TextMate document model for background tokenization. Listen for token changes and force tokenization for specific lines. ```csharp var model = new TMModel(modelLines); model.SetGrammar(grammar); model.AddModelTokensChangedListener(listener); model.ForceTokenization(lineNumber); ``` -------------------------------- ### IModelLines.GetSize() Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the count of model line objects. ```APIDOC ## IModelLines.GetSize() ### Description Gets the count of model line objects. ### Method Signature `int GetSize()` ### Returns - **int**: Number of model line objects. ``` -------------------------------- ### Get Language by File Extension Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Finds a language definition based on its file extension. The extension matching is case-insensitive. Returns null if no matching language is found. ```csharp public Language GetLanguageByExtension(string extension) ``` ```csharp var lang = options.GetLanguageByExtension(".cs"); if (lang != null) { Console.WriteLine($"Language ID: {lang.Id}"); } ``` -------------------------------- ### LineText Length Property Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Gets the number of characters in the LineText. ```csharp public int Length { get; } ``` -------------------------------- ### Build TextMateSharp Project Source: https://github.com/danipen/textmatesharp/blob/master/README.md Navigate to the TextMateSharp source directory and build the project using the .NET CLI. ```bash cd src/TextMateSharp dotnet build ``` -------------------------------- ### IModelLines.GetLineTextIncludingTerminators(int) Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the line text including line terminators. ```APIDOC ## IModelLines.GetLineTextIncludingTerminators(int) ### Description Gets the line text including line terminators. ### Method Signature `LineText GetLineTextIncludingTerminators(int lineIndex)` ### Parameters #### Path Parameters - **lineIndex** (int) - Required - Zero-based line index ### Returns - **LineText**: Line text (should include '\n' or '\r\n' if present). ### Remarks - Including terminators improves tokenization performance - Returns text even if line is empty or contains only whitespace - Allows reading from a virtual line if number exceeds GetNumberOfLines ``` -------------------------------- ### Initialize Registry Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Initialize the Registry with theme options and load a grammar. This is the entry point for grammar and theme management. ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); var grammar = registry.LoadGrammar("source.cs"); ``` -------------------------------- ### IModelLines.Get(int) Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the model line object at a specific index. ```APIDOC ## IModelLines.Get(int) ### Description Gets the model line object at an index. ### Method Signature `ModelLine Get(int lineIndex)` ### Parameters #### Path Parameters - **lineIndex** (int) - Required - Zero-based line index ### Returns - **ModelLine**: ModelLine object containing state and tokens. ``` -------------------------------- ### Initialize Registry with Options Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Instantiate the Registry class by providing an IRegistryOptions object to control grammar and theme loading. ```csharp public Registry(IRegistryOptions locator) ``` ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); ``` -------------------------------- ### IRawTheme GetSettings() Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves the theme settings in the legacy vscode-textmate format. ```csharp ICollection GetSettings() ``` -------------------------------- ### IModelLines GetSize Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the count of model line objects. ```csharp int GetSize() ``` -------------------------------- ### TMToken Class Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Represents a token with its starting position and associated scopes. ```APIDOC ## TMToken ### Description Token with position. ### Constructor - `TMToken(int, List)` ### Properties - `StartIndex` (int) - `Scopes` (string[]) ``` -------------------------------- ### IModelLines GetLineLength Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the length of a line, including terminators if present. ```csharp int GetLineLength(int lineIndex) ``` -------------------------------- ### IModelLines GetNumberOfLines Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Gets the total count of actual document lines. ```csharp int GetNumberOfLines() ``` -------------------------------- ### Theme.GetColor Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Gets the hex color string corresponding to an internal numeric ID. ```APIDOC ## Theme.GetColor ### Description Gets the color string for an internal ID. ### Method `public string GetColor(int id)` ### Parameters #### Path Parameters - **id** (int) - Required - Internal color ID from GetColorId or token metadata ### Returns Hex color string, or null if ID not found. ``` -------------------------------- ### Theme.GetColorId Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Gets the internal numeric ID for a given hex color string. ```APIDOC ## Theme.GetColorId ### Description Gets the internal ID for a color string. ### Method `public int GetColorId(string color)` ### Parameters #### Path Parameters - **color** (string) - Required - Hex color string (e.g., "#FF0000") ### Returns Internal numeric ID (>0) or 0 if not found. ### Remarks IDs are used in token metadata for efficient storage. ``` -------------------------------- ### TMToken Properties Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Properties for TMToken, providing the start index and scope names. ```csharp public int StartIndex { get; } ``` ```csharp public List Scopes { get; } ``` -------------------------------- ### IRawThemeSetting.GetSetting() Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves the styling properties for a theme scope. Returns a ThemeSetting object. ```csharp IThemeSetting GetSetting() ``` -------------------------------- ### Initialize RegistryOptions with Default Theme Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Create a RegistryOptions instance, specifying a default theme for grammars and themes. Several predefined themes are available. ```csharp public RegistryOptions(ThemeName defaultTheme) ``` ```csharp // Create options with different default themes var darkOptions = new RegistryOptions(ThemeName.DarkPlus); var lightOptions = new RegistryOptions(ThemeName.LightPlus); var accessibleOptions = new RegistryOptions(ThemeName.HighContrastDark); ``` -------------------------------- ### GetScopeName Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Retrieves the scope name of the grammar, for example, "source.cs". ```csharp string GetScopeName() ``` -------------------------------- ### IModelLines Get Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Retrieves the model line object at a specific zero-based index. ```csharp ModelLine Get(int lineIndex) ``` -------------------------------- ### Registry Initialization Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md The Registry is the entry point for loading grammars and managing themes. It should be initialized once and reused throughout the application. ```APIDOC ## Registry Initialization ### Description Initializes the TextMateSharp Registry with specified options and loads a grammar. ### Method Constructor and LoadGrammar ### Endpoint N/A (SDK Method) ### Parameters #### Registry Constructor - **options** (RegistryOptions) - Required - Options for the registry, including theme selection. #### LoadGrammar - **grammarName** (string) - Required - The name or path of the grammar to load (e.g., "source.cs"). ### Request Example ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); var grammar = registry.LoadGrammar("source.cs"); ``` ### Response #### Success Response - **registry** (Registry) - An initialized Registry object. - **grammar** (IGrammar) - The loaded grammar object. #### Response Example ```csharp // See Request Example for the grammar object ``` ``` -------------------------------- ### Range FromLineNumber Property Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Represents the starting line number of the range. It is zero-based and inclusive. ```csharp public int FromLineNumber { get; } ``` -------------------------------- ### Default TextMateSharp Configuration Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Demonstrates default configurations for Registry, RegistryOptions with bundled grammars, Tokenization, TMModel, ThemeName, and StateStack. ```csharp // Default Registry var registry = new Registry(); // Uses DefaultLocator (no grammars available) // With Bundled Grammars (recommended) var options = new RegistryOptions(ThemeName.DarkPlus); // 50+ languages, Dark+ theme var registry = new Registry(options); // Default Tokenization grammar.TokenizeLine(lineText); // No previous state, no timeout limit // Default Model var model = new TMModel(lines); // No grammar set initially model.SetGrammar(grammar); // Must set manually // Default Theme ThemeName.DarkPlus // Default in RegistryOptions // Default State StateStack.NULL // First line initial state ``` -------------------------------- ### TMToken Class Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Represents a token on a line with its starting position and semantic scope names. ```APIDOC ## TMToken A token on a line with position and scopes. ```csharp public class TMToken ``` **Namespace:** `TextMateSharp.Model` ### Properties #### StartIndex ```csharp public int StartIndex { get; } ``` Character position where this token starts. #### Scopes ```csharp public List Scopes { get; } ``` Semantic scope names for this token. ### Constructor #### TMToken(int, List) ```csharp public TMToken(int startIndex, List scopes) ``` Creates a token. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | startIndex | int | Yes | — | Character position in the line | | scopes | List | Yes | — | Scope names for this token | **Example:** ```csharp var token = new TMToken(0, new List { "source.cs", "keyword.control" }); ``` ``` -------------------------------- ### Load Custom Grammars from Local Directory Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Loads custom grammars from a specified local directory. Initializes a registry with these custom grammars. ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); options.LoadFromLocalDir("./custom-grammars"); var registry = new Registry(options); var grammar = registry.LoadGrammar("source.custom"); ``` -------------------------------- ### Initialize TMModel Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Instantiate TMModel with a provider for line data. The 'lines' parameter is required. ```csharp public class TMModel : ITMModel { public TMModel(IModelLines lines) } ``` -------------------------------- ### Get All Colors Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves a collection of all registered hex color strings currently stored in the map. ```csharp public ICollection GetColorMap() ``` -------------------------------- ### Configure Line Length Limits for Tokenization Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Illustrates how to handle lines exceeding a predefined maximum length to prevent performance degradation during tokenization. ```csharp // Lines over 10,000 characters may have reduced performance const int MAX_LEN_TO_TOKENIZE = 10000; if (line.Length > MAX_LEN_TO_TOKENIZE) { // Handle long lines specially var shortened = line.Substring(0, MAX_LEN_TO_TOKENIZE); var result = grammar.TokenizeLine(shortened); } ``` -------------------------------- ### Range Class Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Represents a contiguous range of lines. Properties include start and end line numbers. ```APIDOC ## Class Range Represents a contiguous range of lines. ```csharp public class Range ``` **Namespace:** `TextMateSharp.Model` ### Properties #### FromLineNumber ```csharp public int FromLineNumber { get; } ``` Start line (zero-based, inclusive). #### ToLineNumber ```csharp public int ToLineNumber { get; set; } ``` End line (zero-based, inclusive). ### Constructors #### Range(int) ```csharp public Range(int lineNumber) ``` Creates a range for a single line. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | lineNumber | int | Yes | — | Zero-based line index | #### Range(int, int) ```csharp public Range(int fromLineNumber, int toLineNumber) ``` Creates a range spanning multiple lines. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | fromLineNumber | int | Yes | — | Start line (inclusive) | | toLineNumber | int | Yes | — | End line (inclusive) | **Example:** ```csharp var singleLine = new Range(5); var multiLine = new Range(5, 10); ``` ``` -------------------------------- ### LineText Constructors Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammar.md Demonstrates the creation of LineText objects using different constructors. ```APIDOC ## LineText(string) ### Description Creates a LineText from a string. ### Parameters #### Path Parameters - **text** (string) - Required - The line text (null becomes empty) ``` ```APIDOC ## LineText(ReadOnlyMemory) ### Description Creates a LineText from a ReadOnlyMemory buffer. ### Parameters #### Path Parameters - **memory** (ReadOnlyMemory) - Required - The text buffer ``` -------------------------------- ### Initialize TextMateSharp Registry Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/START_HERE.md Initialize the TextMateSharp registry with theme options and load a specific grammar, such as C#. ```csharp using TextMateSharp.Registry; using TextMateSharp.Grammars; var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); var grammar = registry.LoadGrammar("source.cs"); ``` -------------------------------- ### TMToken Class Definition Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Represents a token within a line, including its starting position and scope names. ```csharp public class TMToken ``` -------------------------------- ### Set Active Theme in TextMateSharp Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Demonstrates how to create a registry, load and set a different built-in theme, and retrieve the currently active theme. ```csharp var registry = new Registry(new RegistryOptions(ThemeName.DarkPlus)); // Load and set a different built-in theme var lightTheme = new RegistryOptions(ThemeName.DarkPlus).LoadTheme(ThemeName.LightPlus); registry.SetTheme(lightTheme); // Get current theme var activeTheme = registry.GetTheme(); // Query theme properties var colors = activeTheme.GetGuiColorDictionary(); var colorMap = activeTheme.GetColorMap(); ``` -------------------------------- ### Create Registry with Custom Options Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Creates a new Registry instance with custom registry options. This allows for specific configurations like theme selection. ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); ``` -------------------------------- ### Registry() Constructor Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Creates a new Registry instance using the default locator implementation for grammar and theme resources. ```APIDOC ## Registry() ### Description Creates a Registry with a default locator implementation. ### Returns New Registry instance. ### Example ```csharp var registry = new Registry(); ``` ``` -------------------------------- ### RegistryOptions Constructor Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Creates registry options with bundled grammars and themes. This constructor initializes the registry with a specified default theme and automatically loads all bundled grammars and themes, with grammars being lazy-loaded on first request. ```APIDOC ## RegistryOptions(ThemeName) ### Description Creates registry options with bundled grammars and themes. ### Method Signature public RegistryOptions(ThemeName defaultTheme) ### Parameters #### Path Parameters - **defaultTheme** (ThemeName) - Required - The default theme to use for the registry (e.g., ThemeName.DarkPlus). ### Remarks - Automatically loads all 50+ bundled grammars. - Lazy-loads grammars on first request. - Loads all built-in themes. ### Example ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); var grammar = registry.LoadGrammar("source.cs"); ``` ``` -------------------------------- ### Get Registry Options Provider Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Retrieves the registry options provider. This returns the IRegistryOptions instance used by this registry. ```csharp var registryOptions = registry.GetLocator(); ``` -------------------------------- ### Multi-line Tokenization with StateStack Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Illustrates how to tokenize text across multiple lines by managing the state stack. The state is updated after each line is tokenized, and tokens are processed in a loop. ```csharp IStateStack state = null; state = grammar.TokenizeLine(line, state, timeout).RuleStack; foreach (var token in result.Tokens) ``` -------------------------------- ### Registry(IRegistryOptions) Constructor Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Creates a new Registry instance with a custom registry options provider, allowing for specific configurations for grammar and theme resources. ```APIDOC ## Registry(IRegistryOptions locator) ### Description Creates a Registry with a custom registry options provider. ### Parameters #### Path Parameters - **locator** (IRegistryOptions) - Required - Provider for grammar and theme resources ### Returns New Registry instance. ### Throws `TMException` if grammar loading fails ### Example ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var registry = new Registry(options); ``` ``` -------------------------------- ### Get Available Grammar Definitions Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Retrieves all loaded grammar definitions from the registry. This method is useful for understanding which grammars are currently active. ```csharp public IEnumerable GetAvailableGrammarDefinitions() ``` -------------------------------- ### Initialize Registry Once Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Initialize the Registry instance once and reuse it throughout your application. Frequent re-initialization can lead to performance degradation. ```csharp // Good: Single initialization private static readonly Registry _registry; static Initialize() { var options = new RegistryOptions(ThemeName.DarkPlus); _registry = new Registry(options); } // Bad: Re-initialize frequently for (int i = 0; i < 1000; i++) { var registry = new Registry(new RegistryOptions(ThemeName.DarkPlus)); // ... } ``` -------------------------------- ### Get Available Languages Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Retrieves a list of all available language definitions supported by the registry. Useful for inspecting supported languages and their metadata. ```csharp public List GetAvailableLanguages() ``` ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); var languages = options.GetAvailableLanguages(); foreach (var lang in languages) { Console.WriteLine($"{lang.Id}: {lang.Aliases?[0]}"); } ``` -------------------------------- ### Get Color by ID Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves the hex color string associated with a given numeric ID. Returns null if the ID is not found. ```csharp public string GetColor(int id) ``` -------------------------------- ### Tokenize C# Code with TextMateSharp Source: https://github.com/danipen/textmatesharp/blob/master/README.md Demonstrates tokenizing lines of C# code using the TextMateSharp registry and grammar. It shows how to iterate through tokens, extract scopes, and match theme rules for syntax highlighting. ```csharp using System; using System.Collections.Generic; using TextMateSharp.Grammars; using TextMateSharp.Themes; namespace TextMateSharp; class Program { static void Main(string[] args) { try { Registry.Registry registry = new Registry.Registry( new RegistryOptions(ThemeName.DarkPlus)); List textLines = new List(); textLines.Add("using static System; /* comment here */"); textLines.Add("namespace Example"); textLines.Add("{"); textLines.Add("}"); IGrammar grammar = registry.LoadGrammar("source.cs"); IStateStack? ruleStack = null; foreach (var line in textLines) { Console.WriteLine($"Tokenizing line: {line}"); ITokenizeLineResult result = grammar.TokenizeLine(line, ruleStack, TimeSpan.MaxValue); ruleStack = result.RuleStack; foreach (var token in result.Tokens) { int startIndex = (token.StartIndex > line.Length) ? line.Length : token.StartIndex; int endIndex = (token.EndIndex > line.Length) ? line.Length : token.EndIndex; Console.WriteLine( " - token from {0} to {1} -->{2}<-- with scopes {3}", startIndex, endIndex, line.Substring(startIndex, endIndex - startIndex), string.Join(",", token.Scopes)); Theme theme = registry.GetTheme(); foreach (var themeRule in theme.Match(token.Scopes)) { Console.WriteLine( " - Matched theme rule: " + "[bg: {0}, fg:{1}, fontStyle: {2}]", theme.GetColor(themeRule.background), theme.GetColor(themeRule.foreground), themeRule.fontStyle); } } } } catch (Exception ex) { Console.WriteLine("ERROR: " + ex.Message); } } } ``` -------------------------------- ### Map File Extensions to Grammar Scopes Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Use RegistryOptions to map file extensions or language IDs to grammar scope names for loading grammars. The ThemeName.DarkPlus is used for options. ```csharp var options = new RegistryOptions(ThemeName.DarkPlus); // Find scope by file extension string scope = options.GetScopeByExtension(".cs"); // Returns "source.cs" var grammar = registry.LoadGrammar(scope); // Find scope by language ID scope = options.GetScopeByLanguageId("csharp"); // Returns "source.cs" grammar = registry.LoadGrammar(scope); ``` -------------------------------- ### Add TextMateSharp.Grammars Package Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/README.md Add the TextMateSharp.Grammars NuGet package to your project for bundled grammars and themes. ```xml ``` -------------------------------- ### Get Color Map Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves a collection of all unique hex color strings used within the theme. This can be used to iterate over all available colors. ```csharp var colorMap = theme.GetColorMap(); foreach (var color in colorMap) { Console.WriteLine(color); } ``` -------------------------------- ### Theme.CreateFromRawTheme Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Creates a compiled Theme instance from a raw theme definition, processing rules, inheritance, and building lookup structures. ```APIDOC ## Theme.CreateFromRawTheme ### Description Creates a compiled Theme from a raw theme definition. ### Method `public static Theme CreateFromRawTheme(IRawTheme source, IRegistryOptions registryOptions)` ### Parameters #### Path Parameters - **source** (IRawTheme) - Required - The raw theme object to compile - **registryOptions** (IRegistryOptions) - Required - Registry options for resolving theme includes ### Returns Compiled `Theme` instance ready for use. ### Remarks - Processes all theme rules and inheritance - Builds color map and scope trie for efficient lookup - Handles theme includes recursively ### Example ```csharp var registryOptions = new RegistryOptions(ThemeName.DarkPlus); var rawTheme = registryOptions.GetDefaultTheme(); var theme = Theme.CreateFromRawTheme(rawTheme, registryOptions); ``` ``` -------------------------------- ### Create Theme from Raw Theme Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Compiles a Theme instance from a raw theme definition using provided registry options. This method processes rules, inheritance, and builds efficient lookup structures. ```csharp var registryOptions = new RegistryOptions(ThemeName.DarkPlus); var rawTheme = registryOptions.GetDefaultTheme(); var theme = Theme.CreateFromRawTheme(rawTheme, registryOptions); ``` -------------------------------- ### Range Constructor for Multiple Lines Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Creates a Range object spanning multiple lines. Both start and end line numbers are inclusive and zero-based. ```csharp public Range(int fromLineNumber, int toLineNumber) ``` -------------------------------- ### Core Modules - Registry Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/MANIFEST.txt Documentation for the Registry class, responsible for grammar and theme loading, and the IRegistryOptions interface defining the resource provider contract. Includes the DefaultLocator class for null implementation. ```APIDOC ## Registry Class ### Description Handles the loading of grammars and themes. ### Methods - `LoadGrammar(grammarName)` - `LoadTheme(themeName)` ## IRegistryOptions Interface ### Description Defines the contract for resource providers used by the Registry. ### Properties - `GrammarSource`: Source for grammars. - `ThemeSource`: Source for themes. ## DefaultLocator Class ### Description A null implementation of a locator, often used as a default or placeholder. ``` -------------------------------- ### Get Tokens for a Specific Line in TextMateSharp Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Retrieve the tokens for a given line. Returns null if tokenization is pending. Tokens are cached until the line is modified. ```csharp var tokens = model.GetLineTokens(5); if (tokens != null) { foreach (var token in tokens) { Console.WriteLine($"Line 5, position {token.StartIndex}: {token.Scopes}"); } } ``` -------------------------------- ### Get Scope by File Extension Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Retrieves the grammar scope name associated with a given file extension. This is useful for directly loading a grammar by its scope. ```csharp public string GetScopeByExtension(string extension) ``` ```csharp var scope = options.GetScopeByExtension(".cs"); if (scope != null) { var grammar = registry.LoadGrammar(scope); } ``` -------------------------------- ### Load Grammar from Local File Path Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Loads a single grammar from a specified local package.json file path. You can provide a custom name for the grammar and choose whether to overwrite existing ones. ```csharp public void LoadFromLocalFile(string grammarName, string packageJsonFileInfo, bool overwrite = false) ``` ```csharp options.LoadFromLocalFile("MY_LANG", "/path/to/package.json"); ``` -------------------------------- ### Core Modules - Grammar Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/MANIFEST.txt Details on the IGrammar interface for tokenization, the IToken interface for token representation, and ITokenizeLineResult/ITokenizeLineResult2 for tokenization output. Also covers IStateStack and StateStack for parser state management, and LineText for efficient text handling. ```APIDOC ## IGrammar Interface ### Description Contract for tokenization of text. ### Methods - `TokenizeLine(lineText, state)` - `TokenizeLine2(lineText, state)` ## IToken Interface ### Description Represents a single token generated during tokenization. ### Properties - `StartIndex`: The starting index of the token. - `EndIndex`: The ending index of the token. - `Scopes`: An array of scope names. ## ITokenizeLineResult Interface ### Description Output structure for line tokenization. ### Properties - `Tokens`: An array of IToken objects. - `EndState`: The state after tokenizing the line. ## ITokenizeLineResult2 Interface ### Description A more compact representation of tokenization output. ### Properties - `Tokens`: An array of compact token representations. - `EndState`: The state after tokenizing the line. ## IStateStack Interface ### Description Contract for managing the parser's state stack. ### Methods - `Push(state)` - `Pop()` - `Peek()` ## StateStack Class ### Description Full implementation of the IStateStack contract. ## LineText Struct ### Description A struct for wrapping text with memory efficiency, often used in tokenization. ``` -------------------------------- ### Get Loaded Grammar by Scope Name Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Retrieves a previously loaded grammar by its scope name. This method does not load the grammar; it only returns cached grammars. ```csharp var grammar = registry.GrammarForScopeName("source.cs"); ``` -------------------------------- ### LoadFromLocalFile (FileInfo overload) Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Loads a grammar from a package.json file using a FileInfo object. ```APIDOC ## LoadFromLocalFile(string grammarName, FileInfo packageJsonFileInfo, bool overwrite = false) ### Description Loads a grammar from a package.json FileInfo. ### Parameters #### Path Parameters - **grammarName** (string) - Required - Name for this grammar - **packageJsonFileInfo** (FileInfo) - Required - FileInfo for package.json - **overwrite** (bool) - Optional - If true, replace existing grammar (Default: false) ### Example ```csharp options.LoadFromLocalFile("MY_LANG", new FileInfo("/path/to/package.json")); ``` ``` -------------------------------- ### Get Color Map from Theme Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Registry.md Retrieves the color map from the current theme. Returns a collection of hex color strings currently in use by the theme. ```csharp var colors = registry.GetColorMap(); foreach (var color in colors) { Console.WriteLine(color); } ``` -------------------------------- ### IThemeSetting.GetBackground() Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves the background color of a theme setting. Returns a hex color string or null. ```csharp string GetBackground() ``` -------------------------------- ### Loading Custom Grammars with RegistryOptions Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Details the process of configuring RegistryOptions to load custom grammars from local directories or files. This allows for syntax highlighting of languages not natively supported. ```csharp RegistryOptions options = new RegistryOptions(theme); options.LoadFromLocalDir(path); options.LoadFromLocalFile(name, path); new Registry(options); ``` -------------------------------- ### Core Modules - Grammars-Package Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/MANIFEST.txt Information on the RegistryOptions class for bundled grammar/theme access, ThemeName enum for built-in themes, and classes like GrammarDefinition, Language, Grammar, and Contributes for defining and structuring grammar packages. ```APIDOC ## RegistryOptions Class ### Description Options for configuring the Registry, including bundled grammar and theme access. ### Properties - `BundledGrammars`: Array of grammar definitions. - `BundledThemes`: Array of theme definitions. ## ThemeName Enum ### Description Enumeration of built-in theme identifiers. ### Members - `SolarizedLight` - `SolarizedDark` - `OneDark` - ... (21 total) ## GrammarDefinition Class ### Description Metadata for a grammar package. ### Properties - `Name`: The name of the grammar. - `ScopeName`: The scope name of the grammar. - `Path`: The file path to the grammar. ## Language Class ### Description Definition of a language, often used within grammar packages. ## Grammar Class ### Description Represents a grammar loaded from a package. ## Contributes Class ### Description Structure for VSCode-style contributions, often used in grammar packages. ``` -------------------------------- ### Range Class Definition Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/types.md Defines the Range class, a value type for line number ranges within the TextMateSharp.Model namespace. It includes properties for the start and end line numbers. ```csharp public class Range ``` -------------------------------- ### Configure TMModel After Creation Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Set the grammar for tokenization and register change listeners after the TMModel has been instantiated. ```csharp var model = new TMModel(modelLines); // Set grammar for tokenization model.SetGrammar(grammar); // Register change listeners model.AddModelTokensChangedListener(new MyListener()); ``` -------------------------------- ### Example Token Scope for JavaScript function call Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/types.md Shows the scope names assigned to a JavaScript function call, including the method call context and the function's entity name. ```json ["source.js", "meta.method-call", "entity.name.function"] ``` -------------------------------- ### IModelLines.ForEach(Action) Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Model.md Executes an action for each model line. ```APIDOC ## IModelLines.ForEach(Action) ### Description Executes an action for each model line. ### Method Signature `void ForEach(Action action)` ### Parameters #### Path Parameters - **action** (Action) - Required - Delegate to call for each line ``` -------------------------------- ### Get Scope by Language ID Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Grammars-Package.md Retrieves the grammar scope name for a given language ID. This method is helpful when you know the language ID but need its corresponding scope for grammar loading. ```csharp public string GetScopeByLanguageId(string languageId) ``` ```csharp var scope = options.GetScopeByLanguageId("csharp"); ``` -------------------------------- ### IRawThemeSetting Interface Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/INDEX.md Interface for individual settings within a raw theme. ```APIDOC ## IRawThemeSetting ### Description Theme setting. ### Methods - `GetScope()` - `GetSetting()` - `GetName()` ``` -------------------------------- ### Maintain State Across Lines for Tokenization Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/configuration.md Chain the state through tokenization to maintain context across lines, such as for multi-line comments or strings. Always starting from a null state will lose this context. ```csharp // Good: Chain state through tokenization IStateStack state = null; foreach (var line in lines) { var result = grammar.TokenizeLine(line, state, TimeSpan.MaxValue); state = result.RuleStack; } // Bad: Always start from null state foreach (var line in lines) { var result = grammar.TokenizeLine(line, null, TimeSpan.MaxValue); // Loses multi-line context (comments, strings, etc.) } ``` -------------------------------- ### LineText Conversions Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/types.md Demonstrates conversions for LineText, showing how to create a LineText from a string and convert it to ReadOnlyMemory. ```csharp LineText line = "int x = 5;"; // From string ReadOnlyMemory mem = line; // To memory ``` -------------------------------- ### IThemeSetting.GetForeground() Method Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves the foreground color of a theme setting. Returns a hex color string or null. ```csharp string GetForeground() ``` -------------------------------- ### Get GUI Color Dictionary Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/api-reference/Theme.md Retrieves a dictionary of GUI color definitions from the theme, mapping color names to their corresponding hex values. Useful for accessing specific UI element colors. ```csharp var colors = theme.GetGuiColorDictionary(); if (colors.TryGetValue("editor.background", out var bgColor)) { Console.WriteLine($"Editor background: {bgColor}"); } ``` -------------------------------- ### Load Grammar by File Extension Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/START_HERE.md Retrieve the appropriate grammar scope and load the corresponding grammar definition using the file extension. ```csharp var scope = options.GetScopeByExtension(".cs"); var grammar = registry.LoadGrammar(scope); ``` -------------------------------- ### Example Trigger for Theme Parse Error Source: https://github.com/danipen/textmatesharp/blob/master/_autodocs/errors.md Illustrates triggering a theme parse error by attempting to set a malformed theme object. This typically happens when the theme's JSON structure is invalid or missing required fields. ```csharp var malformedTheme = new MockRawTheme(); // Invalid structure registry.SetTheme(malformedTheme); ```