A grammar finds spans; the role map names them; the theme gives them a visible style.
Keep the source of each decision visible
Syntax highlighting is often presented as a single language definition that somehow turns code into colored HTML. The implementation here separates that work into inspectable steps. The article chooses a grammar ID. The catalog resolves that ID to a PEG file or profile and a sibling role map. The highlighter combines the language grammar with shared lexical rules and symbols, then asks TextFamily to process the source. A packet is lowered into source intervals, intervals are mapped to semantic roles, and the HTML renderer escapes each slice before wrapping it.
This division is useful for the blog and Writing Studio because both render code through the same framework component. The browser receives finished HTML and a stylesheet dependency in the appropriate resource slot. It does not parse PEG files, load TextFamily, or decide how a source string should be tokenized.
Discovery is based on the grammar's location
GrammarCatalog recursively scans the roots supplied by the consuming application. A standalone powershell.peg file is selectable when it has a sibling powershell.roles file. Its grammar ID comes from the relative path: grammars/powershell.peg becomes powershell; a nested file can become a namespaced ID such as ecmascript/json. The application does not need to hardcode every grammar in a list just to make it selectable.
Profiles allow a language family to be composed from ordered PEG fragments. The ECMAScript profiles share a core and add dialect-specific keywords or host names in a deliberate order. Each profile line names one relative fragment; profile validation rejects absolute paths, parent-directory traversal, duplicate entries, and malformed lines. The first fragment provides the Token scanning rule. After the profile is composed, the shared Common.peg lexicon is appended.
This keeps grammar families maintainable without copying common rules into each application. The grammar composer project owns grammar and profile files; a consuming application points at the shared grammar root and may add a local root for app-specific language extensions. Shared definitions retain priority when an ID exists in both roots.
Ordered PEG rules define the scanner's boundaries
A PEG source is executable grammar input to TextFamily, not a regular-expression bundle. Rule order in Token makes the scanner try comments, strings, numbers, keywords, identifiers, operators, and punctuation in a controlled sequence. A catch-all Other rule is last so that an unfamiliar character does not disappear from the output.
The LiveScript grammar is an existing example from the language the framework uses. It recognizes its wordlist and wordmap delimiters, backtick templates, comments, numeric suffixes, and operators. Named spellings such as @comment_open and @btick come from the shared symbol catalog; reusable character rules such as IdentifierStart, DecimalDigits, and LineBreak come from Common.peg. Reusing these definitions keeps the grammar readable and gives punctuation one consistent name across grammars.
Token <- Comment / DoubleQuotedString / Keyword / Identifier / Whitespace / Other
Comment <- @hash LineCommentBody
Keyword <- ('let' / 'return') !IdentifierContinue
Other <- .
The negative lookahead !IdentifierContinue is a boundary check: it lets the keyword rule accept return when the next character is not part of an identifier, while leaving returning to the generic identifier rule. Ordered alternatives also need care for prefixes. If for appears before foreach in a keyword choice, the shorter spelling can prevent the longer one from being considered. The PowerShell scanner puts foreach first, and the role map assigns Keyword the semantic keyword role.
These rules are scanners, not complete language parsers. The LiveScript source is a lexical projection for highlighting, and the PowerShell file classifies common source forms without proving that a command exists or that a script is valid for a particular release. Context-sensitive distinctions such as slash-as-division-or-regexp require more than a purely local token shape. The grammar documentation states those limits so a colorizer is not mistaken for a validator.
TextFamily returns structured spans, not HTML
The highlighter calls the TextFamily tool with the source, the composed PEG text, the symbol catalog, and the query mode grammar. TextFamily returns a packet. The framework's textfamily.Packet module lowers and type-checks that packet, then extracts annotation spans. TokenMap keeps only annotations whose kind is rule and whose rule name has a role mapping. The resulting tokens are sorted by source start and checked so their intervals stay ordered, non-overlapping, and inside the source.
This is an important boundary: the PEG engine describes matches and source locations, while the framework decides which annotations should become visual tokens. A grammar may include helper rules that are useful to composition but absent from the .roles file; those matches do not acquire an accidental style. The role map is an explicit allowlist between grammar implementation details and the theme's semantic classes.
Render only after validating and escaping every interval
The HTML renderer receives the original source, validated token spans, role names, and optional annotation spans. It builds a sorted set of interval boundaries, slices the source at those points, escapes each slice with the framework's HTML entity component, and wraps the escaped slice in a semantic span. Yellow highlight, red strike, and cyan underline annotations are a separate presentation layer and may wrap syntax tokens without changing the source offsets.
The result is deterministic HTML, not a string assembled by inserting untrusted source directly. The CodeBlock component places it inside pre and code elements, sets a grammar marker for the syntax stylesheet, and returns the style resources through net.html.Component. A fragment loader can read those dependencies and insert them into the target page's slots before displaying the incoming fragment.
highlighted = required (highlighter.try-highlight source, 'lscript'), 'Unable to highlight LiveScript'
{ value: html, error } = try-escape-html source.slice start, end
throw error if error isnt void
token = { start, end, role: 'keyword' }
Literal rules solve a different problem
A literal highlight is intentionally simpler: it searches for exact substrings and assigns the selected CSS class. It does not invoke TextFamily, consult a grammar catalog, or distinguish whether the match appears inside a string or identifier. The Writing Studio's class pulldown helps authors choose an existing syntax class, and the saved article stores each rule as text plus className. LiveScript code refers to that property with its idiomatic class-name spelling. CodeBlock gives literal highlighting precedence for that block so the two matching models do not compete over the same source characters.
The distinction is practical. Use PEG when the desired color follows language structure and many token kinds. Use a literal rule when the desired emphasis follows one or a few strings chosen by the author. The component makes either result safe HTML, but the grammar pipeline stays separate from direct substring matching.
Reusable grammars improve the whole toolchain
The grammar catalog serves more than the public blog. The Writing Studio uses its grammar IDs to populate the language pulldown, and the same highlighter renders the in-memory article preview. A new grammar in the shared composer project becomes available to each configured consumer without copying a second grammar file into the blog. Its .roles mapping and theme role still need to agree, and its examples and limitations belong in the grammar documentation.
This architecture leaves each decision in a place that can be reviewed: language spelling in the article, rule ordering in the PEG, reusable characters and delimiters in the common lexicon and symbols, semantic classification in .roles, colors in the theme, spans in the TextFamily packet, escaping in the framework HTML renderer, and stylesheet dependencies in the component result. That is the implementation contract behind the colored code sample.
