feat(markdown): render LaTeX math with KaTeX (#4138)

Markdown views (file preview, agent chat, notebook Markdown cells, LSP/GitHub/plugin Markdown) now typeset $...$, $$...$$, \(...\), \[...\] and ```math blocks with KaTeX. The marked extension emits [data-math] placeholders that survive DOMPurify and are typeset after sanitizing (trust: false); inline $ follows Pandoc's rules, so currency like $5 and $10 stays text. The Markdown preview keeps the placeholders in its rendered HTML and typesets them after each render, like Mermaid diagrams, so its per-block sanitize cache is unaffected.

New dependency: katex 0.19.1 (MIT).

Co-authored-by: zzxzz12345 <8338183+zzxzz12345@users.noreply.github.com>
This commit is contained in:
胡翀
2026-11-18 18:36:43 +08:00
committed by GitHub
co-authored by zzxzz12345
parent 79accd1311
commit 4e5dbc8e0c
16 changed files with 433 additions and 12 deletions
+11
View File
@@ -369,6 +369,17 @@ describe("streamed replies", () => {
expect(container.querySelector("details p")?.textContent).toBe("text");
});
it("renders LaTeX math across streamed blocks", () => {
const text = "Inline $a + b$.\n\n$$\n\\frac{1}{2}\n$$\n\nTail";
const blocks = markdownBlocks(text);
expect(blocks).toHaveLength(3);
expect(blocks.join("")).toBe(text);
const { container } = render(<Markdown text={text} cwd="/repo" />);
expect(container.querySelectorAll(".katex")).toHaveLength(2);
expect(container.querySelector(".katex-display")).not.toBeNull();
expect(screen.queryByRole("button", { name: "Copy Code" })).toBeNull();
});
it("cuts only what streamed on after the blocks that ended", () => {
const before = markdownBlocks("One.\n\nTwo.\n\nThr");
const after = markdownBlocks("One.\n\nTwo.\n\nThree.\n\n- a", before);
+5 -3
View File
@@ -11,6 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { highlightInto } from "@/editor/lsp/markdown";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { iconNode } from "@/ui/iconNode";
import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
@@ -37,7 +38,7 @@ const marked = new Marked({
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
},
},
});
}).use(mathExtension());
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
const rendered = new Map<string, string>();
@@ -133,10 +134,11 @@ function renderHtml(text: string): string {
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
ALLOW_DATA_ATTR: false,
// Only the mermaid placeholder written by the renderer above; data attributes
// Only the mermaid and math placeholders written by the renderer above; data attributes
// quoted in a reply stay out.
ADD_ATTR: ["data-mermaid"],
ADD_ATTR: ["data-mermaid", "data-math"],
}) as HTMLElement;
renderMath(root);
root.querySelectorAll("li").forEach(wrapLooseText);
// WebKit cuts controls inside <pre> out of a text selection, even when transparent.
root.querySelectorAll("pre").forEach((pre) => {
+13
View File
@@ -104,6 +104,19 @@ describe("notebook Markdown preview", () => {
rerender(<MarkdownCell source="plain" attachments={{}} path="/p/a.ipynb" />);
expect(container.querySelector("p")).toBe(paragraph);
});
it("renders LaTeX math in Markdown cells while blocking unsafe styles", () => {
const { container } = render(
<MarkdownCell
source={'Inline $x^2$ and <div style="position:fixed">hi</div>\n\n$$\n\\sum_{i=1}^n i\n$$'}
attachments={{}}
path="/p/a.ipynb"
/>,
);
expect(container.querySelectorAll(".katex")).toHaveLength(2);
expect(container.querySelector(".katex-display")).not.toBeNull();
expect(container.querySelector("div[style]")).toBeNull();
});
});
describe("notebook image outputs", () => {
+4 -2
View File
@@ -1,5 +1,6 @@
import DOMPurify from "dompurify";
import { Marked } from "marked";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { mimeText, object, own } from "./outputs";
export const OUTPUT_CSP =
@@ -194,7 +195,7 @@ function htmlRoot(html: string, markdown = false): HTMLElement {
"rowspan",
"scope",
"align",
...(markdown ? ["href"] : ["style"]),
...(markdown ? ["href", "data-math"] : ["style"]),
],
// Attachment references are resolved by us after sanitization. No arbitrary
// URI survives the explicit src allowlist below.
@@ -221,13 +222,14 @@ export function staticOutputDocument(html: string): string {
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:#222;background:white;overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid #ddd;text-align:left}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
}
const markdown = new Marked({ gfm: true });
const markdown = new Marked({ gfm: true }).use(mathExtension());
/**
* Sanitized Markdown with inert links; link clicks are handled by the editor and
* `attachment:` images are left for `resolveMarkdownAttachments`.
*/
export function markdownRoot(source: string): HTMLElement {
const root = htmlRoot(markdown.parse(source, { async: false }) as string, true);
renderMath(root);
for (const link of root.querySelectorAll("a[href]")) {
const href = link.getAttribute("href")!;
link.removeAttribute("href");
@@ -41,6 +41,7 @@ import {
import { publishPreviewSelection, publishPreviewTop, stepMarkdownPreviewFontZoom, useLiveMarkdown } from "./live";
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
import { renderMath } from "@/editor/lsp/markdownMath";
import { modeOf, useMarkdownModes } from "./modes";
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
import {
@@ -184,8 +185,11 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
});
}, [html]);
// Math before the preview index: typesetting changes the blocks' heights.
useLayoutEffect(() => {
if (ref.current) invalidatePreviewIndex(ref.current);
if (!ref.current) return;
renderMath(ref.current);
invalidatePreviewIndex(ref.current);
}, [html]);
// Mermaid diagrams: before paint, so cached ones don't flash their source.
@@ -97,6 +97,7 @@ function collectRuns(root: Node): TextRun[] {
const el = node as Element;
const tag = el.tagName.toUpperCase();
if (SKIP_TAGS.has(tag)) return;
if (el.classList.contains("katex-mathml")) return;
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok") return;
const isBlock = BLOCK_TAGS.has(tag);
if (isBlock) flush();
@@ -1,6 +1,7 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderMath } from "@/editor/lsp/markdownMath";
import {
createMarkdownRenderer,
frontMatter,
@@ -280,6 +281,17 @@ describe("markdown preview rendering", () => {
expect(previewLineAtOffset(blocks, 5000)).toBe(20);
expect(previewLineAtOffset([], 50)).toBe(0);
});
it("renders LaTeX math blocks with source lines and inline math", () => {
const root = document.createElement("div");
root.innerHTML = renderMarkdown("# Heading\n\n$$\nx^2 + y^2 = z^2\n$$\n\nInline $a_1 + b_2$.\n");
expect(root.querySelectorAll("[data-math]")).toHaveLength(2);
renderMath(root);
const lines = [...root.querySelectorAll<HTMLElement>(":scope > [data-line]")].map((e) => e.dataset.line);
expect(lines).toEqual(["0", "2", "6"]);
expect(root.querySelector(".katex-display")).not.toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(2);
});
});
describe("markdown preview re-rendering", () => {
@@ -300,6 +312,8 @@ describe("markdown preview re-rendering", () => {
"| a | b |\n|---|---|\n| 1 | <b>2</b> |",
'<span is="x-span">custom</span> and <body class="x"> and </body> text',
"> quote\n> more",
"$$\nx^2 + y^2 = z^2\n$$",
"Inline $a_1 + b_2$ math.",
"Last paragraph.",
];
const doc = (parts: readonly string[]) => parts.join("\n\n") + "\n";
+5 -3
View File
@@ -3,11 +3,13 @@
* blocks inside one HTML container) is wrapped in an element carrying its
* 0-based source line (`data-line`) for scroll sync; images keep their source in `data-src` and are loaded by the preview
* (local files through the backend, as the CSP blocks file URLs). Mermaid
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`. YAML front matter is shown
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`; math becomes `[data-math]`
* placeholders, typeset by the preview (`renderMath`). YAML front matter is shown
* as a table of its top-level fields.
*/
import { Marked, type Token, type TokensList } from "marked";
import DOMPurify from "dompurify";
import { mathExtension } from "@/editor/lsp/markdownMath";
import { opensOtherShare } from "@/platform/paths";
const escapeHtml = (s: string) =>
@@ -22,7 +24,7 @@ const marked = new Marked({
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
},
},
});
}).use(mathExtension());
// Own instance: hooks must not leak into the hover / documentation renderer.
let purifier: ReturnType<typeof DOMPurify> | null = null;
@@ -180,7 +182,7 @@ function blocks(text: string): { line: number; html: string }[] {
const SANITIZE = {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-src", "data-line", "data-front-matter"],
ADD_ATTR: ["data-src", "data-line", "data-front-matter", "data-math"],
// The preview shares the IDE's document: a `<style>` in a file would restyle the whole IDE.
// `srcset` and `<source>` would pick an image past the one the preview loads.
FORBID_TAGS: ["style", "form", "source"],