diff --git a/src/editor/lsp/markdownMath.test.ts b/src/editor/lsp/markdownMath.test.ts index 3e42997ec8..871deffa12 100644 --- a/src/editor/lsp/markdownMath.test.ts +++ b/src/editor/lsp/markdownMath.test.ts @@ -5,9 +5,11 @@ import { mathExtension } from "./markdownMath"; import { renderMath } from "./renderMarkdownMath"; const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension()); +/** As LSP hovers parse: see `markdownParser.ts`. */ +const hoverMarked = new Marked({ gfm: true, breaks: false }).use(mathExtension({ strictBrackets: true })); -function parseSafe(md: string): HTMLElement { - const html = marked.parse(md, { async: false }) as string; +function parseSafe(md: string, parser = marked): HTMLElement { + const html = parser.parse(md, { async: false }) as string; const root = DOMPurify.sanitize(html, { USE_PROFILES: { html: true }, ADD_ATTR: ["data-math"], @@ -108,4 +110,44 @@ describe("markdown LaTeX math", () => { expect(root.querySelector("div[style]")).toBeNull(); expect(root.querySelectorAll(".katex")).toHaveLength(2); }); + + describe("escaped brackets from LSP hovers", () => { + const parseHover = (md: string) => parseSafe(md, hoverMarked); + + it("keeps unpadded bracket math elsewhere (agents, Markdown files)", () => { + expect(parseSafe("\\[x^2\\]").querySelector(".katex-display")).not.toBeNull(); + expect(parseHover("\\[x^2\\]").querySelector(".katex")).toBeNull(); + }); + + it("keeps the basedpyright str signature literal (#7454)", () => { + const md = "str(bytes\\_or\\_buffer\\[, encoding\\[, errors\\]\\]) -> str"; + const root = parseHover(md); + expect(root.querySelector(".katex")).toBeNull(); + expect(root.textContent?.trim()).toBe("str(bytes_or_buffer[, encoding[, errors]]) -> str"); + }); + + it.each([ + ["unpadded", "list\\[int\\] and dict\\[str, int\\]", "list[int] and dict[str, int]"], + ["nested", "f(a\\[, b\\[, c\\]\\])", "f(a[, b[, c]])"], + ["single unpadded line", "\\[x\\]", "[x]"], + ])("stays text: %s", (_n, md, expected) => { + const root = parseHover(md); + expect(root.querySelector(".katex")).toBeNull(); + expect(root.textContent?.trim()).toBe(expected); + }); + + it("still renders padded inline, multi-line, and neighbouring real math", () => { + const root = parseHover("a \\[ x^2 \\] b $y$ and \\(z\\)\n\n\\[\nq\n\\]\n\nlist\\[int\\]"); + expect(root.querySelectorAll(".katex")).toHaveLength(4); + expect(root.querySelectorAll(".katex-display")).toHaveLength(2); + expect([...root.querySelectorAll("p")].at(-1)!.textContent).toBe("list[int]"); + }); + + it("leaves code spans and fences alone", () => { + const root = parseHover("`f(a\\[, b\\])`\n\n```\n\\[ x \\]\n```"); + expect(root.querySelector(".katex")).toBeNull(); + expect(root.querySelector("p > code")?.textContent).toBe("f(a\\[, b\\])"); + expect(root.querySelector("pre")?.textContent).toBe("\\[ x \\]\n"); + }); + }); }); diff --git a/src/editor/lsp/markdownMath.ts b/src/editor/lsp/markdownMath.ts index 091a4e22a9..2f63e8f7c1 100644 --- a/src/editor/lsp/markdownMath.ts +++ b/src/editor/lsp/markdownMath.ts @@ -72,10 +72,18 @@ function matchInlineDollar(src: string, protectedDollar: RegExp): { end: number; return null; } +/** + * Real `\[ ... \]` math is padded with whitespace and never nests another `\[`: with + * `strictBrackets`, others are text. Servers such as basedpyright escape the literal brackets of + * a signature in hover Markdown (`str(x\[, encoding\])`, #7454). + */ +const isPaddedBracketMath = (text: string) => /^\s/.test(text) && /\s$/.test(text) && !text.includes("\\["); + /** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */ function matchInlineMath( src: string, protectedDollar = PROTECTED_INLINE_DOLLAR, + strictBrackets = false, ): { raw: string; text: string; display: boolean } | null { if (src.startsWith("$$")) { const close = findClosingDelimiter(src, 2, "$$"); @@ -107,6 +115,7 @@ function matchInlineMath( const close = findClosingDelimiter(src, 2, "\\]"); if (close > 2 && src[close + 2] !== "(") { const text = src.slice(2, close); + if (strictBrackets && !isPaddedBracketMath(text)) return null; if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true }; } return null; @@ -119,26 +128,27 @@ const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t 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 { +function matchBlockMath(src: string, strictBrackets = false): { 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]! }; + if (m && m[1]!.trim() && (!strictBrackets || re !== BLOCK_BRACKET_SINGLE || isPaddedBracketMath(m[1]!))) + 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 { +function maskInlineMath(src: string, strictBrackets = false): string { let out = ""; let start = 0; - for (const { index, raw } of inlineMathSpans(src, MASKED_PROTECTED_INLINE_DOLLAR)) { + for (const { index, raw } of inlineMathSpans(src, MASKED_PROTECTED_INLINE_DOLLAR, strictBrackets)) { out += src.slice(start, index) + raw.replace(/[^\r\n]/g, "a"); start = index + raw.length; } return start ? out + src.slice(start) : src; } -export function* inlineMathSpans(src: string, protectedDollar = PROTECTED_INLINE_DOLLAR) { +export function* inlineMathSpans(src: string, protectedDollar = PROTECTED_INLINE_DOLLAR, strictBrackets = false) { const delimiters = /[$\\]/g; for (let at = delimiters.exec(src); at; at = delimiters.exec(src)) { const i = at.index; @@ -146,7 +156,7 @@ export function* inlineMathSpans(src: string, protectedDollar = PROTECTED_INLINE delimiters.lastIndex++; continue; } - const math = matchInlineMath(src.slice(i), protectedDollar); + const math = matchInlineMath(src.slice(i), protectedDollar, strictBrackets); if (math) { yield { ...math, index: i }; delimiters.lastIndex = i + math.raw.length; @@ -154,11 +164,12 @@ export function* inlineMathSpans(src: string, protectedDollar = PROTECTED_INLINE } } -export function mathExtension(): MarkedExtension { +/** `strictBrackets`: single-line `\[...\]` is math only when padded (LSP hovers, see `isPaddedBracketMath`). */ +export function mathExtension({ strictBrackets = false }: { strictBrackets?: boolean } = {}): MarkedExtension { return { hooks: { emStrongMask(src) { - return maskInlineMath(src); + return maskInlineMath(src, strictBrackets); }, }, renderer: { @@ -176,7 +187,7 @@ export function mathExtension(): MarkedExtension { return m ? m.index : undefined; }, tokenizer(src): MathToken | undefined { - const m = matchBlockMath(src); + const m = matchBlockMath(src, strictBrackets); if (!m) return undefined; return { type: "blockMath", raw: m.raw, text: m.text, display: true }; }, @@ -202,7 +213,7 @@ export function mathExtension(): MarkedExtension { return undefined; }, tokenizer(src): MathToken | undefined { - const m = matchInlineMath(src); + const m = matchInlineMath(src, PROTECTED_INLINE_DOLLAR, strictBrackets); if (!m) return undefined; return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display }; }, diff --git a/src/editor/lsp/markdownParser.ts b/src/editor/lsp/markdownParser.ts index ac8db6bce6..048a256e3b 100644 --- a/src/editor/lsp/markdownParser.ts +++ b/src/editor/lsp/markdownParser.ts @@ -7,7 +7,8 @@ import { renderMath } from "./renderMarkdownMath"; /** 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 }).use(mathExtension()); +// Servers escape literal brackets in hover signatures (`\[`), see `isPaddedBracketMath`. +const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension({ strictBrackets: true })); export function markdownToSafeHtml(markdown: string): string { const html = marked.parse(markdown, { async: false }) as string;