From a38a64414781974dfff8b213e2e5ca689056a687 Mon Sep 17 00:00:00 2001 From: Sagar Thakrar Date: Wed, 3 Jun 2026 00:57:11 +0530 Subject: [PATCH] fix(web): preserve math before citation linkification --- web/lib/markdown-display.ts | 8 ++++++-- web/tests/markdown-display.test.ts | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.ts index 34c93c7d9..630f7a3d9 100644 --- a/web/lib/markdown-display.ts +++ b/web/lib/markdown-display.ts @@ -138,6 +138,7 @@ const ALLOWED_HTML_TAGS = new Set([ const HTML_LIKE_TAG_REGEX = /<\/?([A-Za-z][A-Za-z0-9_-]*)\b[^<>]*?\/?>/g; const FENCED_CODE_BLOCK_REGEX = /```[\s\S]*?```/g; const INLINE_CODE_SPAN_REGEX = /`[^`\n]*`/g; +const MATH_SPAN_REGEX = /\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$\$[\s\S]*?\$\$/g; const PROTECTED_SPAN_REGEX = /```[\s\S]*?```|`[^`\n]*`/g; const PROTECTED_PLACEHOLDER_REGEX = /\u0000PROTECTED_(\d+)\u0000/g; const HTML_ATTR_VALUE = /(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+)/.source; @@ -468,13 +469,16 @@ function linkifyCitationsOutsideCode(content: string): string { FENCED_CODE_BLOCK_REGEX, "FENCED_CODE", ); - const unwrapped = unwrapBacktickedCitations(fenced.masked); + const math = maskProtectedSpans(fenced.masked, MATH_SPAN_REGEX, "MATH"); + const unwrapped = unwrapBacktickedCitations(math.masked); const inline = maskProtectedSpans( unwrapped, INLINE_CODE_SPAN_REGEX, "INLINE_CODE", ); - return fenced.restore(inline.restore(linkifyCitations(inline.masked))); + return fenced.restore( + math.restore(inline.restore(linkifyCitations(inline.masked))), + ); } export function normalizeMarkdownForDisplay(content: string): string { diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.ts index c67c28c12..014000d14 100644 --- a/web/tests/markdown-display.test.ts +++ b/web/tests/markdown-display.test.ts @@ -73,6 +73,20 @@ test("normalizeMarkdownForDisplay keeps array indexes inside inline code", () => assert.equal(normalizeMarkdownForDisplay(input), input); }); +test("normalizeMarkdownForDisplay keeps bracketed vectors inside display math", () => { + const input = ["The row for `sat` is:", "", "\\[", "[1, 1, 2]", "\\]"].join( + "\n", + ); + assert.equal(normalizeMarkdownForDisplay(input), input); +}); + +test("normalizeMarkdownForDisplay keeps bracketed vectors inside weighted math", () => { + const input = ["\\[", "0.212[1, 1] + 0.212[2, 0] + 0.576[0, 3]", "\\]"].join( + "\n", + ); + assert.equal(normalizeMarkdownForDisplay(input), input); +}); + test("normalizeMarkdownForDisplay unwraps explicit citation code spans outside code", () => { assert.equal( normalizeMarkdownForDisplay("See `[web-1]` for details."),