danipen/TextMateSharp

TextMateSharp Documentation

Generated May 13, 2026View repository β†—

Project Documentation

πŸš€ 1. Overview

TextMateSharp: A .NET-Powered TextMate Grammar Interpreter

Project Overview

TextMateSharp is a .NET implementation of the TextMate grammar system, designed to bring syntax highlighting, tokenization, and theming capabilities to the .NET ecosystem. It serves as a port of Microsoft’s vscode-textmate and is inspired by the Java-based eclipse/tm4e. The project enables developers to parse, tokenize, and apply syntax highlighting to code using TextMate grammar files (.tmLanguage.json), which are widely used in editors like VS Code.

A key differentiator of TextMateSharp is its integration with the Oniguruma regex engine via the Onigwrap NuGet package, allowing for high-performance pattern matching in .NET applications. This makes it particularly useful for custom code editors, IDEs, and syntax-highlighting tools built on .NET platforms. The library is already leveraged by projects such as AvaloniaEdit, a cross-platform text editor component.

Beyond core tokenization, TextMateSharp provides pre-bundled grammars for 50+ programming languages (C#, Python, JavaScript, etc.) and themes (Dark+, Monokai, Dracula, etc.), making it a one-stop solution for syntax highlighting in .NET applications. Its modular design allows developers to load custom grammars or use the included ones, while its theme system ensures consistent visual styling across different languages.

The project is actively maintained, with CI/CD pipelines for automated testing and NuGet package deployment. It follows semantic versioning and is distributed under the MIT License, ensuring broad compatibility and ease of adoption.


Core Purpose & Problem Solved

TextMateSharp addresses a critical gap in the .NET ecosystem: the lack of native support for TextMate-style syntax highlighting. While VS Code and other editors rely on TextMate grammars, .NET developers previously had to reimplement syntax parsing or use workarounds to achieve similar functionality. TextMateSharp eliminates this barrier by providing a fully managed .NET library that interprets TextMate grammars with high fidelity.

Primary Use Cases:

  1. Custom Code Editors & IDEs
    • Developers building text editors (e.g., AvaloniaEdit) can integrate TextMateSharp to provide real-time syntax highlighting without reinventing the wheel.
  2. Syntax Highlighting in Web & Desktop Apps
    • Applications that display or edit code (e.g., documentation tools, REPL interfaces) can use TextMateSharp to tokenize and style code snippets.
  3. Language Server Protocol (LSP) Support
    • TextMateSharp can be used in LSP servers to provide syntax-aware features like code folding, auto-indentation, and error detection.
  4. Cross-Platform Development
    • Since it runs on .NET Core/.NET 5+, it supports Windows, Linux, and macOS, making it ideal for cross-platform tools.

Key Problems Solved:

ProblemSolution
No native .NET TextMate grammar supportProvides a full .NET implementation of TextMate’s grammar system.
Performance overhead in regex-based parsingUses Oniguruma via Onigwrap for optimized pattern matching.
Manual grammar/theme managementIncludes 50+ pre-built grammars and 15+ themes out of the box.
Inconsistent syntax highlighting across editorsEnsures VS Code-compatible highlighting in .NET apps.
Complexity in integrating syntax parsingSimplifies tokenization with a clean, object-oriented API.

Tech Stack at a Glance

CategoryTechnologyPurpose
Core LanguageC# (.NET 6+)Primary implementation language for the TextMate grammar interpreter.
Regex EngineOniguruma (via Onigwrap)High-performance regex engine for pattern matching in grammars.
Grammar FormatJSON (.tmLanguage.json)Standard format for TextMate grammars, parsed by TextMateSharp.
TestingxUnit / MochaUnit and integration testing for grammar parsing and tokenization.
Build System.NET CLI / MSBuildCompiles and packages the library for NuGet distribution.
CI/CDGitHub ActionsAutomates testing, building, and NuGet package publishing.
Package ManagerNuGetDistributes the library and bundled grammars/themes as NuGet packages.
ThemingCustom Theme EngineApplies color schemes (e.g., Dark+, Monokai) to tokenized text.
Demo Application.NET Console AppProvides a working example of TextMateSharp in action.

Architecture & Key Components

TextMateSharp follows a modular architecture, separating concerns into distinct components:

  1. Grammar Loading & Parsing

    • The Registry class loads .tmLanguage.json files and initializes grammars.
    • Grammars define token patterns (regex-based) for syntax highlighting.
  2. Tokenization Engine

    • The IGrammar interface tokenizes input text into scoped tokens (e.g., keyword, string, comment).
    • Uses Oniguruma for efficient regex matching.
  3. Theme Application

    • Themes (e.g., DarkPlus, Monokai) map token scopes to foreground/background colors.
    • The Theme class handles theme resolution and style application.
  4. State Management

    • The IStateStack tracks the current parsing state (e.g., inside a multi-line comment).
    • Ensures correct tokenization across line breaks.
  5. Bundled Assets

    • 50+ Grammars: Pre-defined syntax rules for popular languages.
    • 15+ Themes: Visual styles compatible with VS Code themes.

Example Workflow:

  1. A developer loads a grammar (e.g., source.cs).
  2. TextMateSharp tokenizes input code into scoped tokens.
  3. The Theme engine applies colors/styles based on token scopes.
  4. The result is syntax-highlighted output (e.g., for a custom editor).

Comparison with Alternatives

FeatureTextMateSharpRoslyn (C#)ANTLRPygments (Python)
Grammar FormatTextMate (.tmLanguage.json)Roslyn Syntax TreesANTLR Grammar FilesCustom Python Rules
Language Support50+ Languages (via grammars)C# OnlyAny (with grammar definition)300+ Languages
.NET Integrationβœ… Native .NET Libraryβœ… Native❌ (Requires Java/.NET bridge)❌ (Python-based)
Performance⚑ High (Oniguruma regex engine)⚑ Very High⚑ High⚑ Medium
Theming Supportβœ… Built-in (VS Code-compatible themes)❌ Limited❌ (Requires custom setup)βœ… (Customizable)
Use CaseCustom editors, IDEs, syntax highlightingC# Code AnalysisLanguage ParsingDocumentation, Web Highlighting
TextMateSharp stands out for .NET developers who need VS Code-compatible syntax highlighting without relying on external tools or bridges.

Future Directions & Community Impact

TextMateSharp is positioned to become the de facto standard for TextMate grammar support in .NET. Potential enhancements include:

  • Cross-Grammar Injection Support (currently unsupported).
  • Enhanced LSP Integration (e.g., for IntelliSense).
  • More Themes & Grammars (community-driven contributions).
  • Performance Optimizations (e.g., caching compiled regex patterns).

By providing a robust, open-source solution, TextMateSharp empowers .NET developers to build advanced text-editing features without reinventing syntax parsing. Its alignment with VS Code’s grammar system ensures consistency across tools, fostering a more unified developer experience.

For contributions, users can engage via GitHub issues, pull requests, or the Felgo QML extension (which uses TextMateSharp for QML syntax highlighting). The project’s MIT License encourages adoption in both open-source and commercial applications.


Final Verdict: TextMateSharp is a must-have library for any .NET developer working with syntax highlighting, code editors, or language services. Its performance, compatibility, and ease of use make it a game-changer for the .NET ecosystem. πŸš€


πŸ“‚ 2. Project Structure

Directory Structure

The codebase contains the following primary files and directories:

  • .build/GetBuildVersion.psm1
  • .gitattributes
  • .github/FUNDING.yml
  • .github/ISSUE_TEMPLATE/bug_report.md
  • .github/ISSUE_TEMPLATE/feature_request.md
  • .github/workflows/codeql.yml
  • .github/workflows/dotnet.yml
  • .github/workflows/nuget.yml
  • .gitignore
  • .idea/.idea.TextMateSharp.dir/.idea/.gitignore
  • .idea/.idea.TextMateSharp/.idea/.gitignore
  • .runsettings
  • LICENSE.md
  • README.md
  • TextMateSharp.sln
  • build/Directory.Build.props
  • build/SourceLink.props
  • src/TextMateSharp.Benchmarks/BigFileTokenizationBenchmark.cs
  • src/TextMateSharp.Benchmarks/Program.cs
  • src/TextMateSharp.Benchmarks/TextMateSharp.Benchmarks.csproj

Generated via local analysis.


πŸ—οΈ 3. Architecture & Data Flow

TextMateSharp Architecture Deep Dive

1. Architecture Reasoning & Module Interactions

TextMateSharp is a .NET port of the VS Code TextMate engine, designed to parse and tokenize source code using TextMate grammar files (.tmLanguage.json). It is structured as a modular, extensible system with clear separation of concerns between grammar parsing, tokenization, theme application, and model management.

Core Architectural Principles

  1. Separation of Concerns (SoC)

    • Grammar Parsing (TextMateSharp.Grammars) β†’ Handles .tmLanguage.json and .tmTheme files.
    • Tokenization (TextMateSharp) β†’ Converts source code into semantic tokens.
    • Theme Application (TextMateSharp.Themes) β†’ Maps tokens to visual styles.
    • Model Management (TextMateSharp.Model) β†’ Tracks token changes and line states.
  2. Dependency Injection & Registry Pattern

    • The Registry class acts as a centralized dependency container, managing grammar and theme loading.
    • Uses IRegistryOptions to abstract grammar resolution (e.g., embedded vs. external grammars).
  3. Stateful Tokenization

    • Uses a stack-based state machine (StateStack) to track parsing context across lines.
    • Supports incremental parsing (resuming from a previous state).
  4. Oniguruma Regex Engine Integration

    • Relies on Onigwrap (a .NET wrapper for Oniguruma) for advanced regex matching (e.g., balanced brackets, lookaheads).
  5. Immutable & Thread-Safe Design

    • Many components (Token, StateStack, Theme) are immutable to ensure thread safety.
    • Uses functional-style parsing (e.g., TokenizeLineResult is returned as a new object rather than modifying state).

2. Data Flow & State Transitions

OriginActionLogic HandlerResulting State
Registry.LoadGrammar()Loads a grammar from .tmLanguage.jsonGrammarReader parses JSON into IRawGrammarGrammar is cached in Registry
Grammar.TokenizeLine()Tokenizes a line of textLineTokenizer processes text using StateStackReturns ITokenizeLineResult with tokens and new StateStack
Theme.Match(token.Scopes)Applies syntax highlightingTheme searches for matching rules in ThemeTrieElementReturns IThemeSetting with foreground/background colors
TMModel.UpdateModel()Updates tokenization for a documentTokenizer processes lines incrementallyFires ModelTokensChangedEvent
RuleFactory.CreateRule()Compiles a regex patternRegExpSource optimizes regex for OnigurumaReturns CompiledRule for tokenization

3. High-Level Mermaid.js Architecture Diagram


4. Detailed Breakdown of Key Components

4.1. Grammar System (TextMateSharp.Grammars)

  • RegistryOptions β†’ Defines where grammars/themes are loaded from (embedded vs. filesystem).
  • GrammarReader β†’ Parses .tmLanguage.json into IRawGrammar.
  • Grammar β†’ Compiles rules into a tokenization engine.
  • RuleFactory β†’ Converts raw grammar rules into executable regex patterns.

4.2. Tokenization (TextMateSharp)

  • LineTokenizer β†’ Processes a single line of text using a StateStack.
  • StateStack β†’ Tracks parsing state (e.g., inside a comment, string, or block).
  • TokenizeLineResult β†’ Returns tokens with scopes (e.g., source.cs,keyword.other).

4.3. Theme System (TextMateSharp.Themes)

  • ThemeReader β†’ Parses .tmTheme files into IRawTheme.
  • Theme β†’ Maps token scopes to visual styles (colors, font styles).
  • ThemeTrieElement β†’ Optimized lookup for theme rules.

4.4. Model (TextMateSharp.Model)

  • TMModel β†’ Manages tokenization across multiple lines.
  • ModelTokensChangedEvent β†’ Notifies UI of token changes (e.g., for syntax highlighting).

4.5. External Dependencies

  • Onigwrap β†’ .NET wrapper for Oniguruma regex engine (used for advanced pattern matching).
  • SimpleJSON β†’ Lightweight JSON parser for .tmLanguage.json files.

5. Advanced Design Patterns Used

PatternUsageExample
Registry PatternCentralized grammar/theme managementRegistry class
State PatternTracks parsing state across linesStateStack
Factory PatternCompiles grammar rules into executable patternsRuleFactory
Visitor PatternApplies theme rules to tokensTheme.Match()
Immutable ObjectsEnsures thread safetyToken, StateStack
Observer PatternNotifies UI of token changesModelTokensChangedEvent

6. Performance Optimizations

  1. Regex Compilation
    • Rules are pre-compiled into RegExpSource for faster matching.
  2. State Stack Caching
    • Reuses StateStack across lines to avoid reprocessing.
  3. Theme Trie Lookup
    • Uses a trie structure for O(log n) theme rule matching.
  4. Incremental Parsing
    • Only re-tokenizes modified lines (used in TMModel).

7. Extensibility & Customization

  • Custom Grammars β†’ Can be loaded via IRegistryOptions.
  • Custom Themes β†’ Can be loaded via RegistryOptions.
  • Language Extensions β†’ Supports injecting custom rules (e.g., for embedded languages like HTML in PHP).

8. Error Handling & Robustness

  • Graceful Fallbacks β†’ If a grammar fails to load, falls back to plain text.
  • Timeout Handling β†’ TokenizeLine() supports cancellation via TimeSpan.MaxValue.
  • Validation β†’ Ensures .tmLanguage.json files conform to expected schemas.

Conclusion

TextMateSharp is a well-structured, modular, and performant implementation of TextMate’s grammar system in .NET. It leverages functional programming principles, design patterns, and efficient data structures to provide a robust syntax highlighting engine. The separation of grammar parsing, tokenization, and theme application makes it highly extensible for custom use cases.

Would you like a deeper dive into any specific component (e.g., StateStack implementation, Theme matching algorithm)?

πŸ“ˆ System Architecture Diagram

Rendering diagram…

πŸ› οΈ 4. Function Breakdowns

Analysis of Source Files

The provided source files are primarily related to the TextMateSharp project, a .NET implementation of the TextMate grammar system. The files include configuration files, test files, and documentation.

.github/FUNDING.yml

Function/Export NameParametersLogic DescriptionImpact
githubdanipenSpecifies the GitHub username for fundingFunding information for the project

src/TextMateSharp.Grammars.Tests/GrammarAssets/qml/package.json

Function/Export NameParametersLogic DescriptionImpact
namefelgoSpecifies the name of the packagePackage identification
version2.0.1Specifies the version of the packagePackage versioning
enginesvscode: ^1.81.0Specifies the compatible version of VSCodeCompatibility with VSCode
categoriesProgramming Languages, OtherSpecifies the categories for the packagePackage categorization
activationEventsonCommand:qml.runWebLive, ...Specifies the events that activate the packagePackage activation

README.md

Function/Export NameParametersLogic DescriptionImpact
InstallationProvides instructions for installing TextMateSharpInstallation of the project
UsageProvides an example of how to use TextMateSharpUsage of the project
BuildingProvides instructions for building TextMateSharpBuilding of the project
Supported LanguagesLists the supported languages for syntax highlightingSyntax highlighting support
Available ThemesLists the available themes for syntax highlightingTheme support

.github/ISSUE_TEMPLATE/bug_report.md

Function/Export NameParametersLogic DescriptionImpact
Bug ReportProvides a template for reporting bugsBug reporting
Describe the bugSpecifies the section for describing the bugBug description
To ReproduceSpecifies the section for steps to reproduce the bugBug reproduction
Expected behaviorSpecifies the section for expected behaviorExpected behavior
ScreenshotsSpecifies the section for adding screenshotsScreenshot addition
DesktopSpecifies the section for desktop informationDesktop information
Additional contextSpecifies the section for additional contextAdditional context

.github/workflows/nuget.yml

Function/Export NameParametersLogic DescriptionImpact
Publish NuGet packageSpecifies the workflow for publishing NuGet packagesPublishing of NuGet packages
Createtags: v*Specifies the event that triggers the workflowWorkflow triggering
JobsbuildSpecifies the job for building and publishing the packagePackage building and publishing
EnvBUILD_CONFIG: 'Release', SOLUTION: 'TextMateSharp.sln'Specifies the environment variables for the jobEnvironment variable setup
StepsSpecifies the steps for the jobJob steps
Extract branch nameExtracts the branch name from the tagBranch name extraction
Restore dependenciesRestores the dependencies for the projectDependency restoration
Setup .NETSets up the .NET environment for the job.NET environment setup
BuildBuilds the projectProject building
Run testsRuns the tests for the projectTest execution
PublishPublishes the NuGet packagePackage publishing
Note: This analysis provides a high-level overview of the provided source files. For a deeper understanding, it is recommended to review the code and documentation in more detail.