From c55776f680c8fcf40135a16b5b7cc4e90b5ad605 Mon Sep 17 00:00:00 2001 From: riccardo-algorime Date: Tue, 10 Nov 2026 13:56:10 +0000 Subject: [PATCH] fix(web): tighten a loose $ formula before wrapping bare LaTeX A formula closed with a space before the dollar (`$\lim a_n = $ ____`, the usual shape of a fill-in-the-blank question) is no MATH_SPAN_RE match, so the bare-LaTeX pass wrapped its body again and produced `$$\lim a_n =$ $`: a display block that never closes, with the rest of the text raw. Pairing the dollars before that pass tightens it first; the final pass still runs as before. Co-Authored-By: Claude Opus 5.5 --- web/lib/latex-normalize.ts | 4 ++++ web/tests/latex-normalize.test.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/web/lib/latex-normalize.ts b/web/lib/latex-normalize.ts index ff29bf7eb..cd929ecdb 100644 --- a/web/lib/latex-normalize.ts +++ b/web/lib/latex-normalize.ts @@ -603,6 +603,10 @@ function normalizeProse(text: string, mathContext: boolean): string { result = convertBracketDelimiters(result); result = convertParenDelimiters(result); + // Pair the dollars first as well: a loose formula (`$\lim a_n = $ ____`) is + // no MATH_SPAN_RE match until it is tightened, and the bare-LaTeX pass would + // otherwise wrap its body a second time (`$$\lim a_n =$ $`). + result = escapeStrayDollars(result); const math = maskSpans(result, MATH_SPAN_RE, "MATH"); result = math.restore(wrapBareLatex(math.masked)); result = escapeStrayDollars(result); diff --git a/web/tests/latex-normalize.test.ts b/web/tests/latex-normalize.test.ts index edfbd26c7..7b75f2796 100644 --- a/web/tests/latex-normalize.test.ts +++ b/web/tests/latex-normalize.test.ts @@ -132,6 +132,20 @@ test("an inline paren formula never merges two table cells", () => { assert.equal(normalizeMathMarkup(input), input); }); +test("a loose $ pair around LaTeX is tightened, not wrapped again", () => { + // A fill-in-the-blank question: the model closes the formula before the + // blank, with a space. The bare-LaTeX pass used to wrap the body a second + // time, giving `$$\lim … =$ $`, a display block that never closes. + assert.equal( + normalizeMathMarkup("si ha $\\lim_{n \\to +\\infty} a_n = $ ____."), + "si ha $\\lim_{n \\to +\\infty} a_n =$ ____.", + ); + assert.equal( + normalizeMathMarkup("Let $a_n = \\frac{1}{n}$, so $ \\lim a_n = $ ____."), + "Let $a_n = \\frac{1}{n}$, so $\\lim a_n =$ ____.", + ); +}); + test("a loose $ pair is tightened rather than dropped", () => { assert.equal( normalizeMathMarkup("由此 $ x + y $ 成立。"),