Mental model
Incremental syntax highlighting turns incoming code text into themed tokens while the grammar is still undecided. Keep a highlighter instance and tokenizer state, then choose whether the UI accepts stable output at line boundaries or can apply recall events that replace earlier tokens. This choice controls latency, granularity, memory, and how many revisions the renderer must reconcile.
Theory
A lexer or grammar assigns a token its role from context. The characters con may later become a keyword such as const, an identifier prefix, or text inside a string. A decorator can arrive before the line that closes its scope. Re-highlighting the full source after every delta is simple but repeatedly scans the same prefix. A stream-aware tokenizer carries grammar state across chunks and emits tokens as it can justify them.
Shiki's stream package makes an important stability choice explicit. By default, the transform emits stable tokens, usually at line granularity. When a consumer enables recall events, the highlighter can refine earlier classifications as new text changes the context; the consumer must remove the requested tail tokens before appending replacements. Appending every token blindly produces duplicated or stale color runs. Conversely, setting a line as final too early can freeze a classification that a later delimiter should have changed.
Let be the cumulative code bytes at update , the number of updates, and the final code size. A renderer that calls a batch highlighter on each full prefix scans bytes. A stream tokenizer scans the newly received bytes once, , plus any context-dependent recall work . For 8,192 bytes delivered in 256 chunks of 32 bytes, batch re-highlighting touches bytes, about 128.5 times the source length, before rendering or layout. The stream path avoids most prefix rescans but trades that work for state management and recall handling.
Stream tokens and recalls
This example keeps one highlighter instance, feeds text deltas through Shiki's transform, and reconciles recall tokens. If recalls are disabled, output is coarser but stable tokens usually arrive a line at a time. If enabled, the renderer must treat the token list as mutable state rather than as an append-only log.
typescriptimport { CodeToTokenTransformStream, type RecallToken } from "@shikijs/stream";import {createHighlighter,createJavaScriptRegexEngine,type ThemedToken,} from "shiki";const highlighter = await createHighlighter({langs: ["typescript"],themes: ["nord"],engine: createJavaScriptRegexEngine(),});const source = new ReadableStream<string>({start(controller) {controller.enqueue("const total = 4;\nif (total > 2) {\n");controller.enqueue(" console.log(\"ready");controller.enqueue("\");\n}\n");controller.close();},});const tokens: ThemedToken[] = [];const highlighted = source.pipeThrough(new CodeToTokenTransformStream({highlighter,lang: "typescript",theme: "nord",allowRecalls: true,}),);await highlighted.pipeTo(new WritableStream<ThemedToken | RecallToken>({write(token) {if ("recall" in token) {tokens.splice(Math.max(0, tokens.length - token.recall), token.recall);} else {tokens.push(token);}},}));console.log(tokens.map((token) => token.content).join(""));
The snippet demonstrates token reconciliation; a browser renderer should additionally escape token content and create text nodes rather than trusting an arbitrary HTML string. Keep the language identifier and theme fixed for the life of a block when possible. Changing either can invalidate a large part of the token stream, and an unknown language should fall back to plain text instead of failing the whole response. Cancel the source and terminate its reader on user abort so a completed highlighter does not continue consuming work for an invisible panel.
Failure modes and misconceptions
| Failure | Cause | Control |
|---|---|---|
| A keyword flashes as an identifier and later changes | The prefix ends before the lexer has enough characters or context | Accept recall events or delay publication until a stable token boundary |
| Earlier tokens appear twice | The consumer appended a recall replacement without deleting the requested tail | Apply each recall against the current token buffer before appending |
| A long block freezes during generation | The UI re-highlights the whole growing source for every delta | Reuse tokenizer state or coalesce batch highlighting to a frame |
| The closing quote is missing when the stream ends | End-of-stream was not passed to the tokenizer | Close the source and explicitly finalize pending lexical state |
| A code block receives the wrong grammar | The Markdown fence or metadata has not supplied a language yet | Use plain text until the fence language is known, then initialize the matching grammar |
Trade-offs
Stable line output simplifies a renderer because earlier token rows do not change; it can make highlighting lag behind a stream that pauses mid-line. Recall-aware output gives finer feedback, but the UI must model revisions, bound its retained token history, and test recall behavior under abrupt cancellation. Batch highlighting is appropriate for short snippets or low update rates; its cumulative rescanning cost becomes wasteful when a large code block changes many times per second.
Do not equate token arrival with code validity. A code stream can end halfway through a string or block comment, and highlighted output must preserve the raw text so the final source remains recoverable. If the product supports selecting or copying code, copy the uncolored source, not concatenated HTML or decorated spans. Keep keyboard focus and selection stable when tokens are recalled.
Decision scenario
A coding assistant streams a 200-line TypeScript patch in short deltas. The highlighter displays a token for each chunk, but nested template literals cause several earlier tokens to be reclassified. The renderer currently appends all tokens, so duplicate spans accumulate. Enable recall-aware output and apply each recall to the tail of the token buffer, or choose stable line granularity if simpler rendering and less visual revision matter more than character-level speed.
Learning outcomes
- Distinguish stable token streaming from recall-aware token revisions.
- Estimate repeated highlighting work for a growing code prefix.
- Preserve source text, grammar state, and renderer state separately while handling cancellation and incomplete lexical constructs.