From d9fa94634ea30c2a5c31fb6275276538299e3f5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Wed, 18 Nov 2026 14:51:04 +0000 Subject: [PATCH 1/5] feat(plugins): add `pierre-highlights` plugin Highlights code blocks and language-tagged inline code with @pierre/highlights, a WebAssembly highlighter, producing the same tree as the Shiki plugin. Amp-Thread-ID: https://ampcode.com/threads/T-01a1eec1-229a-708d-a8d0-86c64cba050b --- AGENTS.md | 2 + benchmarks/plugins.bench.ts | 8 +- docs/app/components/Playground.vue | 22 +- .../4.plugins/1.built-in/pierre-highlights.md | 168 ++++++++++++++ docs/content/4.plugins/index.md | 4 + packages/comark/package.json | 5 + .../comark/src/plugins/pierre-highlights.ts | 217 ++++++++++++++++++ .../test/plugins/pierre-highlights.test.ts | 135 +++++++++++ pnpm-lock.yaml | 11 + pnpm-workspace.yaml | 1 + test/bundle.test.ts | 16 +- 11 files changed, 578 insertions(+), 11 deletions(-) create mode 100644 docs/content/4.plugins/1.built-in/pierre-highlights.md create mode 100644 packages/comark/src/plugins/pierre-highlights.ts create mode 100644 packages/comark/test/plugins/pierre-highlights.test.ts diff --git a/AGENTS.md b/AGENTS.md index ab00dd9c..41ee8901 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,6 +75,7 @@ packages/comark/ │ │ ├── linkify.ts # Autolinks via linkify-it 6 (default via registerDefaultPlugins; fuzzyLink opt-in) │ │ ├── math.ts # LaTeX math via KaTeX (optional peer: katex) │ │ ├── mermaid.ts # Mermaid diagrams (optional peer: beautiful-mermaid) +│ │ ├── pierre-highlights.ts # Fast Wasm syntax highlighting with Shiki-compatible output (optional peer: @pierre/highlights) │ │ ├── punctuation.ts # Smart quotes, dashes, and ellipses │ │ ├── rangi.ts # Lightweight syntax highlighting (optional peer: rangi) │ │ ├── rangi/language-comark.ts # Standalone Comark grammar for rangi @@ -187,6 +188,7 @@ import shikiCore from 'comark/plugins/shiki/core' import shikiComarkLanguages from 'comark/plugins/shiki/language-comark' import rangi, { comarkLanguage, comarkLanguages } from 'comark/plugins/rangi' import rangiComarkLanguage from 'comark/plugins/rangi/language-comark' +import pierreHighlights from 'comark/plugins/pierre-highlights' // `comark` fences use the plain mdc lexer import math from 'comark/plugins/math' import mermaid from 'comark/plugins/mermaid' import emoji from 'comark/plugins/emoji' diff --git a/benchmarks/plugins.bench.ts b/benchmarks/plugins.bench.ts index 27938f58..8c2b9cb0 100644 --- a/benchmarks/plugins.bench.ts +++ b/benchmarks/plugins.bench.ts @@ -2,6 +2,7 @@ import { bench, describe } from 'vitest' import { createMarkdownParser } from 'comark' import emoji from 'comark/plugins/emoji' import footnotes from 'comark/plugins/footnotes' +import pierreHighlights from 'comark/plugins/pierre-highlights' import titleDescription from 'comark/plugins/title-description' import punctuation from 'comark/plugins/punctuation' import rangi from 'comark/plugins/rangi' @@ -28,6 +29,7 @@ const withAll = createMarkdownParser({ const codeBaseline = createMarkdownParser() const withShiki = createMarkdownParser({ plugins: [shiki()] }) const withRangi = createMarkdownParser({ plugins: [rangi()] }) +const withPierreHighlights = createMarkdownParser({ plugins: [pierreHighlights()] }) // Warm every parser. For Shiki this also loads the shared highlighter, its // themes and grammars, so the benchmark measures highlighting, not setup. @@ -44,7 +46,7 @@ for (const parse of [ ]) { await parse(pluginMarkdown) } -for (const parse of [codeBaseline, withShiki, withRangi]) { +for (const parse of [codeBaseline, withShiki, withRangi, withPierreHighlights]) { await parse(codeMarkdown) } @@ -99,4 +101,8 @@ describe('highlight', () => { bench('rangi', async () => { await withRangi(codeMarkdown) }) + + bench('pierre-highlights', async () => { + await withPierreHighlights(codeMarkdown) + }) }) diff --git a/docs/app/components/Playground.vue b/docs/app/components/Playground.vue index 2dcd95c5..b1fc6145 100644 --- a/docs/app/components/Playground.vue +++ b/docs/app/components/Playground.vue @@ -76,6 +76,7 @@ const pluginToggles = useLocalStorage( { shiki: true, rangi: false, + pierreHighlights: false, math: true, emoji: true, mermaid: true, @@ -122,6 +123,19 @@ const pluginDefs = [ icon: 'i-lucide-gauge', factory: () => rangi(), }, + { + key: 'pierreHighlights', + label: 'Pierre Syntax Highlighting', + icon: 'i-lucide-cpu', + // Loaded on first use: the module inlines and compiles a ~300 KB wasm lexer. + factory: (): ComarkPlugin => ({ + name: 'pierre-highlights', + async post(state) { + const { pierreHighlightsCodeBlocks } = await import('@comark/vue/plugins/pierre-highlights') + state.tree = pierreHighlightsCodeBlocks(state.tree) + }, + }), + }, { key: 'mermaid', label: 'Mermaid Diagrams', @@ -192,9 +206,13 @@ const pluginDefs = [ type PluginKey = (typeof pluginDefs)[number]['key'] +const highlighters = ['shiki', 'rangi', 'pierreHighlights'] as const + function setPluginEnabled(key: PluginKey, enabled: boolean): void { - if (enabled && key === 'shiki') pluginToggles.value.rangi = false - if (enabled && key === 'rangi') pluginToggles.value.shiki = false + // Only one syntax highlighter runs at a time. + if (enabled && (highlighters as readonly string[]).includes(key)) { + for (const other of highlighters) if (other !== key) pluginToggles.value[other] = false + } pluginToggles.value[key] = enabled } diff --git a/docs/content/4.plugins/1.built-in/pierre-highlights.md b/docs/content/4.plugins/1.built-in/pierre-highlights.md new file mode 100644 index 00000000..3a2c257d --- /dev/null +++ b/docs/content/4.plugins/1.built-in/pierre-highlights.md @@ -0,0 +1,168 @@ +--- +title: Pierre (Highlight) +description: Fast syntax highlighting for code blocks and language-tagged inline code using @pierre/highlights. +seo: + title: Syntax Highlighting using Pierre Highlights +navigation: + icon: i-lucide-cpu +links: + - label: Shiki + icon: i-lucide-code + to: /plugins/built-in/shiki + color: neutral + variant: soft + - label: Rangi + icon: i-lucide-zap + to: /plugins/built-in/rangi + color: neutral + variant: soft + - label: '@pierre/highlights' + icon: i-simple-icons-github + to: https://github.com/pierrecomputer/pierre/tree/main/packages/highlights + color: neutral + variant: soft +--- + +The `comark/plugins/pierre-highlights` plugin highlights code blocks with [`@pierre/highlights`](https://diffs.com/highlights), a synchronous highlighter written in WebAssembly. It ships 152 language lexers in one wasm module and renders the same tree as the [Shiki plugin](/plugins/built-in/shiki): `` lines, inline colors, and `--shiki-dark` variables, so existing Shiki styles keep working. + +`@pierre/highlights` is a peer dependency: + +```bash [terminal] +npm install @pierre/highlights +``` + +::warning +`@pierre/highlights` is in beta. Its colors follow Shiki's themes but its lexers are coarser than TextMate grammars, so some tokens get a different color than with Shiki. +:: + +::tip +Pick Highlights for server rendering and streaming, where its speed and quick startup matter most. Use [Shiki](/plugins/built-in/shiki) for transformers, custom grammars, or Comark syntax colors in `comark` fences, and [Rangi](/plugins/built-in/rangi) for the smallest browser bundle. +:: + +## Usage + +```typescript +import { parseMarkdown } from 'comark' +import pierreHighlights from 'comark/plugins/pierre-highlights' + +const result = await parseMarkdown(content, { + plugins: [pierreHighlights()] +}) +``` + +With framework components: + +::code-group + +```vue [Vue] + + + +``` + +```tsx [React] +import { Markdown } from '@comark/react' +import pierreHighlights from '@comark/react/plugins/pierre-highlights' + + + {content} + +``` + +```svelte [Svelte] + + + +``` + +:: + +--- + +## Performance + +Highlighting time added to a parse, measured with Node 26 on the same documents. The first row is the [`codeMarkdown`](https://github.com/comarkdown/comark/blob/main/benchmarks/fixtures.ts) fixture used by `benchmarks/plugins.bench.ts`. + +| Document | Shiki | Rangi | Highlights | +|---|---|---|---| +| 4 short fences | 4.0 ms | 0.30 ms | 0.11 ms | +| One 564-line TypeScript file | 288 ms | 9.3 ms | 2.0 ms | +| 16,000 lines of TypeScript (530 KiB) | 7.2 s | 267 ms | 83 ms | + +Startup is close to Rangi's (about 20 ms to the first highlighted parse, against 700 ms for Shiki). The trade-off is size: the wasm module is inlined in the JavaScript, adding about 185 KiB gzipped to a browser bundle, against about 14 KiB for Rangi. + +--- + +## Features + +### Themes + +Pass themes from `@pierre/highlights/themes`. It includes Shiki's community themes, converted to the [Zed](https://zed.dev) theme format, plus Pierre's own. The defaults are Material Theme Lighter and Material Theme Palenight, the same as the Shiki plugin: + +```typescript +import githubLight from '@pierre/highlights/themes/github-light' +import githubDark from '@pierre/highlights/themes/github-dark' + +// light/dark pair: light colors inline, dark colors as --shiki-dark variables +pierreHighlights({ themes: { light: githubLight, dark: githubDark } }) + +// a single theme +pierreHighlights({ themes: { dark: githubDark } }) +``` + +Import each theme from its own path. The `@pierre/highlights/themes` entry bundles every theme. + +### Languages + +Fence languages and their aliases are passed to Highlights (`ts`, `typescript`, `sh`, `yml`, …). `comark` fences use its `mdc` lexer, which is Markdown without Comark's component syntax, and `json-render` and `yaml-render` fences use JSON and YAML. A fence with an unknown language keeps its text unhighlighted under the `shiki pierre-highlights` class. Custom grammars are not supported. + +### Inline code + +Inline code is highlighted when it declares a language with the attributes syntax. `lang` wins over `language`: + +```markdown +The type is `Ref`{lang="ts-type"} and the component is ``{lang="vue-html"}. +``` + +`ts-type` is highlighted as a TypeScript type and `vue-html` as Vue template markup. Inline code naming a language Highlights does not know is left as written, so `` `Bonjour`{lang="fr"} `` stays plain text. Set `inlineCode: false` to turn this off. + +### Line highlighting + +Fence info `{2-3,5}` marks the selected lines with the `.highlight` class, the same as the Shiki plugin. + +--- + +## Options + +| Option | Type | Default | Description | +|---|---|---|---| +| `themes` | `{ light?: Theme, dark?: Theme }` | Material Lighter / Palenight | Themes from `@pierre/highlights/themes` | +| `preStyles` | `boolean` | `false` | Add the theme's background and foreground colors to `
` |
+| `inlineCode` | `boolean` | `true` | Highlight inline code that declares a language |
+
+---
+
+## Styling
+
+Code blocks and inline code get the `shiki pierre-highlights` class, so the dark-mode CSS from the [Shiki plugin](/plugins/built-in/shiki) applies unchanged:
+
+```css
+html.dark .shiki span {
+  color: var(--shiki-dark) !important;
+  background-color: var(--shiki-dark-bg) !important;
+  font-style: var(--shiki-dark-font-style) !important;
+  font-weight: var(--shiki-dark-font-weight) !important;
+  text-decoration: var(--shiki-dark-text-decoration) !important;
+}
+```
diff --git a/docs/content/4.plugins/index.md b/docs/content/4.plugins/index.md
index 936ab70f..e2ae4800 100644
--- a/docs/content/4.plugins/index.md
+++ b/docs/content/4.plugins/index.md
@@ -139,6 +139,10 @@ Register optional plugins through the `plugins` option.
   Highlight code with Rangi (~13 kB with all languages, dual themes)
   ::
 
+  ::card{icon="i-lucide-cpu" title="Pierre" to="/plugins/built-in/pierre-highlights"}
+  Highlight code with @pierre/highlights in WebAssembly (152 languages, Shiki-compatible output)
+  ::
+
   ::card{icon="i-lucide-list" title="Table of contents" to="/plugins/built-in/toc"}
   Build a nested table of contents from document headings
   ::
diff --git a/packages/comark/package.json b/packages/comark/package.json
index 93663ac0..f79c7a9e 100644
--- a/packages/comark/package.json
+++ b/packages/comark/package.json
@@ -77,6 +77,7 @@
   },
   "devDependencies": {
     "@json-render/core": "catalog:",
+    "@pierre/highlights": "catalog:",
     "@shikijs/twoslash": "catalog:",
     "@types/markdown-it": "catalog:",
     "github-slugger": "catalog:",
@@ -89,12 +90,16 @@
     "vitest": "catalog:"
   },
   "peerDependencies": {
+    "@pierre/highlights": "catalog:",
     "beautiful-mermaid": "catalog:",
     "katex": "catalog:",
     "rangi": "catalog:",
     "shiki": "catalog:"
   },
   "peerDependenciesMeta": {
+    "@pierre/highlights": {
+      "optional": true
+    },
     "shiki": {
       "optional": true
     },
diff --git a/packages/comark/src/plugins/pierre-highlights.ts b/packages/comark/src/plugins/pierre-highlights.ts
new file mode 100644
index 00000000..ba93243b
--- /dev/null
+++ b/packages/comark/src/plugins/pierre-highlights.ts
@@ -0,0 +1,217 @@
+import type { ElementNode, ElementNodeAttributes, MarkdownDocument, Node } from 'comark'
+import type { Theme, ThemedToken, TokensResult } from '@pierre/highlights'
+import { codeToTokens, isSupportedLanguage } from '@pierre/highlights'
+import defaultLight from '@pierre/highlights/themes/material-theme-lighter'
+import defaultDark from '@pierre/highlights/themes/material-theme-palenight'
+import { defineComarkPlugin } from 'comark'
+import { visit } from 'comark/utils'
+import { GRAMMAR_CONTEXTS, inlineCodeLanguage } from '../internal/inline-code-lang.ts'
+
+export type { Theme as PierreHighlightsTheme } from '@pierre/highlights'
+
+export interface PierreHighlightsOptions {
+  /**
+   * Themes from `@pierre/highlights/themes`. With two different themes, the
+   * light one is inlined as `color` and the dark one is emitted as
+   * `--shiki-dark*` variables, the same as the Shiki plugin.
+   *
+   * Defaults to Material Theme Lighter and Material Theme Palenight, the Shiki
+   * plugin's defaults.
+   */
+  themes?: {
+    light?: Theme
+    dark?: Theme
+  }
+
+  /**
+   * Whether to add the theme's background and foreground colors to `
`.
+   * @default false
+   */
+  preStyles?: boolean
+
+  /**
+   * Whether to highlight inline code that declares a language, e.g.
+   * `` `Ref`{lang="ts-type"} ``. `lang` wins over `language`. `preStyles`
+   * does not apply to inline code.
+   *
+   * @default true
+   */
+  inlineCode?: boolean
+}
+
+export interface CodeBlockAttributes {
+  language?: string
+  class?: string
+  highlights?: number[]
+  meta?: string
+}
+
+const CLASS = 'shiki pierre-highlights'
+
+/** Fence names Highlights does not know itself, mapped like the Shiki plugin maps them. */
+const LANGUAGE_ALIASES: Record = {
+  comark: 'mdc',
+  'json-render': 'json',
+  'yaml-render': 'yaml',
+}
+
+/**
+ * Map a fence or inline language to a Highlights language, or `undefined`
+ * when Highlights has no lexer for it. A missing language is plain text.
+ */
+export function resolvePierreHighlightsLanguage(language: string | undefined): string | undefined {
+  const raw = language?.trim().toLowerCase()
+  if (!raw) return 'text'
+  const lang = LANGUAGE_ALIASES[raw] ?? raw
+  return isSupportedLanguage(lang) ? lang : undefined
+}
+
+function tokenStyle(token: ThemedToken): string {
+  let style = ''
+  const styles = token.htmlStyle!
+  for (const key in styles) style += `${style ? ';' : ''}${key}:${styles[key]}`
+  return style
+}
+
+function tokensToSpans(line: ThemedToken[]): Node[] {
+  const spans: Node[] = []
+  for (const token of line) {
+    const style = tokenStyle(token)
+    spans.push(style ? ['span', { style }, token.content] : ['span', {}, token.content])
+  }
+  return spans
+}
+
+/** Drop the first `length` characters of a line, splitting the token they end in. */
+function dropPrefix(line: ThemedToken[], length: number): ThemedToken[] {
+  const out: ThemedToken[] = []
+  let remain = length
+  for (const token of line) {
+    if (remain >= token.content.length) {
+      remain -= token.content.length
+      continue
+    }
+    out.push(remain > 0 ? { ...token, content: token.content.slice(remain) } : token)
+    remain = 0
+  }
+  return out
+}
+
+function withUserClass(highlighterClass: string, userClass: unknown): string {
+  const user = typeof userClass === 'string' ? userClass.trim() : ''
+  return user ? `${highlighterClass} . ${user}` : highlighterClass
+}
+
+/**
+ * Apply `@pierre/highlights` syntax highlighting to every `
` block
+ * and, when enabled, to inline `` that declares a language.
+ */
+export function pierreHighlightsCodeBlocks(
+  tree: MarkdownDocument,
+  options: PierreHighlightsOptions = {}
+): MarkdownDocument {
+  const light = options.themes?.light ?? options.themes?.dark ?? defaultLight
+  const dark = options.themes?.dark ?? options.themes?.light ?? defaultDark
+  const themes: Record = light === dark ? { light } : { light, dark }
+  const inlineEnabled = options.inlineCode !== false
+
+  const tokenize = (code: string, lang: string): TokensResult =>
+    codeToTokens(code, { lang: lang as any, themes, cssVariablePrefix: '--shiki-' })
+
+  visit(
+    tree,
+    (node) => {
+      if (!Array.isArray(node) || node[0] === null) return false
+      if (node[0] === 'pre') {
+        const code = node[2]
+        return Array.isArray(code) && code[0] === 'code' && code.length === 3 && typeof code[2] === 'string'
+      }
+      // A raw-HTML `` is authored markup, not Comark inline
+      // code, and replacing it with spans would break its round-trip.
+      return (
+        inlineEnabled &&
+        node[0] === 'code' &&
+        node.length === 3 &&
+        typeof node[2] === 'string' &&
+        (node[1] as ElementNodeAttributes)?.$?.html !== 1 &&
+        !!inlineCodeLanguage(node[1] as ElementNodeAttributes)
+      )
+    },
+    (node) => {
+      const el = node as ElementNode
+      return el[0] === 'pre' ? highlightBlock(el) : highlightInline(el)
+    }
+  )
+
+  function highlightBlock(pre: ElementNode): ElementNode {
+    const attrs = pre[1] as CodeBlockAttributes & Record
+    const codeEl = pre[2] as ElementNode
+    const code = codeEl[2] as string
+    const lang = resolvePierreHighlightsLanguage(attrs.language)
+    const preAttrs: Record = { ...attrs, class: withUserClass(CLASS, attrs.class) }
+
+    // A `
` is unambiguously code, so an unknown language still gets the
+    // highlighter class, with the code left as plain text.
+    if (!lang) return ['pre', preAttrs, ['code', codeEl[1], code]]
+
+    const result = tokenize(code, lang)
+    if (options.preStyles) preAttrs.style = `background-color:${result.bg};color:${result.fg}`
+
+    const highlights = Array.isArray(attrs.highlights) && attrs.highlights.length > 0 ? new Set(attrs.highlights) : null
+    const lines = result.tokens
+    // eslint-disable-next-line unicorn/no-new-array -- pre-allocated for perf
+    const codeNode = new Array(2) as ElementNode
+    codeNode[0] = 'code'
+    codeNode[1] = codeEl[1]
+    for (let i = 0; i < lines.length; i++) {
+      const highlighted = highlights !== null && highlights.has(i + 1)
+      // TODO: (enforcing default style) once we unify all ecosystem styles we can remove `style`
+      codeNode.push([
+        'span',
+        highlighted
+          ? { class: 'line highlight', style: 'display: inline-block' }
+          : { class: 'line', style: 'display: inline' },
+        ...tokensToSpans(lines[i]),
+      ] as ElementNode)
+      if (i < lines.length - 1) codeNode.push('\n')
+    }
+    return ['pre', preAttrs, codeNode]
+  }
+
+  function highlightInline(el: ElementNode): ElementNode | undefined {
+    const attrs = el[1] as ElementNodeAttributes
+    const code = el[2] as string
+    const written = inlineCodeLanguage(attrs) as string
+    // Fragment names are matched case-insensitively, same as fence languages.
+    const context = GRAMMAR_CONTEXTS.get(written.toLowerCase())
+    const lang = resolvePierreHighlightsLanguage(context?.lang ?? written)
+
+    // Unlike a `
`, an inline `` is not unambiguously code, since
+    // `lang` is a real HTML attribute for natural language. Leave
+    // `` `Bonjour`{lang="fr"} `` exactly as it was authored.
+    if (!lang) return undefined
+
+    // Highlights has no grammar-context option: tokenize the seed with the
+    // code, then drop the seed's characters from the first line.
+    const prefix = context?.grammarContextCode ?? ''
+    const lines = tokenize(prefix + code, lang).tokens
+    if (prefix && lines.length > 0) lines[0] = dropPrefix(lines[0], prefix.length)
+
+    const children: Node[] = []
+    for (let i = 0; i < lines.length; i++) {
+      if (i > 0) children.push('\n')
+      children.push(...tokensToSpans(lines[i]))
+    }
+    if (children.length === 0) children.push(code)
+    return ['code', { ...attrs, class: withUserClass(CLASS, attrs.class) }, ...children]
+  }
+
+  return tree
+}
+
+export default defineComarkPlugin((options: PierreHighlightsOptions = {}) => ({
+  name: 'pierre-highlights',
+  post(state) {
+    state.tree = pierreHighlightsCodeBlocks(state.tree, options)
+  },
+}))
diff --git a/packages/comark/test/plugins/pierre-highlights.test.ts b/packages/comark/test/plugins/pierre-highlights.test.ts
new file mode 100644
index 00000000..6b8f715c
--- /dev/null
+++ b/packages/comark/test/plugins/pierre-highlights.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest'
+import githubDark from '@pierre/highlights/themes/github-dark'
+import { parseMarkdown } from '../../src/index'
+import { renderMarkdown } from '../../src/render'
+import pierreHighlights, { resolvePierreHighlightsLanguage } from '../../src/plugins/pierre-highlights'
+import type { ElementNode, Node } from '../../src/types'
+
+function find(nodes: Node[], tag: string): ElementNode | undefined {
+  for (const node of nodes) {
+    if (!Array.isArray(node)) continue
+    if (node[0] === tag) return node as ElementNode
+    const nested = find(node.slice(2) as Node[], tag)
+    if (nested) return nested
+  }
+  return undefined
+}
+
+function textOf(node: Node): string {
+  if (typeof node === 'string') return node
+  if (node[0] === null) return ''
+  let out = ''
+  for (let i = 2; i < node.length; i++) out += textOf(node[i] as Node)
+  return out
+}
+
+function spans(node: ElementNode): ElementNode[] {
+  const out: ElementNode[] = []
+  for (const child of node.slice(2) as Node[]) {
+    if (!Array.isArray(child) || child[0] !== 'span') continue
+    if (typeof child[2] === 'string') out.push(child as ElementNode)
+    else out.push(...spans(child as ElementNode))
+  }
+  return out
+}
+
+describe('resolvePierreHighlightsLanguage', () => {
+  it('maps Comark fence names and treats a missing language as plain text', () => {
+    expect(resolvePierreHighlightsLanguage('comark')).toBe('mdc')
+    expect(resolvePierreHighlightsLanguage('json-render')).toBe('json')
+    expect(resolvePierreHighlightsLanguage(undefined)).toBe('text')
+    expect(resolvePierreHighlightsLanguage(' TypeScript ')).toBe('typescript')
+    expect(resolvePierreHighlightsLanguage('not-a-real-lang')).toBeUndefined()
+  })
+})
+
+describe('pierre-highlights plugin', () => {
+  it('highlights a fence with the default light colors and --shiki-dark variables', async () => {
+    const source = 'const answer = 42\nconsole.log(answer)'
+    const tree = await parseMarkdown(`\`\`\`ts\n${source}\n\`\`\``, { plugins: [pierreHighlights()] })
+    const pre = find(tree.nodes, 'pre')!
+
+    expect(pre[1].class).toBe('shiki pierre-highlights')
+    expect(textOf(pre)).toBe(source)
+    const code = pre[2] as ElementNode
+    expect(code.filter((child) => Array.isArray(child) && child[1].class === 'line')).toHaveLength(2)
+    // Material Theme Lighter / Palenight numbers, the Shiki plugin's default pair
+    const number = spans(code).find((span) => span[2] === '42')!
+    expect(number[1].style).toBe('color:#f76d47;--shiki-dark:#f78c6c')
+  })
+
+  it('emits no dark variables with a single theme', async () => {
+    const tree = await parseMarkdown('```js\nconst a = 1\n```', {
+      plugins: [pierreHighlights({ themes: { dark: githubDark } })],
+    })
+    const styles = spans(find(tree.nodes, 'pre')![2] as ElementNode).map((span) => span[1].style as string)
+    expect(styles.length).toBeGreaterThan(0)
+    expect(styles.every((style) => style.startsWith('color:') && !style.includes('--shiki-dark'))).toBe(true)
+  })
+
+  it('marks the lines selected in the fence info', async () => {
+    const tree = await parseMarkdown('```js {2}\na\nb\nc\n```', { plugins: [pierreHighlights()] })
+    const lines = (find(tree.nodes, 'pre')![2] as ElementNode).filter((child) => Array.isArray(child)) as ElementNode[]
+    expect(lines.map((line) => line[1].class)).toEqual(['line', 'line highlight', 'line'])
+  })
+
+  it('keeps an unknown language as plain text under the highlighter class', async () => {
+    const tree = await parseMarkdown('```nope\nx < y\n```', { plugins: [pierreHighlights()] })
+    expect(find(tree.nodes, 'pre')).toEqual([
+      'pre',
+      { language: 'nope', class: 'shiki pierre-highlights' },
+      ['code', { class: 'language-nope' }, 'x < y'],
+    ])
+  })
+
+  it('highlights code blocks nested inside components', async () => {
+    const tree = await parseMarkdown('::card\n```js\nconst a = 1\n```\n::', { plugins: [pierreHighlights()] })
+    expect(spans(find(tree.nodes, 'pre')![2] as ElementNode).length).toBeGreaterThan(1)
+  })
+
+  it('adds the theme colors to 
 with preStyles', async () => {
+    const tree = await parseMarkdown('```js\na\n```', { plugins: [pierreHighlights({ preStyles: true })] })
+    expect(find(tree.nodes, 'pre')![1].style).toBe(
+      'background-color:#fafafa;--shiki-dark-bg:#292d3e;color:#90a4ae;--shiki-dark:#babed8'
+    )
+  })
+
+  it('round-trips to the original markdown, keeping only the user class', async () => {
+    const source = '```js {2}\nconst a = 1\nb\n```\n\nThe `Ref`{lang="ts-type" .tight} type.'
+    const tree = await parseMarkdown(source, { plugins: [pierreHighlights()] })
+    expect(find(find(tree.nodes, 'p')!.slice(2) as Node[], 'code')![1].class).toBe('shiki pierre-highlights . tight')
+    expect(await renderMarkdown(tree)).toBe(source)
+  })
+})
+
+describe('pierre-highlights inline code', () => {
+  it('highlights inline code that declares a language', async () => {
+    const tree = await parseMarkdown('Run `const a = 1`{lang="js"} now', { plugins: [pierreHighlights()] })
+    const code = find(tree.nodes, 'code')!
+    expect(code[1].class).toBe('shiki pierre-highlights')
+    expect(textOf(code)).toBe('const a = 1')
+    expect(spans(code).length).toBeGreaterThan(1)
+  })
+
+  it('tokenizes ts-type as a type and drops the seed text', async () => {
+    const tree = await parseMarkdown('`Ref`{lang="ts-type"}', { plugins: [pierreHighlights()] })
+    const code = find(tree.nodes, 'code')!
+    expect(textOf(code)).toBe('Ref')
+    // Seeded with `let a:`, `Ref` is a type, not a plain identifier.
+    expect(spans(code)[0]).toEqual(['span', { style: 'color:#e2931d;--shiki-dark:#ffcb6b' }, 'Ref'])
+  })
+
+  it('leaves natural languages, raw HTML code and disabled inline code alone', async () => {
+    const french = await parseMarkdown('`Bonjour`{lang="fr"}', { plugins: [pierreHighlights()] })
+    expect(find(french.nodes, 'code')).toEqual(['code', { lang: 'fr' }, 'Bonjour'])
+
+    const html = await parseMarkdown('const a = 1', { plugins: [pierreHighlights()] })
+    expect(find(html.nodes, 'code')!.slice(2)).toEqual(['const a = 1'])
+
+    const disabled = await parseMarkdown('`const a = 1`{lang="js"}\n\n```js\nconst a = 1\n```', {
+      plugins: [pierreHighlights({ inlineCode: false })],
+    })
+    expect(find(disabled.nodes, 'p')).toEqual(['p', {}, ['code', { lang: 'js' }, 'const a = 1']])
+    expect(find(disabled.nodes, 'pre')![1].class).toBe('shiki pierre-highlights')
+  })
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e541dc89..d84f3335 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -239,6 +239,9 @@ catalogs:
     '@nuxtlabs/monarch-mdc':
       specifier: ^0.10.0
       version: 0.10.0
+    '@pierre/highlights':
+      specifier: ^0.5.1
+      version: 0.5.1
     '@shikijs/langs':
       specifier: ^4.6.0
       version: 4.6.0
@@ -1473,6 +1476,9 @@ importers:
       '@json-render/core':
         specifier: 'catalog:'
         version: 0.22.0(zod@4.6.7)
+      '@pierre/highlights':
+        specifier: 'catalog:'
+        version: 0.5.1
       '@shikijs/twoslash':
         specifier: 'catalog:'
         version: 4.6.0(supports-color@10.2.2)(typescript@6.0.3)
@@ -5473,6 +5479,9 @@ packages:
     resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==}
     engines: {node: '>=20.0.0'}
 
+  '@pierre/highlights@0.5.1':
+    resolution: {integrity: sha512-c2WF6sgwgKdxXU6FpWDLWUYHRca/cJy+3QJkWAqYqEAFxqlPf8eSH0ehHcFFjKBmT+9KBl9H7q6z7HMRU7+m6g==}
+
   '@polka/url@1.0.0-next.29':
     resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
 
@@ -16474,6 +16483,8 @@ snapshots:
       tslib: 2.9.1
       tsyringe: 4.10.0
 
+  '@pierre/highlights@0.5.1': {}
+
   '@polka/url@1.0.0-next.29': {}
 
   '@poppinss/colors@4.1.6':
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index d7fd83f7..21d2bbec 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -126,6 +126,7 @@ catalog:
   scule: ^1.3.0
 
   # Shared peer dependencies
+  "@pierre/highlights": ^0.5.1
   rangi: ^2.2.0
   shiki: ^4.6.0
   splitpanes: ^4.1.2
diff --git a/test/bundle.test.ts b/test/bundle.test.ts
index aad454f5..8f1c9011 100644
--- a/test/bundle.test.ts
+++ b/test/bundle.test.ts
@@ -70,14 +70,14 @@ describe('package bundle size', { timeout: 60_000 }, () => {
 
     expect(report).toMatchInlineSnapshot(`
       {
-        "@comark/angular": "69.7k (61 files)",
-        "@comark/ansi": "41.9k (107 files)",
-        "@comark/html": "17.5k (67 files)",
-        "@comark/nuxt": "10.8k (67 files)",
-        "@comark/react": "43.1k (85 files)",
-        "@comark/svelte": "50.8k (93 files)",
-        "@comark/vue": "62.5k (91 files)",
-        "comark": "440k (173 files)",
+        "@comark/angular": "70.1k (63 files)",
+        "@comark/ansi": "42.1k (109 files)",
+        "@comark/html": "17.7k (69 files)",
+        "@comark/nuxt": "11.0k (69 files)",
+        "@comark/react": "43.3k (87 files)",
+        "@comark/svelte": "51.0k (95 files)",
+        "@comark/vue": "62.7k (93 files)",
+        "comark": "449k (175 files)",
       }
     `)
   })

From 6bb050f21477af86005b9e9e4dc7a5f3811a6252 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= 
Date: Wed, 18 Nov 2026 15:15:20 +0000
Subject: [PATCH 2/5] fix(plugins): harden `pierre-highlights` against review
 findings

- Copy the path to replaced nodes instead of mutating the parsed tree, so
  the streaming cache stays raw and generated spans are not walked again.
- Treat a non-string language as missing and leave `ansi` fences as plain
  text so their escape sequences survive Markdown output.
- Append spans in loops instead of spreads to avoid argument limits on
  long lines, and only highlight a `pre` whose single child is the code.
- Document the dark `pre` rule for `preStyles` and that the dark CSS
  needs two themes.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1eec1-229a-708d-a8d0-86c64cba050b
---
 .../4.plugins/1.built-in/pierre-highlights.md |   8 +-
 .../comark/src/plugins/pierre-highlights.ts   | 104 +++++++++++-------
 .../test/plugins/pierre-highlights.test.ts    |  13 ++-
 3 files changed, 84 insertions(+), 41 deletions(-)

diff --git a/docs/content/4.plugins/1.built-in/pierre-highlights.md b/docs/content/4.plugins/1.built-in/pierre-highlights.md
index 3a2c257d..62646eb9 100644
--- a/docs/content/4.plugins/1.built-in/pierre-highlights.md
+++ b/docs/content/4.plugins/1.built-in/pierre-highlights.md
@@ -155,7 +155,7 @@ Fence info `{2-3,5}` marks the selected lines with the `.highlight` class, the s
 
 ## Styling
 
-Code blocks and inline code get the `shiki pierre-highlights` class, so the dark-mode CSS from the [Shiki plugin](/plugins/built-in/shiki) applies unchanged:
+Code blocks and inline code get the `shiki pierre-highlights` class, so the dark-mode CSS from the [Shiki plugin](/plugins/built-in/shiki) applies unchanged. It switches to the `--shiki-dark*` variables, which are only emitted with a light and a dark theme; with a single theme the inline colors need no extra CSS:
 
 ```css
 html.dark .shiki span {
@@ -165,4 +165,10 @@ html.dark .shiki span {
   font-weight: var(--shiki-dark-font-weight) !important;
   text-decoration: var(--shiki-dark-text-decoration) !important;
 }
+
+/* With preStyles: true */
+html.dark pre.shiki {
+  background-color: var(--shiki-dark-bg) !important;
+  color: var(--shiki-dark) !important;
+}
 ```
diff --git a/packages/comark/src/plugins/pierre-highlights.ts b/packages/comark/src/plugins/pierre-highlights.ts
index ba93243b..f82238d6 100644
--- a/packages/comark/src/plugins/pierre-highlights.ts
+++ b/packages/comark/src/plugins/pierre-highlights.ts
@@ -4,7 +4,6 @@ import { codeToTokens, isSupportedLanguage } from '@pierre/highlights'
 import defaultLight from '@pierre/highlights/themes/material-theme-lighter'
 import defaultDark from '@pierre/highlights/themes/material-theme-palenight'
 import { defineComarkPlugin } from 'comark'
-import { visit } from 'comark/utils'
 import { GRAMMAR_CONTEXTS, inlineCodeLanguage } from '../internal/inline-code-lang.ts'
 
 export type { Theme as PierreHighlightsTheme } from '@pierre/highlights'
@@ -59,11 +58,14 @@ const LANGUAGE_ALIASES: Record = {
  * Map a fence or inline language to a Highlights language, or `undefined`
  * when Highlights has no lexer for it. A missing language is plain text.
  */
-export function resolvePierreHighlightsLanguage(language: string | undefined): string | undefined {
-  const raw = language?.trim().toLowerCase()
+export function resolvePierreHighlightsLanguage(language: unknown): string | undefined {
+  // Attributes from a `::pre{language=…}` wrapper can be any JSON value.
+  const raw = typeof language === 'string' ? language.trim().toLowerCase() : ''
   if (!raw) return 'text'
   const lang = LANGUAGE_ALIASES[raw] ?? raw
-  return isSupportedLanguage(lang) ? lang : undefined
+  // `ansi` tokens drop the escape sequences, which would then be lost when
+  // the document is written back to Markdown.
+  return lang !== 'ansi' && isSupportedLanguage(lang) ? lang : undefined
 }
 
 function tokenStyle(token: ThemedToken): string {
@@ -73,13 +75,12 @@ function tokenStyle(token: ThemedToken): string {
   return style
 }
 
-function tokensToSpans(line: ThemedToken[]): Node[] {
-  const spans: Node[] = []
+/** Append one span per token. A loop, not a spread: a long line can exceed the argument limit. */
+function appendSpans(target: ElementNode, line: ThemedToken[]): void {
   for (const token of line) {
     const style = tokenStyle(token)
-    spans.push(style ? ['span', { style }, token.content] : ['span', {}, token.content])
+    target.push(style ? ['span', { style }, token.content] : ['span', {}, token.content])
   }
-  return spans
 }
 
 /** Drop the first `length` characters of a line, splitting the token they end in. */
@@ -118,30 +119,46 @@ export function pierreHighlightsCodeBlocks(
   const tokenize = (code: string, lang: string): TokensResult =>
     codeToTokens(code, { lang: lang as any, themes, cssVariablePrefix: '--shiki-' })
 
-  visit(
-    tree,
-    (node) => {
-      if (!Array.isArray(node) || node[0] === null) return false
-      if (node[0] === 'pre') {
-        const code = node[2]
-        return Array.isArray(code) && code[0] === 'code' && code.length === 3 && typeof code[2] === 'string'
+  const isBlock = (node: ElementNode): boolean => {
+    const code = node[2]
+    return (
+      node[0] === 'pre' &&
+      node.length === 3 &&
+      Array.isArray(code) &&
+      code[0] === 'code' &&
+      code.length === 3 &&
+      typeof code[2] === 'string'
+    )
+  }
+
+  // A raw-HTML `` is authored markup, not Comark inline
+  // code, and replacing it with spans would break its round-trip.
+  const isInline = (node: ElementNode): boolean =>
+    inlineEnabled &&
+    node[0] === 'code' &&
+    node.length === 3 &&
+    typeof node[2] === 'string' &&
+    node[1]?.$?.html !== 1 &&
+    !!inlineCodeLanguage(node[1])
+
+  // Copy only the path to each replaced node: the streaming parser caches and
+  // reuses the input nodes, so they must stay unhighlighted.
+  const walk = (node: Node): Node => {
+    if (!Array.isArray(node) || node[0] === null) return node
+    const el = node as ElementNode
+    if (isBlock(el)) return highlightBlock(el)
+    if (isInline(el)) return highlightInline(el) ?? el
+    let copy: ElementNode | undefined
+    for (let i = 2; i < el.length; i++) {
+      const child = el[i] as Node
+      const next = walk(child)
+      if (next !== child) {
+        copy ??= el.slice() as ElementNode
+        copy[i] = next
       }
-      // A raw-HTML `` is authored markup, not Comark inline
-      // code, and replacing it with spans would break its round-trip.
-      return (
-        inlineEnabled &&
-        node[0] === 'code' &&
-        node.length === 3 &&
-        typeof node[2] === 'string' &&
-        (node[1] as ElementNodeAttributes)?.$?.html !== 1 &&
-        !!inlineCodeLanguage(node[1] as ElementNodeAttributes)
-      )
-    },
-    (node) => {
-      const el = node as ElementNode
-      return el[0] === 'pre' ? highlightBlock(el) : highlightInline(el)
     }
-  )
+    return copy ?? el
+  }
 
   function highlightBlock(pre: ElementNode): ElementNode {
     const attrs = pre[1] as CodeBlockAttributes & Record
@@ -166,13 +183,14 @@ export function pierreHighlightsCodeBlocks(
     for (let i = 0; i < lines.length; i++) {
       const highlighted = highlights !== null && highlights.has(i + 1)
       // TODO: (enforcing default style) once we unify all ecosystem styles we can remove `style`
-      codeNode.push([
+      const line: ElementNode = [
         'span',
         highlighted
           ? { class: 'line highlight', style: 'display: inline-block' }
           : { class: 'line', style: 'display: inline' },
-        ...tokensToSpans(lines[i]),
-      ] as ElementNode)
+      ]
+      appendSpans(line, lines[i])
+      codeNode.push(line)
       if (i < lines.length - 1) codeNode.push('\n')
     }
     return ['pre', preAttrs, codeNode]
@@ -197,16 +215,24 @@ export function pierreHighlightsCodeBlocks(
     const lines = tokenize(prefix + code, lang).tokens
     if (prefix && lines.length > 0) lines[0] = dropPrefix(lines[0], prefix.length)
 
-    const children: Node[] = []
+    const inlineNode: ElementNode = ['code', { ...attrs, class: withUserClass(CLASS, attrs.class) }]
     for (let i = 0; i < lines.length; i++) {
-      if (i > 0) children.push('\n')
-      children.push(...tokensToSpans(lines[i]))
+      if (i > 0) inlineNode.push('\n')
+      appendSpans(inlineNode, lines[i])
     }
-    if (children.length === 0) children.push(code)
-    return ['code', { ...attrs, class: withUserClass(CLASS, attrs.class) }, ...children]
+    if (inlineNode.length === 2) inlineNode.push(code)
+    return inlineNode
   }
 
-  return tree
+  let nodes: Node[] | undefined
+  for (let i = 0; i < tree.nodes.length; i++) {
+    const next = walk(tree.nodes[i])
+    if (next !== tree.nodes[i]) {
+      nodes ??= tree.nodes.slice()
+      nodes[i] = next
+    }
+  }
+  return nodes ? { ...tree, nodes } : tree
 }
 
 export default defineComarkPlugin((options: PierreHighlightsOptions = {}) => ({
diff --git a/packages/comark/test/plugins/pierre-highlights.test.ts b/packages/comark/test/plugins/pierre-highlights.test.ts
index 6b8f715c..41e9c8d0 100644
--- a/packages/comark/test/plugins/pierre-highlights.test.ts
+++ b/packages/comark/test/plugins/pierre-highlights.test.ts
@@ -1,6 +1,6 @@
 import { describe, expect, it } from 'vitest'
 import githubDark from '@pierre/highlights/themes/github-dark'
-import { parseMarkdown } from '../../src/index'
+import { createMarkdownParser, parseMarkdown } from '../../src/index'
 import { renderMarkdown } from '../../src/render'
 import pierreHighlights, { resolvePierreHighlightsLanguage } from '../../src/plugins/pierre-highlights'
 import type { ElementNode, Node } from '../../src/types'
@@ -40,6 +40,10 @@ describe('resolvePierreHighlightsLanguage', () => {
     expect(resolvePierreHighlightsLanguage(undefined)).toBe('text')
     expect(resolvePierreHighlightsLanguage(' TypeScript ')).toBe('typescript')
     expect(resolvePierreHighlightsLanguage('not-a-real-lang')).toBeUndefined()
+    // Its tokens drop escape sequences, which Markdown output must keep.
+    expect(resolvePierreHighlightsLanguage('ansi')).toBeUndefined()
+    // A `::pre{language=…}` wrapper can set any JSON value.
+    expect(resolvePierreHighlightsLanguage([1])).toBe('text')
   })
 })
 
@@ -94,6 +98,13 @@ describe('pierre-highlights plugin', () => {
     )
   })
 
+  it('leaves the streaming parser cache unhighlighted between updates', async () => {
+    const parse = createMarkdownParser({ plugins: [pierreHighlights()] })
+    let tree
+    for (const tail of ['a', 'ab', 'abc']) tree = await parse(`\`\`\`nope\nx\n\`\`\`\n\n${tail}`, { streaming: true })
+    expect(find(tree!.nodes, 'pre')![1].class).toBe('shiki pierre-highlights')
+  })
+
   it('round-trips to the original markdown, keeping only the user class', async () => {
     const source = '```js {2}\nconst a = 1\nb\n```\n\nThe `Ref`{lang="ts-type" .tight} type.'
     const tree = await parseMarkdown(source, { plugins: [pierreHighlights()] })

From 067d6bccee4483c97e48a6484fd6334ca2bc3522 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= 
Date: Wed, 18 Nov 2026 15:27:14 +0000
Subject: [PATCH 3/5] perf(plugins): reuse `pierre-highlights` output for
 unchanged streaming nodes

Cache highlighted nodes by their raw node, which the streaming parser reuses
while its source is unchanged, and cap the tree walk at TREE_WALK_MAX_DEPTH
so hand-built deep trees cannot overflow the stack.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1eec1-229a-708d-a8d0-86c64cba050b
---
 .../comark/src/plugins/pierre-highlights.ts   | 59 +++++++++++++------
 .../test/plugins/pierre-highlights.test.ts    | 23 +++++++-
 2 files changed, 64 insertions(+), 18 deletions(-)

diff --git a/packages/comark/src/plugins/pierre-highlights.ts b/packages/comark/src/plugins/pierre-highlights.ts
index f82238d6..96256f34 100644
--- a/packages/comark/src/plugins/pierre-highlights.ts
+++ b/packages/comark/src/plugins/pierre-highlights.ts
@@ -4,6 +4,7 @@ import { codeToTokens, isSupportedLanguage } from '@pierre/highlights'
 import defaultLight from '@pierre/highlights/themes/material-theme-lighter'
 import defaultDark from '@pierre/highlights/themes/material-theme-palenight'
 import { defineComarkPlugin } from 'comark'
+import { TREE_WALK_MAX_DEPTH } from 'comark/utils'
 import { GRAMMAR_CONTEXTS, inlineCodeLanguage } from '../internal/inline-code-lang.ts'
 
 export type { Theme as PierreHighlightsTheme } from '@pierre/highlights'
@@ -111,6 +112,15 @@ export function pierreHighlightsCodeBlocks(
   tree: MarkdownDocument,
   options: PierreHighlightsOptions = {}
 ): MarkdownDocument {
+  return createHighlighter(options)(tree)
+}
+
+/**
+ * The streaming parser hands the same raw node to every update while its
+ * source is unchanged, so each highlighted node is cached by its raw node.
+ */
+function createHighlighter(options: PierreHighlightsOptions): (tree: MarkdownDocument) => MarkdownDocument {
+  const cache = new WeakMap()
   const light = options.themes?.light ?? options.themes?.dark ?? defaultLight
   const dark = options.themes?.dark ?? options.themes?.light ?? defaultDark
   const themes: Record = light === dark ? { light } : { light, dark }
@@ -143,15 +153,25 @@ export function pierreHighlightsCodeBlocks(
 
   // Copy only the path to each replaced node: the streaming parser caches and
   // reuses the input nodes, so they must stay unhighlighted.
-  const walk = (node: Node): Node => {
+  const highlight = (el: ElementNode): ElementNode => {
+    let out = cache.get(el)
+    if (!out) {
+      out = isBlock(el) ? highlightBlock(el) : (highlightInline(el) ?? el)
+      cache.set(el, out)
+    }
+    return out
+  }
+
+  // Deeper subtrees are left unhighlighted rather than overflowing the stack.
+  const walk = (node: Node, depth: number): Node => {
     if (!Array.isArray(node) || node[0] === null) return node
     const el = node as ElementNode
-    if (isBlock(el)) return highlightBlock(el)
-    if (isInline(el)) return highlightInline(el) ?? el
+    if (isBlock(el) || isInline(el)) return highlight(el)
+    if (depth >= TREE_WALK_MAX_DEPTH) return el
     let copy: ElementNode | undefined
     for (let i = 2; i < el.length; i++) {
       const child = el[i] as Node
-      const next = walk(child)
+      const next = walk(child, depth + 1)
       if (next !== child) {
         copy ??= el.slice() as ElementNode
         copy[i] = next
@@ -224,20 +244,25 @@ export function pierreHighlightsCodeBlocks(
     return inlineNode
   }
 
-  let nodes: Node[] | undefined
-  for (let i = 0; i < tree.nodes.length; i++) {
-    const next = walk(tree.nodes[i])
-    if (next !== tree.nodes[i]) {
-      nodes ??= tree.nodes.slice()
-      nodes[i] = next
+  return (tree) => {
+    let nodes: Node[] | undefined
+    for (let i = 0; i < tree.nodes.length; i++) {
+      const next = walk(tree.nodes[i], 0)
+      if (next !== tree.nodes[i]) {
+        nodes ??= tree.nodes.slice()
+        nodes[i] = next
+      }
     }
+    return nodes ? { ...tree, nodes } : tree
   }
-  return nodes ? { ...tree, nodes } : tree
 }
 
-export default defineComarkPlugin((options: PierreHighlightsOptions = {}) => ({
-  name: 'pierre-highlights',
-  post(state) {
-    state.tree = pierreHighlightsCodeBlocks(state.tree, options)
-  },
-}))
+export default defineComarkPlugin((options: PierreHighlightsOptions = {}) => {
+  const highlight = createHighlighter(options)
+  return {
+    name: 'pierre-highlights',
+    post(state) {
+      state.tree = highlight(state.tree)
+    },
+  }
+})
diff --git a/packages/comark/test/plugins/pierre-highlights.test.ts b/packages/comark/test/plugins/pierre-highlights.test.ts
index 41e9c8d0..c5e46ab5 100644
--- a/packages/comark/test/plugins/pierre-highlights.test.ts
+++ b/packages/comark/test/plugins/pierre-highlights.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest'
 import githubDark from '@pierre/highlights/themes/github-dark'
 import { createMarkdownParser, parseMarkdown } from '../../src/index'
 import { renderMarkdown } from '../../src/render'
-import pierreHighlights, { resolvePierreHighlightsLanguage } from '../../src/plugins/pierre-highlights'
+import pierreHighlights, {
+  pierreHighlightsCodeBlocks,
+  resolvePierreHighlightsLanguage,
+} from '../../src/plugins/pierre-highlights'
 import type { ElementNode, Node } from '../../src/types'
 
 function find(nodes: Node[], tag: string): ElementNode | undefined {
@@ -105,6 +108,24 @@ describe('pierre-highlights plugin', () => {
     expect(find(tree!.nodes, 'pre')![1].class).toBe('shiki pierre-highlights')
   })
 
+  it('highlights an unchanged fence once while later content streams', async () => {
+    const parse = createMarkdownParser({ plugins: [pierreHighlights()] })
+    const fences: Node[] = []
+    for (const tail of ['a', 'ab']) {
+      const tree = await parse(`\`\`\`ts\nconst a = 1\n\`\`\`\n\n${tail}`, { streaming: true })
+      fences.push(tree.nodes[0])
+    }
+    expect(spans((fences[0] as ElementNode)[2] as ElementNode).length).toBeGreaterThan(1)
+    expect(fences[1]).toBe(fences[0])
+  })
+
+  it('leaves code nested deeper than the walk limit untouched instead of overflowing', () => {
+    let node: Node = ['pre', { language: 'js' }, ['code', {}, 'const a = 1']]
+    for (let i = 0; i < 20_000; i++) node = ['div', {}, node]
+    const tree = { nodes: [node], frontmatter: {}, meta: {} }
+    expect(pierreHighlightsCodeBlocks(tree)).toBe(tree)
+  })
+
   it('round-trips to the original markdown, keeping only the user class', async () => {
     const source = '```js {2}\nconst a = 1\nb\n```\n\nThe `Ref`{lang="ts-type" .tight} type.'
     const tree = await parseMarkdown(source, { plugins: [pierreHighlights()] })

From c369ccd7caac9a988267d7c8eeeb76002df72c51 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= 
Date: Wed, 18 Nov 2026 15:39:04 +0000
Subject: [PATCH 4/5] fix(plugins): cache `pierre-highlights` tokens, not
 output nodes

Reuse tokens only when the raw node's code and language still match, and
rebuild output nodes on every pass so in-place edits by callers or later
plugins never leak into the next streaming update.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1eec1-229a-708d-a8d0-86c64cba050b
---
 .../comark/src/plugins/pierre-highlights.ts   | 36 +++++++++----------
 .../test/plugins/pierre-highlights.test.ts    | 27 +++++++++-----
 2 files changed, 35 insertions(+), 28 deletions(-)

diff --git a/packages/comark/src/plugins/pierre-highlights.ts b/packages/comark/src/plugins/pierre-highlights.ts
index 96256f34..d09a11a9 100644
--- a/packages/comark/src/plugins/pierre-highlights.ts
+++ b/packages/comark/src/plugins/pierre-highlights.ts
@@ -115,19 +115,24 @@ export function pierreHighlightsCodeBlocks(
   return createHighlighter(options)(tree)
 }
 
-/**
- * The streaming parser hands the same raw node to every update while its
- * source is unchanged, so each highlighted node is cached by its raw node.
- */
 function createHighlighter(options: PierreHighlightsOptions): (tree: MarkdownDocument) => MarkdownDocument {
-  const cache = new WeakMap()
+  // The streaming parser hands the same raw node to every update while its
+  // source is unchanged, so tokens are cached by raw node and reused only when
+  // its code and language still match. Output nodes are rebuilt every time:
+  // callers and later plugins may edit them in place.
+  const cache = new WeakMap()
   const light = options.themes?.light ?? options.themes?.dark ?? defaultLight
   const dark = options.themes?.dark ?? options.themes?.light ?? defaultDark
   const themes: Record = light === dark ? { light } : { light, dark }
   const inlineEnabled = options.inlineCode !== false
 
-  const tokenize = (code: string, lang: string): TokensResult =>
-    codeToTokens(code, { lang: lang as any, themes, cssVariablePrefix: '--shiki-' })
+  const tokenize = (el: ElementNode, source: string, lang: string): TokensResult => {
+    const cached = cache.get(el)
+    if (cached?.source === source && cached.lang === lang) return cached.result
+    const result = codeToTokens(source, { lang: lang as any, themes, cssVariablePrefix: '--shiki-' })
+    cache.set(el, { source, lang, result })
+    return result
+  }
 
   const isBlock = (node: ElementNode): boolean => {
     const code = node[2]
@@ -153,20 +158,12 @@ function createHighlighter(options: PierreHighlightsOptions): (tree: MarkdownDoc
 
   // Copy only the path to each replaced node: the streaming parser caches and
   // reuses the input nodes, so they must stay unhighlighted.
-  const highlight = (el: ElementNode): ElementNode => {
-    let out = cache.get(el)
-    if (!out) {
-      out = isBlock(el) ? highlightBlock(el) : (highlightInline(el) ?? el)
-      cache.set(el, out)
-    }
-    return out
-  }
-
   // Deeper subtrees are left unhighlighted rather than overflowing the stack.
   const walk = (node: Node, depth: number): Node => {
     if (!Array.isArray(node) || node[0] === null) return node
     const el = node as ElementNode
-    if (isBlock(el) || isInline(el)) return highlight(el)
+    if (isBlock(el)) return highlightBlock(el)
+    if (isInline(el)) return highlightInline(el) ?? el
     if (depth >= TREE_WALK_MAX_DEPTH) return el
     let copy: ElementNode | undefined
     for (let i = 2; i < el.length; i++) {
@@ -191,7 +188,7 @@ function createHighlighter(options: PierreHighlightsOptions): (tree: MarkdownDoc
     // highlighter class, with the code left as plain text.
     if (!lang) return ['pre', preAttrs, ['code', codeEl[1], code]]
 
-    const result = tokenize(code, lang)
+    const result = tokenize(pre, code, lang)
     if (options.preStyles) preAttrs.style = `background-color:${result.bg};color:${result.fg}`
 
     const highlights = Array.isArray(attrs.highlights) && attrs.highlights.length > 0 ? new Set(attrs.highlights) : null
@@ -232,7 +229,8 @@ function createHighlighter(options: PierreHighlightsOptions): (tree: MarkdownDoc
     // Highlights has no grammar-context option: tokenize the seed with the
     // code, then drop the seed's characters from the first line.
     const prefix = context?.grammarContextCode ?? ''
-    const lines = tokenize(prefix + code, lang).tokens
+    // Copied: the token arrays may be cached for the next update.
+    const lines = tokenize(el, prefix + code, lang).tokens.slice()
     if (prefix && lines.length > 0) lines[0] = dropPrefix(lines[0], prefix.length)
 
     const inlineNode: ElementNode = ['code', { ...attrs, class: withUserClass(CLASS, attrs.class) }]
diff --git a/packages/comark/test/plugins/pierre-highlights.test.ts b/packages/comark/test/plugins/pierre-highlights.test.ts
index c5e46ab5..e99d592e 100644
--- a/packages/comark/test/plugins/pierre-highlights.test.ts
+++ b/packages/comark/test/plugins/pierre-highlights.test.ts
@@ -1,4 +1,5 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
+import { codeToTokens } from '@pierre/highlights'
 import githubDark from '@pierre/highlights/themes/github-dark'
 import { createMarkdownParser, parseMarkdown } from '../../src/index'
 import { renderMarkdown } from '../../src/render'
@@ -8,6 +9,11 @@ import pierreHighlights, {
 } from '../../src/plugins/pierre-highlights'
 import type { ElementNode, Node } from '../../src/types'
 
+vi.mock('@pierre/highlights', async (importOriginal) => {
+  const actual = await importOriginal()
+  return { ...actual, codeToTokens: vi.fn(actual.codeToTokens) }
+})
+
 function find(nodes: Node[], tag: string): ElementNode | undefined {
   for (const node of nodes) {
     if (!Array.isArray(node)) continue
@@ -108,15 +114,18 @@ describe('pierre-highlights plugin', () => {
     expect(find(tree!.nodes, 'pre')![1].class).toBe('shiki pierre-highlights')
   })
 
-  it('highlights an unchanged fence once while later content streams', async () => {
+  it('tokenizes an unchanged fence once while later content streams, without sharing output nodes', async () => {
     const parse = createMarkdownParser({ plugins: [pierreHighlights()] })
-    const fences: Node[] = []
-    for (const tail of ['a', 'ab']) {
-      const tree = await parse(`\`\`\`ts\nconst a = 1\n\`\`\`\n\n${tail}`, { streaming: true })
-      fences.push(tree.nodes[0])
-    }
-    expect(spans((fences[0] as ElementNode)[2] as ElementNode).length).toBeGreaterThan(1)
-    expect(fences[1]).toBe(fences[0])
+    const source = (tail: string) => `\`\`\`ts\nconst a = 1\n\`\`\`\n\n${tail}`
+    const first = await parse(source('a'), { streaming: true })
+    const calls = vi.mocked(codeToTokens).mock.calls.length
+    // A later plugin or the caller editing the output must not leak into the next update.
+    ;(first.nodes[0] as ElementNode)[1].class = 'edited'
+    const second = await parse(source('ab'), { streaming: true })
+
+    expect(vi.mocked(codeToTokens).mock.calls.length).toBe(calls)
+    expect((second.nodes[0] as ElementNode)[1].class).toBe('shiki pierre-highlights')
+    expect(spans((second.nodes[0] as ElementNode)[2] as ElementNode).length).toBeGreaterThan(1)
   })
 
   it('leaves code nested deeper than the walk limit untouched instead of overflowing', () => {

From c3c26700da357ef1f9b5ccc217b2219634f01e78 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= 
Date: Wed, 18 Nov 2026 15:46:50 +0000
Subject: [PATCH 5/5] test(plugins): assert a single tokenizer call across
 streaming updates

Amp-Thread-ID: https://ampcode.com/threads/T-01a1eec1-229a-708d-a8d0-86c64cba050b
---
 packages/comark/test/plugins/pierre-highlights.test.ts | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/packages/comark/test/plugins/pierre-highlights.test.ts b/packages/comark/test/plugins/pierre-highlights.test.ts
index e99d592e..2e036020 100644
--- a/packages/comark/test/plugins/pierre-highlights.test.ts
+++ b/packages/comark/test/plugins/pierre-highlights.test.ts
@@ -117,13 +117,14 @@ describe('pierre-highlights plugin', () => {
   it('tokenizes an unchanged fence once while later content streams, without sharing output nodes', async () => {
     const parse = createMarkdownParser({ plugins: [pierreHighlights()] })
     const source = (tail: string) => `\`\`\`ts\nconst a = 1\n\`\`\`\n\n${tail}`
+    const before = vi.mocked(codeToTokens).mock.calls.length
     const first = await parse(source('a'), { streaming: true })
-    const calls = vi.mocked(codeToTokens).mock.calls.length
+    expect(vi.mocked(codeToTokens).mock.calls.length).toBe(before + 1)
     // A later plugin or the caller editing the output must not leak into the next update.
     ;(first.nodes[0] as ElementNode)[1].class = 'edited'
     const second = await parse(source('ab'), { streaming: true })
 
-    expect(vi.mocked(codeToTokens).mock.calls.length).toBe(calls)
+    expect(vi.mocked(codeToTokens).mock.calls.length).toBe(before + 1)
     expect((second.nodes[0] as ElementNode)[1].class).toBe('shiki pierre-highlights')
     expect(spans((second.nodes[0] as ElementNode)[2] as ElementNode).length).toBeGreaterThan(1)
   })