GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(web): add opt-in rendering for TeX equations by TheAnimatrix · Pull Request #18202 · pingdotgg/t3code

feat(web): add opt-in rendering for TeX equations #18202

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
TheAnimatrix wants to merge 11 commits into pingdotgg:main from TheAnimatrix:feat/render-chat-math

Uh oh!

There was an error while loading. Please reload this page.

Closed

feat(web): add opt-in rendering for TeX equations #18202

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit Hold shift + click to select a range
0d4aee4
feat(web): add opt-in rendering for TeX equations
TheAnimatrix Oct 8, 2026
5853826
fix(web): preserve file links containing rendered math when copying
TheAnimatrix Oct 8, 2026
83c1993
fix(web): keep math source stable when loading, copying, and citing
TheAnimatrix Oct 8, 2026
692c984
Merge remote-tracking branch 'origin/main' into feat/render-chat-math
TheAnimatrix Oct 8, 2026
29313e6
Merge remote-tracking branch 'origin/main' into feat/render-chat-math
TheAnimatrix Oct 8, 2026
992edb9
feat(web): accept $$ display fences and simplify math wiring
TheAnimatrix Oct 8, 2026
9bda800
fix(web): run an unclosed display block to the end of its container
TheAnimatrix Oct 8, 2026
f487974
Merge remote-tracking branch 'origin/main' into feat/render-chat-math
TheAnimatrix Oct 11, 2026
71bc695
test(web): stub computed styles for KaTeX's MathML in jsdom
TheAnimatrix Oct 11, 2026
3d2d9b8
Merge remote-tracking branch 'origin/main' into feat/render-chat-math
TheAnimatrix Oct 11, 2026
1587811
Merge branch 'main' into feat/render-chat-math
TheAnimatrix Oct 12, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
fix(web): run an unclosed display block to the end of its container
An unclosed `\[` or `$$` block failed after consuming later lines, which
flattened the lists and quotes that followed. Like a fenced code block,
it now ends at its closing line or the end of its container, and an
unclosed block is shown as source instead of typeset.
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@TheAnimatrix
TheAnimatrix committed Oct 8, 2026
commit 9bda800ca20b23ec8f721a9e0f1b9c9dd957fd4c

There are no files selected for viewing

22 changes: 22 additions & 0 deletions 22 apps/web/src/components/ChatMarkdown.test.tsx
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,28 @@ describe("ChatMarkdown math", () => {
}
});

it("shows an unfinished display formula as source until its closing line arrives", async () => {
settingsOverrides.mathRenderingEnabled = true;
const unfinished = "Intro\n\n$$\nx = 1";
const streaming = await renderMath(unfinished);
try {
expect(streaming.container.querySelector(".katex")).toBeNull();
expect(streaming.container.querySelector("[data-markdown-math]")).toBeNull();
const block = streaming.container.querySelector("pre");
expect(block?.textContent).toContain("$$");
expect(block?.textContent).toContain("x = 1");
} finally {
await streaming.unmount();
}
const finished = await renderMath(`${unfinished}\n$$`);
try {
expect(finished.tex(".katex-display")).toEqual(["x = 1"]);
} finally {
await finished.unmount();
delete settingsOverrides.mathRenderingEnabled;
}
});

it("shows the source of TeX that KaTeX rejects and copies formulas as TeX", async () => {
settingsOverrides.mathRenderingEnabled = true;
const view = await renderMath("Good \\(x^2\\), bad \\(\\frac{1\\).");
Expand Down
1 change: 0 additions & 1 deletion 1 apps/web/src/markdown-clipboard.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,6 @@ export function serializeTableElementToMarkdown(table: Element): string {
// the attribute from authored HTML.
const MATH_SELECTOR = "[data-markdown-math]";

/** The formula wrapper at or above `element`, if any. */
export function mathWrapperOf(element: Element | null): Element | null {
return element?.closest(MATH_SELECTOR) ?? null;
}
Expand Down
83 changes: 65 additions & 18 deletions 83 apps/web/src/markdown-math.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,32 @@ import { texMathFromMarkdown, texMathSyntax } from "./markdown-math";

type Node = { type: string; value?: string; children?: Node[] };

/** Math nodes in document order, as `type:value`. */
function mathIn(source: string): string[] {
const found: string[] = [];
function parse(source: string): Node {
return fromMarkdown(source, {
extensions: [texMathSyntax],
mdastExtensions: [texMathFromMarkdown],
}) as Node;
}

function nodesIn(source: string, ...types: string[]): Node[] {
const found: Node[] = [];
const visit = (node: Node) => {
if (node.type === "inlineMath" || node.type === "math")
found.push(`${node.type}:${node.value}`);
if (types.includes(node.type)) found.push(node);
node.children?.forEach(visit);
};
visit(
fromMarkdown(source, {
extensions: [texMathSyntax],
mdastExtensions: [texMathFromMarkdown],
}) as Node,
);
visit(parse(source));
return found;
}

/** Math nodes in document order, as `type:value`. */
const mathIn = (source: string) =>
nodesIn(source, "inlineMath", "math").map((node) => `${node.type}:${node.value}`);

/** Values of the code nodes in document order. */
const codeIn = (source: string) => nodesIn(source, "code").map((node) => node.value);

const typesOf = (node: Node) => node.children?.map((child) => child.type);

describe("TeX math syntax", () => {
it("reads \\(…\\) inline, including TeX backslashes and underscores", () => {
expect(mathIn("so \\(\\sigma\\propto r_1T^{-5}\\) holds")).toEqual([
Expand Down Expand Up @@ -66,11 +75,6 @@ describe("TeX math syntax", () => {
["currency", "Costs $5 and $10"],
["a single $", "$\nx\n$"],
["a citation", "see \\[1\\] and \\[2\\]"],
["an unclosed display block", "\\[\nx = 1\n"],
["an unclosed $$ block", "$$\nx = 1\n"],
["a $$ block closed by \\]", "$$\na\n\\]"],
["a \\[ block closed by $$", "\\[\na\n$$"],
["a display block cut by a lazy line", "> \\[\n> x\nlazy\n> \\]"],
["a link target", "[a](https://x.test/\\(b\\))"],
])("leaves %s alone", (_, source) => {
expect(mathIn(source)).toEqual([]);
Expand All @@ -87,8 +91,51 @@ describe("TeX math syntax", () => {
expect(performance.now() - start).toBeLessThan(2000);
});

it("ends an unfinished display block at the next opener", () => {
expect(mathIn("\\[\na\n\\[\nb\n\\]")).toEqual(["math:b"]);
it("keeps an opener line inside a display block as formula content", () => {
expect(mathIn("\\[\na\n\\[\nb\n\\]")).toEqual(["math:a\n\\[\nb"]);
});

it.each([
["an unclosed \\[ block", "\\[\nx = 1\n", "\\[\nx = 1"],
["an unclosed $$ block", "$$\nx = 1\n", "$$\nx = 1"],
["a $$ block closed by \\]", "$$\na\n\\]", "$$\na\n\\]"],
["a \\[ block closed by $$", "\\[\na\n$$", "\\[\na\n$$"],
["a display block cut by a lazy line", "> \\[\n> x\nlazy\n> \\]", "\\[\nx"],
["a display opener at the end", "text\n\n$$", "$$"],
])("shows %s as source in a code node", (_, source, code) => {
expect(mathIn(source)).toEqual([]);
expect(codeIn(source)).toEqual([code]);
});

it.each([
["\\[", "\\]"],
["$$", "$$"],
])("keeps the structure after a %s block", (open, close) => {
const closed = parse(`Intro\n${open}\nx\n${close}\n\n- a\n- b\n\n> quote`);
expect(typesOf(closed)).toEqual(["paragraph", "math", "list", "blockquote"]);
});

it.each(["\\[", "$$"])("runs an unclosed %s block to the end of the document", (open) => {
const source = `Intro\n${open}\n\n- a\n- b\n\n> quote`;
expect(typesOf(parse(source))).toEqual(["paragraph", "code"]);
expect(codeIn(source)).toEqual([`${open}\n\n- a\n- b\n\n> quote`]);
expect(codeIn(`Intro\n${open}\nx`)).toEqual([`${open}\nx`]);
});

it("ends an unclosed block with its list item", () => {
const [list, quote] = parse("- item\n $$\n x\n- next\n\n> quote").children!;
expect(typesOf(list!)).toEqual(["listItem", "listItem"]);
expect(typesOf(list!.children![0]!)).toEqual(["paragraph", "code"]);
expect(list!.children![0]!.children![1]!.value).toBe("$$\nx");
expect(typesOf(list!.children![1]!)).toEqual(["paragraph"]);
expect(quote?.type).toBe("blockquote");
});

it("ends an unclosed block with its blockquote", () => {
const tree = parse("> $$\n> x\n\nafter");
expect(typesOf(tree)).toEqual(["blockquote", "paragraph"]);
expect(typesOf(tree.children![0]!)).toEqual(["code"]);
expect(codeIn("> $$\n> x\n\nafter")).toEqual(["$$\nx"]);
});

it("scans a message of unmatched display openers in linear time", () => {
Expand Down
98 changes: 61 additions & 37 deletions 98 apps/web/src/markdown-math.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,17 @@ declare module "micromark-util-types" {
texMathTextData: "texMathTextData";
texMathFlow: "texMathFlow";
texMathFlowFence: "texMathFlowFence";
texMathFlowClosingFence: "texMathFlowClosingFence";
texMathFlowValue: "texMathFlowValue";
}
}

declare module "mdast-util-from-markdown" {
interface CompileData {
texMathFlowClosed?: boolean | undefined;
}
}

// \(…\) inline, and \[ / \] or $$ on their own lines for display. These run before
// CommonMark's escape construct, which would otherwise consume \( and \[. A
// one-line \[x\] stays prose so \[1\] citations do.
Expand Down Expand Up @@ -122,28 +129,30 @@ const texMathText: Construct = {
type Marker = readonly [first: number, second: number];

/**
* A line holding only the `open` marker, up to one holding only the `close`
* marker. Like a code fence, it must close; an unfinished formula (a reply still
* streaming) stays prose.
* A line holding only the `open` marker, then lines up to one holding only the
* `close` marker. Like a fenced code block, it runs to its closing line or the
* end of its container; an unclosed block is shown as source.
*/
const tokenizeTexMathFlow = (open: Marker, close: Marker): Tokenizer =>
function (effects, ok, nok) {
const interrupting = this.interrupt;
const nonLazyLine: Construct = {
partial: true,
tokenize(this: TokenizeContext, effects, ok, nok) {
return (code) => {
if (code === null) return nok(code);
effects.enter("lineEnding");
effects.consume(code);
effects.exit("lineEnding");
return (next) => (this.parser.lazy[this.now().line] ? nok(next) : ok(next));
};
},
};
const fenceLine = (marker: Marker): Construct => ({
const closingFence: Construct = {
partial: true,
tokenize(effects, ok, nok) {
return function start(code) {
effects.enter("texMathFlowFence");
effects.enter("texMathFlowClosingFence");
return indent(code);
};

Expand All @@ -152,10 +161,10 @@ const tokenizeTexMathFlow = (open: Marker, close: Marker): Tokenizer =>
effects.consume(code);
return indent;
}
if (code !== marker[0]) return nok(code);
if (code !== close[0]) return nok(code);
effects.consume(code);
return function second(code) {
if (code !== marker[1]) return nok(code);
if (code !== close[1]) return nok(code);
effects.consume(code);
return fenceEnd;
};
Expand All @@ -167,13 +176,11 @@ const tokenizeTexMathFlow = (open: Marker, close: Marker): Tokenizer =>
return fenceEnd;
}
if (code !== null && !isLineEnding(code)) return nok(code);
effects.exit("texMathFlowFence");
effects.exit("texMathFlowClosingFence");
return ok(code);
}
},
});
const closingFence = fenceLine(close);
const openingFence = fenceLine(open);
};

return function start(code) {
effects.enter("texMathFlow");
Expand All @@ -186,37 +193,36 @@ const tokenizeTexMathFlow = (open: Marker, close: Marker): Tokenizer =>
};
};

// Only the opening line can fail. Past it the block ends in `ok`, closed or
// not. Checking whether the line interrupts a paragraph stops there too.
function openEnd(code: Code): State | undefined {
if (isSpace(code)) {
effects.consume(code);
return openEnd;
}
if (!isLineEnding(code)) return nok(code);
if (code !== null && !isLineEnding(code)) return nok(code);
effects.exit("texMathFlowFence");
return effects.attempt(nonLazyLine, lineStart, nok)(code);
return interrupting ? ok(code) : lineEnd(code);
}

function lineStart(code: Code): State | undefined {
return effects.attempt(closingFence, finish, notOpening)(code);
function lineEnd(code: Code): State | undefined {
return effects.attempt(nonLazyLine, lineStart, finish)(code);
}

// Another opener cannot be inside a formula. Giving up at it keeps a run of
// unclosed openers linear.
function notOpening(code: Code): State | undefined {
return effects.attempt(openingFence, nok, content)(code);
function lineStart(code: Code): State | undefined {
return effects.attempt(closingFence, finish, content)(code);
}

function content(code: Code): State | undefined {
if (code === null) return nok(code);
if (isLineEnding(code)) return effects.attempt(nonLazyLine, lineStart, nok)(code);
if (code === null || isLineEnding(code)) return lineEnd(code);
effects.enter("texMathFlowValue");
return value(code);
}

function value(code: Code): State | undefined {
if (code === null || isLineEnding(code)) {
effects.exit("texMathFlowValue");
return content(code);
return lineEnd(code);
}
effects.consume(code);
return value;
Expand Down Expand Up @@ -250,8 +256,7 @@ export const texMathFromMarkdown: FromMarkdownExtension = {
this.enter({ type: "inlineMath", value: "", data: { hName: "code" } } as never, token);
this.buffer();
},
texMathFlow(token) {
this.enter({ type: "math", value: "", data: { hName: "pre" } } as never, token);
texMathFlow() {
this.buffer();
},
},
Expand Down Expand Up @@ -279,29 +284,48 @@ export const texMathFromMarkdown: FromMarkdownExtension = {
node.data.hChildren = [{ type: "text", value }];
this.exit(token);
},
texMathFlowClosingFence() {
this.data.texMathFlowClosed = true;
},
texMathFlow(token) {
const closed = this.data.texMathFlowClosed;
this.data.texMathFlowClosed = undefined;
const value = this.resume()
.replace(/\r\n?/g, "\n")
.replace(/^\n|\n$/g, "");
const node = this.stack.at(-1) as unknown as {
value: string;
data: Record<string, unknown>;
};
node.value = value;
node.data.hChildren = [
if (!closed) {
// Not a formula: a plain code node that keeps its opener line.
const opener = this.sliceSerialize(token).slice(0, 2);
this.enter(
{ type: "code", lang: null, meta: null, value: value ? `${opener}\n${value}` : opener },
token,
);
this.exit(token);
return;
}
this.enter(
{
type: "element",
tagName: "code",
properties: { className: ["language-math-display"] },
children: [{ type: "text", value }],
},
];
type: "math",
value,
data: {
hName: "pre",
hChildren: [
{
type: "element",
tagName: "code",
properties: { className: ["language-math-display"] },
children: [{ type: "text", value }],
},
],
},
} as never,
token,
);
this.exit(token);
},
},
};

/** unified plugin: registers both extensions on the remark-parse processor. */
export const remarkTexMath = function (this: Processor) {
const data = this.data() as {
micromarkExtensions?: MicromarkExtension[];
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.