> a simple quote > quote with **bold** inside > > nested quote > # heading in quote a `code` span. `code with *asterisks* inside` stays literal. An `unclosed code and more text. **bold with *italic nested* bold** *italic with `code inside` italic* **bold with `code` bold** ~~strike with **bold** strike~~ *italic [link text](https://example.com) italic* [link with **bold** and `code` inside](url) **[bold link](url) followed by bold** *~~italic strike~~* **bold *italic ~~and strike~~ back to italic* bold** `plain code` outside emphasis *italic containing inside* **bold across ![image alt](img.png) bold** `code` then **bold** then *italic* flat **bold text** *italic text* ***both*** ~~strikethrough~~ **outer *inner* outer** *emph with `code` inside* __underscore bold__ _underscore italic_ **unclosed bold \*not emphasis\* and \\ literal backslash. entity: & © * * a hard break\ continues here. ```js const x = 1; ``` ``` no language ``` ~~~python print("tilde fence") ~~~ --- title: Hello date: 2026-04-14 --- # First heading A paragraph. # Heading 1 ## Heading 2 ### Heading 3 #### Heading 4 ##### Heading 5 ###### Heading 6 # Heading with **bold** and *italic* #notaheading ####### not a heading either # a paragraph first. four spaces of code line two back to paragraph. [text](https://example.com) [with title](https://example.com "Example") [reference][label] [just brackets] ![image alt](image.png) See for details. - first bullet - second bullet * star bullet + plus bullet - [ ] open task - [x] done task - [X] capital done # Project Readme A short **intro** paragraph with a [link](https://example.com) and `inline code`. ## Install ```bash pnpm install ``` ## Features - fast - **bold** feature - [ ] roadmap item > Note: read the docs. --- See for more. above --- below *** more ___ end # Design Document: A High-Performance, Regex-Free Syntax Highlighter ## 1. Vision & Core Principles This document outlines the design for a high-performance syntax highlighting library written in JavaScript. The primary goal is to create a tokenizer that is exceptionally fast, capable of highlighting large files in real-time without impacting user interface responsiveness. **Performance Update:** Comprehensive benchmarking reveals that character scanning consistently outperforms regex in real-world tokenization scenarios. While regex shows advantages in isolated pattern matching, the overhead of string slicing, multiple pattern attempts, and failed matches makes character scanning 8-15x faster for actual parsing tasks. The architecture is guided by four core principles: - _Performance First:_ The runtime must be highly optimized. Character scanning with charCodeAt() provides the fastest tokenization, with computed array indices for state transitions (4.6x faster than string keys) and dense lookup tables for O(1) character classification. - _Separation of Concerns:_ The core runtime engine is completely language-agnostic. All language-specific logic is defined in external, declarative data files. Cross-language concerns (embedding, enrichment) live in a separate post-tokenization layer — the reclassifier — so the hot-path tokenizer never needs to know about multi-language composition. - _Declarative, User-Friendly Grammars:_ Language definitions should be intuitive for authors to create and maintain. The schema should be a high-level abstraction over the underlying state machine, focusing on describing the language's structure rather than the machine's implementation details. - _Robustness and Power:_ The system handles complex, real-world language features including nested contexts (JavaScript template literals with brace-depth-tracked interpolations), cross-language embedding (HTML hosting CSS and JavaScript, JavaScript hosting HTML/CSS via tagged templates, arbitrary host grammars hosting sub-languages), interleaved content with preserved interpolation holes (attribute-position interpolations in lit-html-style templates), and grammatical ambiguities via probe-mode contextual disambiguation. ## 2. Core Architecture The system is composed of two main parts: a generic Runtime Engine and language-specific Grammar Definitions. ### 2.1. Theoretical Model: Stack-Augmented Finite State Machine The tokenizer is modeled as a Finite State Machine (FSM), the classic computational model for lexical analysis. This allows for linear-time (O(n)) processing of the input string. See the following links for more info on FSM and compilers: - [Lexical Analysis - An application of FSM](https://swaminathanj.github.io/fsm/lexer.html) - [Lexical analysis Finite Automata](https://courses.cs.umbc.edu/331/fall13/01/notes/04/04bLexical.pdf) - [Finite State Machines in Compiler Design](https://www.tutorialspoint.com/compiler_design/compiler_design_finite_state_machines.htm) To handle nested and recursive language structures (e.g., JavaScript template literals), the FSM is augmented with a state stack. This elevates the model to a Pushdown Automaton, conceptually inspired by the hierarchical states of Statecharts. This provides a formal and robust mechanism for managing context. For more info on statecharts, see the following links: - [Statecharts definition](https://sismic.readthedocs.io/en/latest/format.html) - [State diagram](https://en.wikipedia.org/wiki/State_diagram) ### 2.2. The Runtime Engine The runtime is a small, efficient, and language-agnostic JavaScript module responsible for executing the tokenization process. #### 2.2.1. Processing Loop The core of the engine is a single `while` loop that iterates through the input string one character at a time. This loop maintains the current `position` and a `stateStack`. In each iteration, it performs a constant-time lookup based on the current character and the active state (the state at the top of the stack) to determine the next action. #### 2.2.2. Performance Optimizations **Based on comprehensive benchmarking of real tokenization scenarios:** - _Character Code Scanning:_ The foundation of performance. Using `charCodeAt()` for direct character access avoids string allocation overhead. In realistic parsing scenarios, character scanning is 8-15x faster than regex due to avoiding string slicing and multiple pattern attempts. - _Lookup Tables:_ Dense lookup tables (Uint8Array) provide O(1) performance for character classification. ASCII characters (0-127) use direct array indexing. Use computed array indices `(state * MAX_ACTIONS + action)` instead of string concatenation for transition keys - this provides 4.6x better performance. - _State Machine Implementation:_ Use pre-allocated typed arrays for the state stack. Bit-packed state stacks can be 14% faster for languages with limited nesting depth (up to 10 levels can fit in a single 32-bit integer). - _Context-Aware Chomping:_ When entering a known state (e.g., string literal, comment block), use specialized character scanning loops to consume the entire construct efficiently. This avoids the overhead of state transitions for predictable patterns. #### 2.2.3. Output Format & Token Storage The engine acts as a transducer, producing output as it processes the input ([Link for more info](https://en.wikipedia.org/wiki/Finite-state_machine)). Based on benchmarking, the optimal token storage strategy is: - **Flat Uint32Array:** Store tokens as `[type, start, end]` triplets in a single typed array - 17,534 ops/sec - fastest approach, 1.4x faster than objects - Access pattern: `tokens[i*3]` = type, `tokens[i*3+1]` = start, `tokens[i*3+2]` = end - Pre-allocate capacity to avoid reallocation during parsing - **Token Type Encoding:** Use integer IDs (0-255) instead of strings - Enables Uint8Array storage for types (1 byte vs 4 bytes) - 1.5x faster than Map lookups during rendering - Pre-compute class name array indexed by token type for O(1) rendering The final rendering of this data into styled HTML is a separate, subsequent step. ### 2.3. The Reclassifier Pipeline The tokenizer produces a raw token stream that is correct for single-language input but does not handle two important classes of problem: 1. **Multi-token lookahead refinement.** Recognizing that an `identifier` token should be reclassified as a `function` token based on multi-token patterns (Prism's "function-variable" case: `const foo = () => { }` → `foo` is a function). The state machine cannot cheaply express this — it would require chained probe states and balanced-paren matching at every `=` in the file. 2. **Cross-language embedding.** Handing off `