Skip to content

Commit 3e0486e

Browse files
ElliotDrelclaude
andcommitted
fix(web): repair glued percents on every line of an equation
Scan the formula once the way KaTeX lexes it: skip escapes and same-line \verb bodies, escape a % written right after text, and leave a % at a line start or after whitespace as a comment. This repairs the reported multiline equation, stays linear on long backslash runs, and still repairs labels after a \verb. The test now covers the exact multiline equation and checks the raw-source cases only after KaTeX has loaded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 52d45df commit 3e0486e

2 files changed

Lines changed: 79 additions & 37 deletions

File tree

‎apps/web/src/components/chat/MarkdownMath.browser.test.tsx‎

Lines changed: 38 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -35,34 +35,42 @@ it("keeps keyboard scrolling available as a streamed equation outgrows its viewp
3535
await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus();
3636
});
3737

38-
it("typesets a display equation whose label has an unescaped percent", async () => {
39-
const tex =
40-
"R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}+\\underbrace{6\\%}_{\\text{growth}}=\\boxed{9.18\\%}";
41-
const adjacent = "\\text{100%% yield}";
42-
const paired = "\\begin{aligned}x\\\\%\\end{aligned}";
43-
const commented = "\\begin{aligned}\nx &= 1 % +999\n\\\\ y &= \\text{2%}\n\\end{aligned}";
44-
const verbatim = "\\verb|100%|+\\text{2%}";
45-
await using screen = await render(
46-
<>
47-
<MarkdownMath tex={tex} display />
48-
<MarkdownMath tex={adjacent} display />
49-
<MarkdownMath tex={paired} display />
50-
<MarkdownMath tex={commented} display />
51-
<MarkdownMath tex={verbatim} display />
52-
</>,
53-
);
54-
await vi.waitFor(() => expect(screen.container.querySelector(".katex")).not.toBeNull());
55-
const text = screen.container.textContent ?? "";
56-
expect(text).toContain("9.18%");
57-
expect(text.replaceAll("\u00a0", " ")).toContain("3.18% dividend yield");
58-
const equations = screen.container.querySelectorAll("[data-markdown-math]");
59-
expect(equations[0]?.querySelector(".katex")).not.toBeNull();
60-
expect(equations[1]?.querySelector(".katex")).not.toBeNull();
61-
expect(equations[1]?.textContent?.replaceAll("\u00a0", " ")).toContain("100%% yield");
62-
expect(equations[2]?.querySelector(".katex")).not.toBeNull();
63-
expect(equations[3]?.querySelector(".katex")).toBeNull();
64-
expect(equations[3]?.textContent).toBe(`\\[\n${commented}\n\\]`);
65-
expect(equations[4]?.querySelector(".katex")).toBeNull();
66-
expect(equations[4]?.textContent).toBe(`\\[\n${verbatim}\n\\]`);
67-
expect(equations[0]?.getAttribute("data-markdown-copy")).toBe(`\\[\n${tex}\n\\]\n\n`);
38+
it("typesets equations whose labels have an unescaped percent", async () => {
39+
// The reported multiline equation, line breaks included.
40+
const issue =
41+
"R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}";
42+
const typeset = [
43+
issue,
44+
"\\text{100%% yield}",
45+
"\\begin{aligned}x\\\\%\\end{aligned}",
46+
"\\begin{aligned}\nx &= 1 % +999\n\\\\ y &= \\text{2%}\n\\end{aligned}",
47+
"\\verb|50%|+\n\\text{2%}",
48+
"x % note\n+ 1",
49+
];
50+
const raw = ["\\frac{1", "\\text{50 % off}", "\\verb|50%+\\text{2%}"];
51+
const equations = (tex: string[]) => tex.map((t) => <MarkdownMath key={t} tex={t} display />);
52+
await using screen = await render(<>{equations(typeset)}</>);
53+
const rendered = () => [...screen.container.querySelectorAll("[data-markdown-math]")];
54+
const visibleText = (index: number) =>
55+
rendered()[index]?.querySelector(".katex-html")?.textContent?.replaceAll("\u00a0", " ");
56+
await vi.waitFor(() => {
57+
for (const equation of rendered()) expect(equation.querySelector(".katex")).not.toBeNull();
58+
});
59+
expect(visibleText(0)).toContain("3.18% dividend yield");
60+
expect(visibleText(0)).toContain("9.18%");
61+
expect(rendered()[0]?.getAttribute("data-markdown-copy")).toBe(`\\[\n${issue}\n\\]\n\n`);
62+
expect(visibleText(1)).toContain("100%% yield");
63+
expect(visibleText(3)).toContain("2%");
64+
expect(visibleText(3)).not.toContain("999");
65+
expect(visibleText(4)).toContain("50%");
66+
expect(visibleText(4)).toContain("2%");
67+
expect(visibleText(5)).not.toContain("note");
68+
69+
// KaTeX has loaded, so these render their final result in this commit.
70+
await screen.rerender(<>{equations([...typeset, ...raw])}</>);
71+
raw.forEach((tex, offset) => {
72+
const equation = rendered()[typeset.length + offset];
73+
expect(equation?.querySelector(".katex")).toBeNull();
74+
expect(equation?.textContent).toBe(`\\[\n${tex}\n\\]`);
75+
});
6876
});

‎apps/web/src/components/chat/MathTypeset.tsx‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,46 @@ import { LRUCache } from "../../lib/lruCache";
88
// that from typesetting the same formulas again. "" records a parse error.
99
const typesetCache = new LRUCache<string>(1000, 4 * 1024 * 1024);
1010

11+
/**
12+
* Escapes each `%` written right after other text, as in `\text{3.18% yield}`.
13+
* A `%` at a line start or after whitespace stays a comment. Skips escapes and
14+
* `\verb` like KaTeX's lexer, in one linear pass.
15+
*/
16+
function escapeLiteralPercents(tex: string): string {
17+
let repaired = "";
18+
let copied = 0;
19+
let index = 0;
20+
while (index < tex.length) {
21+
const char = tex[index];
22+
if (char === "\\") {
23+
if (tex.startsWith("\\verb", index)) {
24+
const starred = tex[index + 5] === "*";
25+
const delimiter = tex[index + (starred ? 6 : 5)];
26+
if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) {
27+
const bodyStart = index + (starred ? 7 : 6);
28+
let close = bodyStart;
29+
while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++;
30+
// KaTeX rejects a \verb that does not close on its own line.
31+
if (tex[close] !== delimiter) return tex;
32+
index = close + 1;
33+
continue;
34+
}
35+
}
36+
// A control symbol such as `\%` or `\\` is two characters.
37+
index += 2;
38+
} else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) {
39+
repaired += `${tex.slice(copied, index)}\\%`;
40+
copied = ++index;
41+
} else if (char === "%") {
42+
const newline = tex.indexOf("\n", index);
43+
index = newline === -1 ? tex.length : newline + 1;
44+
} else {
45+
index++;
46+
}
47+
}
48+
return copied === 0 ? tex : repaired + tex.slice(copied);
49+
}
50+
1151
function typeset(tex: string, display: boolean): string {
1252
const key = `${display ? "display" : "inline"}:${tex}`;
1353
const cached = typesetCache.get(key);
@@ -26,13 +66,7 @@ function typeset(tex: string, display: boolean): string {
2666
try {
2767
html = katex.renderToString(tex, options);
2868
} catch {
29-
// A percent before a newline may be an authored TeX comment; leave it alone.
30-
const lastNewline = Math.max(tex.lastIndexOf("\n"), tex.lastIndexOf("\r"));
31-
const repaired = tex.includes("\\verb")
32-
? tex
33-
: tex.replace(/(\\*)%/g, (match, backslashes: string, offset: number) =>
34-
backslashes.length % 2 === 0 && offset > lastNewline ? `${backslashes}\\%` : match,
35-
);
69+
const repaired = escapeLiteralPercents(tex);
3670
if (repaired !== tex) {
3771
try {
3872
html = katex.renderToString(repaired, options);

0 commit comments

Comments
 (0)