On Highlighting Code
(CLICK TO HIGHLIGHT ART – SEIZURE WARNING)
Today, we’re excited to announce the public release of a new library we call Highlights.
Highlights is a syntax highlighter written in WebAssembly Text, or WAT. It supports over 70 built-in languages, uses Zed-compatible themes, and produces HTML or themed tokens. It also handles streaming input and incremental edits, so applications can keep highlighting as their code changes.
Highlights generates HTML at up to 298× Shiki’s throughput across the large-file fixtures below.
- Highlights
- 297
- Tree-sitter (N-API)
- 11.3
- Shiki
- 1.22
- Highlights
- 615
- Tree-sitter (N-API)
- —
- Shiki
- 2.8
- Highlights
- 928
- Tree-sitter (N-API)
- 25.6
- Shiki
- 5.89
- Highlights
- 320
- Tree-sitter (N-API)
- 9
- Shiki
- 1.07
Bun 1.4.0 · Apple M4 Pro · October 5, 2026 · — not measured
These recorded results are from October 5, 2026, using Bun 1.4.0 on an Apple M4 Pro. Highlights includes UTF-8 encoding and HTML decoding; Shiki is the string-API baseline, and Tree-sitter uses
tree-sitter-highlight1.1.2. Each case gets a 200 ms warm-up and a 1.5-second sampling budget, with at least 20 samples and a rotating contender order. Throughput uses the median of per-call averages from roughly 5 ms batches. To reproduce these results, check out the benchmark.
Background
Syntax highlighting is surprisingly expensive.
Historically in Diffs we’ve used the excellent Shiki library and then relied on workers to help keep this work off the main thread, and caches to help avoid repeating it.
This has been fine, but particularly as we’ve invested more into our edit functionality, syntax highlighting has become more and more an unavoidable bottleneck for us.
How mainstream code highlighters work
A highlighter breaks code into tokens. In
const greeting = "hello";, it recognizes const as a
keyword and "hello" as a string, then uses a theme to assign
colors. It can return tokens for a renderer or HTML with styled spans. Identifying the
tokens takes most of the work.
Regular expressions
regex is the death of performance. - @aidenybai
Shiki, Prism, highlight.js, and Rangi all use regular expressions to match tokens. Regex gives them a compact way to describe what a keyword, number, or quoted string looks like. In engines such as Prism, adding a language means defining those patterns and letting the same engine do the matching. That makes language support easier to build and extend.
The cost comes from how much matching happens. Different rules can scan the same stretch of code, each looking for its own pattern. Complex expressions can also backtrack: when a match fails, the engine revisits characters and tries another path. A single regex can be fast, but applying a whole grammar means paying for successful matches, failed attempts, and repeated scans. Across large files or code highlighted after every edit, that work adds up.
Syntax trees
Tree-sitter takes another approach. It parses source code into a concrete syntax tree, which retains details such as punctuation, then uses queries to assign highlight names to nodes in that tree. A theme maps those names to styles.
That structure lets highlighting rules distinguish a function name from a parameter by its place in the code. Building, storing, and querying the tree takes time and memory, but the tree can also support features such as code navigation. After an edit, Tree-sitter can update it incrementally and reuse unchanged parts. A full-file benchmark measures a different workload from maintaining a tree while someone types.
A learned lexer on the GPU
Recently, Shu Ding
introduced gpu-lexer from Vercel Labs, an experimental highlighter that uses a small learned model running on WebGPU. One
model handles different languages without requiring a language argument or a separate
grammar for each one.
The CPU first splits the source into simple parts, such as words, whitespace, and symbols.
The GPU processes features from those parts and their context, then predicts one of nine
visual classes. The public API, await parse(code), returns classified spans
with JavaScript string offsets. The
project README describes
that pipeline and its requirement for WebGPU in a secure browser context.
The learned approach is interesting because it can attempt to highlight a language it has never been explicitly configured to support. Its quality depends on what the model learned and how well that transfers to the input. The model card explains that evaluation measures agreement with Shiki's labels, rather than semantic correctness.
- Highlights0.2.0 · themed tokens
- 81.6ms
- gpu-lexerspans
- 400.8ms
- Sugar HighHTML
- 761.6ms
- Prism.jsHTML
- 994.4ms
- Highlight.jsHTML
- 1.35s
- Starry NightHAST
- 10.50s
- Shikitokens
- 28.28s
Chromium 153 · Apple M4 Pro · October 21, 2026
The chart shows the October 21, 2026 run with Highlights 0.2.0 from npm: median times from three passes, with one warm-up in a fresh worker for each sample; initialization and DOM rendering are excluded. Highlights and Shiki use
codeToTokens(), returning themed JavaScript tokens. gpu-lexer returns classified spans; Starry Night returns a HAST tree; Sugar High, Prism.js, and Highlight.js return HTML. The recorded samples include versions and run conditions. This measures time for those API paths on one large JavaScript input; it does not measure highlighting quality.
How @pierre/highlights works
The core pipeline is fairly small:
JavaScript handles the public API, input encoding, and theme preparation. The WebAssembly module scans the source and emits HTML or token records. There is no syntax tree to construct along the way. The architecture notes describe the boundaries in more detail.
Give each language a lexer
A lexer walks through source text and identifies meaningful ranges: a keyword, a number, a comment, a string. In Highlights, these lexers are written by hand in WAT and share scanners for common operations.
More complicated languages need more state. Embedded languages also need a way to hand
control to another lexer. The JavaScript lexer, for example, can scan an HTML
<script> region within its bounds, then return control to the HTML
lexer. Supported Markdown code fences work through the same general idea.
This makes language support explicit. Adding a language means implementing and maintaining its lexer. Existing TextMate grammars cannot simply be loaded into Highlights, and the output will not always classify code exactly as Shiki or Tree-sitter would.
For example, in the TypeScript statement const greeting = 1;, Highlights
classifies greeting as a variable, while Shiki assigns it the
TextMate scope variable.other.constant.ts. With their bundled GitHub Dark
themes, that identifier uses the foreground color in Highlights and blue in Shiki. If
matching existing highlighting matters, compare representative files before switching.
Scan more bytes at once
A lot of source code consists of stretches where nothing interesting happens. Inside a line comment, the lexer mostly needs to find the next line ending. Inside a quoted string, it can skip ahead until it encounters a quote, an escape, or another character that needs special handling.
Highlights uses WebAssembly SIMD for several of these scans. SIMD lets one instruction operate on multiple values at once; here, a scanner can load 16 bytes and compare all of them against the characters it is looking for. The comparisons produce a bit mask, which identifies the first matching position.
That lets the scanner advance through a long comment 16 bytes at a time. Short, common cases still matter: whitespace scanning has a scalar path for the small gaps between tokens, avoiding SIMD setup when there is little to scan.
Keyword lookup also uses tables prepared during the build. The lookup hashes selected bytes and the word length, then checks the candidate's exact bytes. Language keywords become data the lexer can look up directly.
Emit the output while scanning
For HTML, the emitter writes escaped text and styled spans directly into WebAssembly memory. JavaScript prepares the theme ahead of time; ordinary color themes become a compact table containing color and font settings for each token type.
Neighboring ranges with the same style can share a span, including the whitespace between them. Span opening tags are cached for reuse. These details reduce both the work of producing HTML and the amount of markup the browser receives.
The API exposes that output as UTF-8 bytes:
import { codeToHtml } from '@pierre/highlights';
import { pierreDark } from '@pierre/highlights/themes';
const bytes = codeToHtml('const greeting = "hello";', {
lang: 'js',
theme: pierreDark,
});
const html = new TextDecoder().decode(bytes);
The package runs in Node.js, browsers, and Cloudflare Workers. It initializes WebAssembly automatically, so highlighting calls are synchronous after import.
Highlights accepts Zed-compatible theme objects. You can import a bundled theme, such as
pierreDark or githubLight, from
@pierre/highlights/themes, or supply your own.
Streaming and incremental editing
Highlighting a complete file quickly helps, but live interfaces also need to handle text that is still arriving or being edited.
StreamTokenizer
accepts chunks of text or UTF-8 bytes and emits themed tokens for completed lines. It
preserves lexer state between chunks, so a comment or string can continue into the next
chunk without rescanning earlier lines. An incomplete final line stays buffered until a
newline arrives or the caller finishes the stream with end().
import { StreamTokenizer } from '@pierre/highlights';
import { pierreDark } from '@pierre/highlights/themes';
const response = await fetch('https://example.com/source.ts');
const lines = response.body.pipeThrough(
new StreamTokenizer({ lang: 'ts', theme: pierreDark })
);
for await (const tokens of lines) {
console.log(tokens);
}
LiveTokenizer
handles edits to existing text. It keeps the document, per-line token records, and saved
lexer states in its own WebAssembly instance. After an edit, it tokenizes the affected
lines and continues until the outgoing state matches the previously saved state at an
unchanged boundary. Beyond that point, the existing results can be reused.
import { LiveTokenizer } from '@pierre/highlights';
import { pierreDark } from '@pierre/highlights/themes';
const live = new LiveTokenizer({
code: 'let count = 1;\nconsole.log(count);',
lang: 'js',
theme: pierreDark,
});
live.applyEdits([{
range: { start: { line: 0, character: 12 }, end: { line: 0, character: 13 } },
newText: '2',
}]);
console.log(live.getLineText(0)); // let count = 2;
console.log(live.getLineTokens(0).tokens);
live.dispose();
Some edits still affect the whole file. Opening a multiline comment near the top can
change how every following line is tokenized. With renderRange, the live
tokenizer processes lines through the end of the visible range, including preceding dirty
lines needed to establish its lexer state. It finishes the remaining work in background
slices and delivers those tokens through onDeferTokenize. The editor can
update visible lines while the rest catches up.
Why we chose WAT
WAT is the text representation of WebAssembly instructions. Writing it by hand means working directly with loads, stores, branches, and vector operations. Which isn't the most fun…
Rust and Zig can both compile to WebAssembly and provide control over memory and SIMD.
However, our preference for WAT is about the workflow: the source expresses the loads, comparisons, and branches we want to inspect and tune.
For example, the 16-byte comment scan is written directly as a vector load, comparisons, and a bit-mask check. With a program built mostly from scans like this, working in that instruction representation is useful. The choice also gives us more details to maintain ourselves.
WAT preprocessing
Writing every table and constant by hand would make the lexers harder to maintain. Our preprocessor adds a few forms to the source and expands them into standard WAT during the build.
Local imports bring shared code into one module, including each file once. Enums give token types numeric IDs, and named constants let scanners refer to memory addresses without repeating raw offsets.
(import "./langs/tsx.wat")
WABT assembles the expanded WAT into WebAssembly, and Binaryen then optimizes it. These conveniences are resolved during the build, so the runtime still scans bytes with ordinary WebAssembly instructions.
Memory control
The module uses WebAssembly's linear memory, a growable buffer addressed by byte offsets. Highlights assigns space for control data, tables, lexer state, input, and output. Strings can be encoded directly into the input region, and the emitter writes into an output region that grows as needed.
This lets the HTML path process token ranges without allocating a JavaScript object for every token. The live tokenizer has a separate heap for document text, line records, and saved states, which it can retain across edits.
The ownership rules are visible in the API. codeToHtml() returns bytes backed
by reusable memory: decode them immediately, as in the example above, or copy them with
.slice() before the next highlighting or tokenization call. Requesting themed
JavaScript tokens creates objects, while consumers of raw records can defer that work.
- Highlights
- 37
- Shiki JS
- 80
- Shiki Wasm
- 148
- Highlights
- 37
- Shiki JS
- 78
- Shiki Wasm
- 147
- Highlights
- 38
- Shiki JS
- 91
- Shiki Wasm
- 181
- Highlights
- 41
- Shiki JS
- 91
- Shiki Wasm
- 171
- Highlights
- 50
- Shiki JS
- 155
- Shiki Wasm
- 349
- Highlights
- 55
- Shiki JS
- 112
- Shiki Wasm
- 303
- Highlights
- 104
- Shiki JS
- 739
- Shiki Wasm
- 963
- Highlights
- 133
- Shiki JS
- 326
- Shiki Wasm
- 488
Five fresh processes per case · Bun 1.4.0 · Apple M4 Pro · October 5, 2026
RSS includes the runtime, compiled code, Wasm, and allocator capacity; HTML output includes decoding for Highlights. Both libraries use GitHub Dark. Highlights includes all built-in lexers; Shiki loads TypeScript with line-length and time limits disabled. These recorded results are from October 5, 2026, using Bun 1.4.0 on an Apple M4 Pro. The benchmark data records the methodology.
Size control
The scanners, keyword tables, language dispatch, and emitters all live in one module. Shared operations can be reused across lexers, and the build can control how tables and constants are represented.
One small example is a vector filled with the same byte. A full vector constant takes more space to encode than loading one small integer and repeating it across the vector. The build rewrites these repeated-byte constants after optimization to recover those bytes.
The Wasm module in published Highlights 0.2.0 is 183,180 bytes, or 84,987 bytes with gzip level 9. Those figures cover its 80 built-in languages; the JavaScript wrapper and theme assets are additional.
- Sugar Highmajor 6 web languages
- 5.4KB
- Prism.jsmajor 6 web languages
- 8.6KB
- Sugar Highall 29 languages
- 8.8KB
- Highlight.jsmajor 6 web languages
- 14.9KB
- gpu-lexerone model
- 27.4KB
- Highlights 0.2.0all 80 languages
- 99.0KB
- Prism.jsall 297 languages
- 162.1KB
- Starry Nightmajor 6 web languages
- 185.3KB
- Shikimajor 6 web languages
- 213.9KB
- Highlight.jsall 193 languages
- 240.4KB
- Shikiall 242 grammars
- 991.5KB
- Starry Nightall 710 grammars
- 1.46MB
Minified + Brotli · runtime + languages · Highlights measured October 21, 2026
Minified browser bundles compressed with Brotli, including the runtime and selected languages, excluding themes. KB means 1,024 bytes. Highlights 0.2.0 was installed from npm and measured October 21, 2026; competitor figures come from the gpu-lexer size comparison, recorded September 9. The size data records coverage, build settings, and artifact hashes.
The cost of that control
Writing WAT also makes the project responsible for details a higher-level language would normally help manage: buffer bounds, scratch space, state layout, and the behavior of every lexer on incomplete input.
Runtime differences still matter. The build includes JavaScriptCore workarounds around SIMD calling conventions and certain integer expressions. These are covered by tests, but they are a reminder that working closer to WebAssembly does not remove the surrounding engine from the picture.
The design fits a program built around compact state and repeated scans over bytes. As the implementation grows, keeping those boundaries understandable is part of the maintenance cost.
Integration with @pierre/diffs
The reason we started this project was to make highlighting cheaper inside Diffs. A fast lexer helps, but the useful test is what happens when it sits behind a file renderer, an editor, or a worker pool.
The integration PR adds
Highlights as an optional backend for File, FileDiff,
Editor, FileStream, server rendering, and workers. Shiki's
JavaScript engine remains the default. To select Highlights, set
preferredHighlighter:
import { FileDiff } from '@pierre/diffs';
const diff = new FileDiff({
theme: { dark: 'pierre-dark', light: 'pierre-light' },
diffStyle: 'split',
preferredHighlighter: 'highlights',
});
Each backend loads on demand. If a component uses a worker pool, the pool chooses the
backend, so set preferredHighlighter in its
highlighterOptions too. Built-in theme names work across backends; custom
Highlights themes use Zed's format. Custom TextMate grammars still belong to Shiki, and
Highlights renders unsupported languages as plain text.
Underneath, a shared highlighter interface handles tokens, themes, streaming, and live edits. The backends feed the same renderer for line markup and diff decorations. That also means Diffs' server-rendered HTML goes through JavaScript tokens and the shared renderer; it does not use the standalone Wasm-to-HTML path shown earlier.
What changes in practice
The PR compares main using Shiki WASM with the integration branch using
Highlights. Diffs defaults to Shiki JS, which was not measured in this comparison, so
these gains apply to the WASM baseline. On a 529 KB TypeScript file, the time to render
the first 100 rows with the virtualizer drops from 925.5 ms to 23.9 ms. The time to render
all 10,825 lines drops from 1,270.3 ms to 320.7 ms. The smaller gain for the full file
makes sense: making highlighting cheaper still leaves thousands of lines of DOM for the
browser to handle.
- Shiki WASM
- 925.5ms
- Highlights
- 23.9ms
- Shiki WASM
- 989.9ms
- Highlights
- 70.0ms
- Shiki WASM
- 1,270.3ms
- Highlights
- 320.7ms
- Shiki WASM
- 2,679.2ms
- Highlights
- 724.2ms
- Shiki WASM
- 2,291.5ms
- Highlights
- 382.9ms
- Shiki WASM
- 978.0ms
- Highlights
- 15.4ms
- Shiki WASM
- 2,012.6ms
- Highlights
- 45.6ms
- Shiki WASM
- 452.3ms
- Highlights
- 17.9ms
- Shiki WASM
- 7,811.8ms
- Highlights
- 181.5ms
- Shiki WASM
- 2,114.4ms
- Highlights
- 97.2ms
529 KB TypeScript · 10,825 lines · each pair has its own linear scale
Reported medians from PR #1141, using an Apple M4 Pro, Bun 1.4.0 for SSR and tokenizer streaming, and Chrome 151 for browser rendering. The workload is a 529 KB TypeScript file with 10,825 lines, one dark theme, and fully expanded split diffs. Virtualization and worker counts vary as labeled. These results compare the two branches, including the integration changes. The benchmark data preserves the reported times and speedups; each bar pair has its own linear scale.
The gains carry through to the other paths: full-file SSR drops from 978.0 ms to 15.4 ms, and tokenizer streaming in 4 KiB chunks drops from 452.3 ms to 17.9 ms. Workers still help distribute the work. Highlights makes the work each worker receives cheaper.
Highlights is still experimental, and its lexer output can differ from Shiki's. You can try the integration in the playground.
Fin
Highlights makes the processing behind syntax highlighting small enough to use in places where code keeps arriving and changing. Its lexers scan bytes directly, its emitters build compact output, and its streaming and live APIs preserve work that can be reused.
There are trade-offs. Handwritten lexers require ongoing language work. TextMate grammars have a much broader ecosystem, and applications that need syntax trees benefit from having that structure available. Faster highlighting also leaves the browser's layout, painting, and DOM costs to deal with.
For applications that need highlighted HTML or tokens, Highlights offers a small engine
with explicit control over how much work happens and when. You can install it with
pnpm add @pierre/highlights,
read the docs, or explore the
implementation.