FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Incremental Syntax Highlighting for Code Streams

Stream syntax-highlighted code with token state, stable lines, and explicit recalls when later characters change earlier classifications.

Freshness: current•15 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

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 nkn_k be the cumulative code bytes at update kk, mm the number of updates, and n=nmn=n_m the final code size. A renderer that calls a batch highlighter on each full prefix scans Wbatch=∑k=1mnkW_{\text{batch}}=\sum_{k=1}^{m}n_k bytes. A stream tokenizer scans the newly received bytes once, Wstream≈nW_{\text{stream}}\approx n, plus any context-dependent recall work RR. For 8,192 bytes delivered in 256 chunks of 32 bytes, batch re-highlighting touches Bbatch=32(1+2+⋯+256)=1,052,672B_{\text{batch}}=32(1+2+\cdots+256)=1{,}052{,}672 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.

Receive text delta
Carry tokenizer grammar state
Emit stable line tokens or a recall
Reconcile token tail in the renderer
Finalize code block on stream end
Conceptual teaching model synthesized from:shiki-streaming-colorization,vercel-ai-sdk-ui-stream-protocol

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.

typescript
import { 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

FailureCauseControl
A keyword flashes as an identifier and later changesThe prefix ends before the lexer has enough characters or contextAccept recall events or delay publication until a stable token boundary
Earlier tokens appear twiceThe consumer appended a recall replacement without deleting the requested tailApply each recall against the current token buffer before appending
A long block freezes during generationThe UI re-highlights the whole growing source for every deltaReuse tokenizer state or coalesce batch highlighting to a frame
The closing quote is missing when the stream endsEnd-of-stream was not passed to the tokenizerClose the source and explicitly finalize pending lexical state
A code block receives the wrong grammarThe Markdown fence or metadata has not supplied a language yetUse 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.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next