From 4e5dbc8e0c3e8a9aa2a2ceef0826b883debc0335 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=83=A1=E7=BF=80?= <1020327414@qq.com> Date: Wed, 18 Nov 2026 18:36:43 +0800 Subject: [PATCH] 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> --- e2e/agentMarkdown.spec.ts | 34 +++ package.json | 1 + pnpm-lock.yaml | 11 + src/editor/lsp/markdown.test.ts | 8 + src/editor/lsp/markdownMath.css | 13 ++ src/editor/lsp/markdownMath.test.ts | 85 +++++++ src/editor/lsp/markdownMath.ts | 215 ++++++++++++++++++ src/editor/lsp/markdownParser.ts | 11 +- src/features/agents/Markdown.test.tsx | 11 + src/features/agents/Markdown.tsx | 8 +- src/features/notebook/OutputView.test.tsx | 13 ++ src/features/notebook/security.ts | 6 +- .../viewers/markdown/MarkdownEditor.tsx | 6 +- src/features/viewers/markdown/highlight.ts | 1 + src/features/viewers/markdown/render.test.ts | 14 ++ src/features/viewers/markdown/render.ts | 8 +- 16 files changed, 433 insertions(+), 12 deletions(-) create mode 100644 src/editor/lsp/markdownMath.css create mode 100644 src/editor/lsp/markdownMath.test.ts create mode 100644 src/editor/lsp/markdownMath.ts diff --git a/e2e/agentMarkdown.spec.ts b/e2e/agentMarkdown.spec.ts index 0be35ec52..af73f069f 100644 --- a/e2e/agentMarkdown.spec.ts +++ b/e2e/agentMarkdown.spec.ts @@ -1024,3 +1024,37 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1); expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5); }); + +test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => { + const reply = await openReply( + page, + [ + "Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.", + "", + "$$", + "\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}", + "$$", + "", + "```math", + "\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}", + "```", + ].join("\n"), + ); + await expect(reply.locator(".katex")).toHaveCount(4); + await expect(reply.locator(".katex-display")).toHaveCount(2); + await expect(reply).toContainText("prices $5 and $10 stay plain."); + + const layout = await reply.evaluate((el) => { + const firstKatex = el.querySelector(".katex")!; + const display = el.querySelectorAll(".katex-display"); + const font = getComputedStyle(firstKatex).fontFamily; + return { + font, + height: firstKatex.getBoundingClientRect().height, + overflowX: getComputedStyle(display[1]!).overflowX, + }; + }); + expect(layout.font).toContain("KaTeX_Main"); + expect(layout.height).toBeGreaterThan(10); + expect(layout.overflowX).toBe("auto"); +}); diff --git a/package.json b/package.json index 006e1b75d..daa0596a7 100644 --- a/package.json +++ b/package.json @@ -80,6 +80,7 @@ "dompurify": "^3.4.17", "emmet": "2.4.11", "immer": "^11.1.21", + "katex": "^0.19.1", "marked": "^18.1.1", "mermaid": "12.1.0", "react": "^19.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d6a0ff4ef..aed4a02a9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -119,6 +119,9 @@ importers: immer: specifier: ^11.1.21 version: 11.1.21 + katex: + specifier: ^0.19.1 + version: 0.19.1 marked: specifier: ^18.1.1 version: 18.1.1 @@ -1799,6 +1802,10 @@ packages: resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==} hasBin: true + katex@0.19.1: + resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==} + hasBin: true + khroma@2.1.0: resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==} @@ -3792,6 +3799,10 @@ snapshots: dependencies: commander: 15.1.0 + katex@0.19.1: + dependencies: + commander: 15.1.0 + khroma@2.1.0: {} knip@6.43.0: diff --git a/src/editor/lsp/markdown.test.ts b/src/editor/lsp/markdown.test.ts index a5931d1e0..d1babbbe1 100644 --- a/src/editor/lsp/markdown.test.ts +++ b/src/editor/lsp/markdown.test.ts @@ -69,6 +69,14 @@ describe("markdown rendering", () => { expect(md.markupToHtml({ kind: "markdown", value: "`x`" })).toBe("

x

\n"); expect(md.markupToHtml({ kind: "plaintext", value: "" })).toBe('

<b>

'); }); + + it("renders LaTeX math in LSP / documentation markdown", async () => { + const md = await freshMarkdown(); + await md.loadMarkdown(); + const root = document.createElement("div"); + root.innerHTML = md.markupToHtml({ kind: "markdown", value: "Complexity $O(n \\log n)$" }); + expect(root.querySelector(".katex")).not.toBeNull(); + }); }); // On Windows, opening `//server/share` signs in to that server with the user's credentials. diff --git a/src/editor/lsp/markdownMath.css b/src/editor/lsp/markdownMath.css new file mode 100644 index 000000000..ba6fd5206 --- /dev/null +++ b/src/editor/lsp/markdownMath.css @@ -0,0 +1,13 @@ +.katex { + overflow-wrap: normal; +} + +.katex-display { + overflow-x: auto; + overflow-y: hidden; + padding: 2px 0; +} + +.katex-error { + color: var(--danger) !important; +} diff --git a/src/editor/lsp/markdownMath.test.ts b/src/editor/lsp/markdownMath.test.ts new file mode 100644 index 000000000..17b26d731 --- /dev/null +++ b/src/editor/lsp/markdownMath.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from "vitest"; +import { Marked } from "marked"; +import DOMPurify from "dompurify"; +import { mathExtension, renderMath } from "./markdownMath"; + +const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension()); + +function parseSafe(md: string): HTMLElement { + const html = marked.parse(md, { async: false }) as string; + const root = DOMPurify.sanitize(html, { + USE_PROFILES: { html: true }, + ADD_ATTR: ["data-math"], + FORBID_TAGS: ["style", "form"], + FORBID_ATTR: ["style"], + RETURN_DOM: true, + }) as HTMLElement; + renderMath(root); + return root; +} + +describe("markdown LaTeX math", () => { + it("renders inline $...$ and avoids currency false positives", () => { + const root = parseSafe( + "Energy $E = mc^2$ and CJK 设$x=1$时.\n\nPrices: $5 and $10, or $5-$10, or $ 5 $, or \\$x\\$.", + ); + expect(root.querySelectorAll(".katex")).toHaveLength(2); + expect(root.querySelectorAll(".katex-display")).toHaveLength(0); + const paras = [...root.querySelectorAll("p")]; + expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$."); + }); + + it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => { + const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**."); + expect(root.querySelector("em")).toBeNull(); + expect(root.querySelectorAll(".katex")).toHaveLength(4); + expect(root.querySelector("strong .katex")).not.toBeNull(); + }); + + it("renders multi-line, single-line, inline, and adjacent $$...$$ blocks", () => { + const root = parseSafe( + "Para\n$$\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n$$\n\n$$E = mc^2$$\n\n$$a$$ and $$b$$", + ); + expect(root.querySelectorAll(".katex-display")).toHaveLength(4); + expect(root.querySelector("p")?.textContent).toBe("Para"); + const lastP = [...root.querySelectorAll("p")].at(-1)!; + expect(lastP.querySelectorAll(".katex-display")).toHaveLength(2); + expect(lastP.textContent).toContain("and"); + }); + + it("renders \\(...\\) and \\[...\\] without breaking escaped links", () => { + const root = parseSafe("Inline \\(x + y\\).\n\n\\[\nx^2 + y^2 = z^2\n\\]\n\n\\[text\\](https://example.com)"); + expect(root.querySelectorAll(".katex")).toHaveLength(2); + expect(root.querySelectorAll(".katex-display")).toHaveLength(1); + const lastP = [...root.querySelectorAll("p")].at(-1)!; + expect(lastP.textContent).toBe("[text](https://example.com)"); + }); + + it("renders ```math code blocks while keeping ```latex and inline code literal", () => { + const root = parseSafe("```math\n\\int_0^1 x^2 dx\n```\n\n```latex\n$x$\n```\n\nInline `$y$`."); + expect(root.querySelectorAll(".katex-display")).toHaveLength(1); + expect(root.querySelector("pre > code.language-latex")?.textContent).toBe("$x$\n"); + expect(root.querySelector("p > code")?.textContent).toBe("$y$"); + }); + + it("renders invalid LaTeX as an error node instead of throwing", () => { + const root = parseSafe("Bad $\\unknowncommand{x}$ and $$\\frac{1$$"); + expect(root.querySelectorAll(".katex")).toHaveLength(1); + expect(root.querySelector(".katex-error")).not.toBeNull(); + expect(root.textContent).toContain("\\unknowncommand"); + }); + + it("blocks unsafe LaTeX trust commands and raw HTML style/script injection", () => { + const root = parseSafe( + [ + "$\\href{javascript:alert(1)}{click}$", + '
x
', + 'a', + ].join("\n\n"), + ); + expect(root.querySelector("a")).toBeNull(); + expect(root.querySelector("img")).toBeNull(); + expect(root.querySelector("div[style]")).toBeNull(); + expect(root.querySelectorAll(".katex")).toHaveLength(2); + }); +}); diff --git a/src/editor/lsp/markdownMath.ts b/src/editor/lsp/markdownMath.ts new file mode 100644 index 000000000..a66f68933 --- /dev/null +++ b/src/editor/lsp/markdownMath.ts @@ -0,0 +1,215 @@ +/** + * LaTeX math support for Markdown (`marked` + `DOMPurify` + KaTeX). + * + * `mathExtension()` tokenizes `$$...$$`, `$...$`, `\[...\]`, `\(...\)`, and + * ```` ```math ```` blocks into sanitized-safe `` + * placeholders, which survive `DOMPurify` (with `data-math` allowed) and are + * rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization. + */ +import katex from "katex"; +import "katex/dist/katex.min.css"; +import "./markdownMath.css"; +import type { MarkedExtension, Tokens } from "marked"; + +interface MathToken extends Tokens.Generic { + type: "blockMath" | "inlineMath"; + raw: string; + text: string; + display: boolean; +} + +const escapeHtml = (s: string) => + s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + +export function mathPlaceholder(tex: string, display: boolean, block = display): string { + const tag = block ? "div" : "span"; + const mode = display ? "display" : "inline"; + return `<${tag} data-math="${mode}">${escapeHtml(tex)}`; +} + +/** Finds the closing `delim` (`$$`, `\)`, or `\]`) skipping `\` escapes. Returns content end index or -1. */ +function findClosingDelimiter(src: string, from: number, delim: string): number { + for (let i = from; i < src.length; i++) { + if (src.startsWith(delim, i)) return i; + if (src[i] === "\\") { + i++; + continue; + } + } + return -1; +} + +/** + * Matches inline `$...$` from index 0 using Pandoc-style guards so currency + * like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match. + */ +function matchInlineDollar(src: string): { end: number; text: string } | null { + if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null; + for (let i = 1; i < src.length; i++) { + const ch = src[i]!; + if (ch === "\\") { + i++; + continue; + } + if (ch === "\n" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) { + return null; + } + if (ch === "$") { + if (i <= 1 || /\s/.test(src[i - 1]!)) continue; + const next = src[i + 1] ?? ""; + if (next === "$" || /\d/.test(next)) return null; + const text = src.slice(1, i); + if (!text.trim()) return null; + return { end: i + 1, text }; + } + } + return null; +} + +/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */ +function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null { + if (src.startsWith("$$")) { + const close = findClosingDelimiter(src, 2, "$$"); + if (close > 2) { + const text = src.slice(2, close); + if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true }; + } + return null; + } + if (src[0] === "$") { + const m = matchInlineDollar(src); + return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null; + } + if (src.startsWith("\\(")) { + const close = findClosingDelimiter(src, 2, "\\)"); + if (close > 2) { + const text = src.slice(2, close); + if (text.trim()) return { raw: src.slice(0, close + 2), text, display: false }; + } + return null; + } + if (src.startsWith("\\[")) { + const close = findClosingDelimiter(src, 2, "\\]"); + if (close > 2 && src[close + 2] !== "(") { + const text = src.slice(2, close); + if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true }; + } + return null; + } + return null; +} + +const BLOCK_DOLLAR_MULTI = /^ {0,3}\$\$[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\$\$[ \t]*(?:\r?\n+|$)/; +const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t]*(?:\r?\n+|$)/; +const BLOCK_BRACKET_MULTI = /^ {0,3}\\\[[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\\\][ \t]*(?:\r?\n+|$)/; +const BLOCK_BRACKET_SINGLE = /^ {0,3}\\\[((?:\\[\s\S]|[^\\\n]|\\(?!\]))+?)\\\][ \t]*(?:\r?\n+|$)/; + +function matchBlockMath(src: string): { raw: string; text: string } | null { + for (const re of [BLOCK_DOLLAR_MULTI, BLOCK_DOLLAR_SINGLE, BLOCK_BRACKET_MULTI, BLOCK_BRACKET_SINGLE]) { + const m = re.exec(src); + if (m && m[1]!.trim()) return { raw: m[0], text: m[1]! }; + } + return null; +} + +/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */ +function maskInlineMath(src: string): string { + let out = ""; + let i = 0; + while (i < src.length) { + if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") { + out += src.slice(i, i + 2); + i += 2; + continue; + } + if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) { + const m = matchInlineMath(src.slice(i)); + if (m) { + out += m.raw.replace(/[^\r\n]/g, "a"); + i += m.raw.length; + continue; + } + } + out += src[i]!; + i++; + } + return out; +} + +export function mathExtension(): MarkedExtension { + return { + hooks: { + emStrongMask(src) { + return maskInlineMath(src); + }, + }, + renderer: { + code({ text, lang }) { + if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "math") return false; + return `${mathPlaceholder(text, true, true)}\n`; + }, + }, + extensions: [ + { + name: "blockMath", + level: "block", + start(src) { + const m = /\n {0,3}(?:\$\$|\\\[)/.exec(src); + return m ? m.index : undefined; + }, + tokenizer(src): MathToken | undefined { + const m = matchBlockMath(src); + if (!m) return undefined; + return { type: "blockMath", raw: m.raw, text: m.text, display: true }; + }, + renderer(token) { + const t = token as MathToken; + return `${mathPlaceholder(t.text, true, true)}\n`; + }, + }, + { + name: "inlineMath", + level: "inline", + start(src) { + for (let i = 0; i < src.length; i++) { + const ch = src[i]!; + if (ch === "\\") { + const next = src[i + 1]; + if (next === "(" || next === "[") return i; + i++; + continue; + } + if (ch === "$") return i; + } + return undefined; + }, + tokenizer(src): MathToken | undefined { + const m = matchInlineMath(src); + if (!m) return undefined; + return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display }; + }, + renderer(token) { + const t = token as MathToken; + return mathPlaceholder(t.text, t.display, false); + }, + }, + ], + }; +} + +/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */ +export function renderMath(root: ParentNode): void { + root.querySelectorAll("[data-math]").forEach((el) => { + const mode = el.getAttribute("data-math"); + el.removeAttribute("data-math"); + if (mode !== "inline" && mode !== "display") return; + const tex = (el.textContent ?? "").trim(); + if (!tex) return; + katex.render(tex, el, { + displayMode: mode === "display", + throwOnError: false, + strict: false, + trust: false, + }); + }); +} diff --git a/src/editor/lsp/markdownParser.ts b/src/editor/lsp/markdownParser.ts index e4473eda6..5502dcc6b 100644 --- a/src/editor/lsp/markdownParser.ts +++ b/src/editor/lsp/markdownParser.ts @@ -1,19 +1,24 @@ /** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */ import { Marked } from "marked"; import DOMPurify from "dompurify"; +import { mathExtension, renderMath } from "./markdownMath"; /** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */ const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i; -const marked = new Marked({ gfm: true, breaks: false }); +const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension()); export function markdownToSafeHtml(markdown: string): string { const html = marked.parse(markdown, { async: false }) as string; // Comments and docs come from anyone; a `${root.innerHTML}`; } -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"); diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index 5b0c527e1..904e72c2e 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -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. diff --git a/src/features/viewers/markdown/highlight.ts b/src/features/viewers/markdown/highlight.ts index 3575408d2..c5d0e2ae9 100644 --- a/src/features/viewers/markdown/highlight.ts +++ b/src/features/viewers/markdown/highlight.ts @@ -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(); diff --git a/src/features/viewers/markdown/render.test.ts b/src/features/viewers/markdown/render.test.ts index c918f1f72..20cc5efc0 100644 --- a/src/features/viewers/markdown/render.test.ts +++ b/src/features/viewers/markdown/render.test.ts @@ -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(":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 | 2 |", 'custom and and 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"; diff --git a/src/features/viewers/markdown/render.ts b/src/features/viewers/markdown/render.ts index 0211cdc6e..8e3afbbc6 100644 --- a/src/features/viewers/markdown/render.ts +++ b/src/features/viewers/markdown/render.ts @@ -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 `
${escapeHtml(text)}
\n`; }, }, -}); +}).use(mathExtension()); // Own instance: hooks must not leak into the hover / documentation renderer. let purifier: ReturnType | 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 `