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 $ 成立。"),