Skip to content
TypeScript

feat(markdown): render LaTeX across web and native mobile (#18735)

Yash Singhcb0553ea3941
diff --git a/apps/mobile/deps/README.md b/apps/mobile/deps/README.md
index bdb490f972a..cf51c97c856 100644
--- a/apps/mobile/deps/README.md
+++ b/apps/mobile/deps/README.md
@@ -1,3 +1,3 @@
-The Enriched Markdown tarball comes from the [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. File/skill link recognition, back navigation from horizontal blocks, table-image presses, and code-block headers use upstream implementations. The remaining fork adds clipboard metadata, parsed asset manifests, signed image source resolution, React media slots, and development-host autolinks.
+The Enriched Markdown tarball comes from [`feat/t3chat-markdown-parity-v2`](https://github.com/pingdotgg/enriched-markdown/tree/feat/t3chat-markdown-parity-v2), based on Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. File/skill link recognition, back navigation from horizontal blocks, table-image presses, and code-block headers use upstream implementations. The fork retains clipboard metadata, parsed asset manifests, signed image source resolution, React media slots, and development-host autolinks. The fork retains native math parsing, scrolling and copying, table layout and gestures, and inline-code layout. Character-reference decoding, iOS intrinsic-width measurement, and HTML clipboard round trips now use the upstream fixes included in Julius's base. RaTeX uses the upstream-released 0.1.15 dependency.
-To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Bump the fork package version for each replacement, update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.
+To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. Native clients need rebuilding when this dependency changes.
diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz
new file mode 100644
index 00000000000..e8c91b75a78
Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz differ
diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz
deleted file mode 100644
index dbf87fde65e..00000000000
Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz and /dev/null differ
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index c4c5905d164..150350090ab 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -125,7 +125,7 @@
"react-dom": "catalog:",
"react-native": "0.88.0",
"react-native-blob-util": "0.25.1",
- "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz",
+ "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz",
"react-native-gesture-handler": "~3.3.0",
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.22.7",
@@ -159,7 +159,7 @@
"typescript": "catalog:"
},
"enriched-markdown": {
- "enableMath": false,
+ "enableMath": true,
"enableVideo": false
},
"expo": {
diff --git a/apps/mobile/src/features/review/ReviewCommentCard.tsx b/apps/mobile/src/features/review/ReviewCommentCard.tsx
index 000638d14c9..01596bd6234 100644
--- a/apps/mobile/src/features/review/ReviewCommentCard.tsx
+++ b/apps/mobile/src/features/review/ReviewCommentCard.tsx
@@ -1,6 +1,8 @@
import { memo, useMemo, useState } from "react";
import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
import { ScrollView, StyleSheet, Text as NativeText, View, type ColorValue } from "react-native";
+import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
+import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
import { AppText as Text } from "../../components/ui/AppText";
import { SymbolView } from "../../components/ui/AppSymbol";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
@@ -48,6 +50,7 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
readonly colors: ReviewCommentColors;
}) {
const { codeSurface, nativeReviewDiffStyle } = useAppearanceCodeSurface();
+ const markdownStyles = useMarkdownPreviewStyles();
const { themeAppearance: appearanceScheme, themeId } = useAppearancePreferences();
const appTheme = useUniwindTheme();
const [NativeReviewDiffView] = useState(() => resolveNativeReviewDiffView());
@@ -166,9 +169,10 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
</View>
{props.comment.text.length > 0 ? (
<View className="px-3 py-3">
- <Text selectable className="text-base leading-snug" style={{ color: props.colors.text }}>
- {props.comment.text}
- </Text>
+ <SelectableMarkdownText
+ markdown={props.comment.text}
+ textStyle={markdownStyles.nativeTextStyle}
+ />
</View>
) : null}
{shouldRenderNativeDiff ? (
diff --git a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
index 310c1f4ee68..4a142511c39 100644
--- a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
+++ b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
@@ -68,6 +68,8 @@ interface AppearancePreferencesContextValue {
readonly setTerminalFontSize: (value: number | null) => void;
readonly setCodeFontSize: (value: number | null) => void;
readonly setCodeWordBreak: (value: boolean) => void;
+ readonly mathRenderingEnabled: boolean;
+ readonly setMathRenderingEnabled: (value: boolean) => void;
}
const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
@@ -264,6 +266,12 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
[updatePreferences],
);
+ const mathRenderingEnabled = storedPreferences?.mathRenderingEnabled === true;
+ const setMathRenderingEnabled = useCallback(
+ (value: boolean) => updatePreferences({ mathRenderingEnabled: value }),
+ [updatePreferences],
+ );
+
const value = useMemo(
(): AppearancePreferencesContextValue => ({
appearance,
@@ -284,6 +292,8 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
setTerminalFontSize,
setCodeFontSize,
setCodeWordBreak,
+ mathRenderingEnabled,
+ setMathRenderingEnabled,
}),
[
appearance,
@@ -303,6 +313,8 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
setTerminalFontSize,
setCodeFontSize,
setCodeWordBreak,
+ mathRenderingEnabled,
+ setMathRenderingEnabled,
],
);
diff --git a/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx b/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx
index c1424088f8d..1a1c61012b7 100644
--- a/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx
+++ b/apps/mobile/src/features/settings/appearance/sections/TextAppearanceSection.tsx
@@ -10,9 +10,11 @@ import {
TextAppearancePreview,
} from "../components/AppearancePreviews";
import { FontSizeSliderRow } from "../components/FontSizeSliderRow";
+import { SettingsSwitchRow } from "../../components/SettingsSwitchRow";
export function TextAppearanceSection() {
- const { isReady, appearance, setBaseFontSize } = useAppearancePreferences();
+ const { isReady, appearance, setBaseFontSize, mathRenderingEnabled, setMathRenderingEnabled } =
+ useAppearancePreferences();
return (
<SettingsSection title="Text">
@@ -29,6 +31,13 @@ export function TextAppearanceSection() {
value={appearance.baseFontSize}
valueLabel={`${appearance.baseFontSize} pt`}
/>
+ <SettingsSwitchRow
+ disabled={!isReady}
+ icon="plusminus"
+ label="Render math"
+ value={mathRenderingEnabled}
+ onValueChange={setMathRenderingEnabled}
+ />
</SettingsSection>
);
}
diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx
index 7fb3a51281e..7e7ecf39674 100644
--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx
+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx
@@ -59,6 +59,15 @@ function enrichedStyle(
};
return {
paragraph: body,
+ math: {
+ fontSize: style.fontSize,
+ color: style.color,
+ backgroundColor: "transparent",
+ padding: 8,
+ marginTop: 4,
+ marginBottom: 12,
+ },
+ inlineMath: { color: style.color },
h1: heading(1),
h2: heading(2),
h3: heading(3),
@@ -140,11 +149,11 @@ function enrichedStyle(
export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
const { renderImage, resolveImageSource } = props;
+ const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
const markdown = useMemo(
() => markdownWithTableBreaks(markdownWithHtml(props.markdown)),
[props.markdown],
);
- const { themeAppearance } = useAppearancePreferences();
const [documentAssets, setDocumentAssets] = useState<DocumentAssetsEvent["assets"]>([]);
const onDocumentAssets = useCallback(({ assets }: DocumentAssetsEvent) => {
setDocumentAssets((previous) =>
@@ -308,7 +317,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
selectionColor={props.textStyle.selectionColor}
selectionHandleColor={props.textStyle.selectionHandleColor}
md4cFlags={{
- latexMath: false,
+ latexMath: mathRenderingEnabled,
hardSoftBreaks: props.preserveSoftBreaks ?? false,
admonitions: true,
}}
diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts
index 4ec0f9ea8cc..7acdd47e4e6 100644
--- a/apps/mobile/src/persistence/mobile-preferences.ts
+++ b/apps/mobile/src/persistence/mobile-preferences.ts
@@ -63,6 +63,7 @@ export interface Preferences {
readonly markdownFontSize?: number;
readonly codeFontSize?: number | null;
readonly codeWordBreak?: boolean;
+ readonly mathRenderingEnabled?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
/** Environments whose "reclaim database space" notice was dismissed. */
@@ -137,6 +138,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
markdownFontSize?: number;
codeFontSize?: number | null;
codeWordBreak?: boolean;
+ mathRenderingEnabled?: boolean;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
dismissedDatabaseStorageNotices?: readonly string[];
@@ -206,6 +208,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
preferences.codeFontSize = parsed.codeFontSize;
}
if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
+ if (typeof parsed.mathRenderingEnabled === "boolean")
+ preferences.mathRenderingEnabled = parsed.mathRenderingEnabled;
if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
(account): account is string => typeof account === "string",
diff --git a/apps/web/package.json b/apps/web/package.json
index 09107e5d126..e6b1bc8471d 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -61,6 +61,7 @@
"jose": "catalog:",
"jsonc-parser": "3.3.1",
"jszip": "3.10.1",
+ "katex": "^0.16.47",
"lucide": "^0.564.0",
"lucide-react": "^0.564.0",
"mermaid": "^11.17.2",
@@ -69,6 +70,7 @@
"react-dom": "catalog:",
"react-markdown": "^10.1.0",
"remark-gfm": "catalog:",
+ "remark-math": "6.0.0",
"tailwind-merge": "^3.4.0",
"unbash": "^5.0.0",
"use-sync-external-store": "^1.6.0",
diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx
index 58a4c556685..f29ee18bd92 100644
--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx
@@ -5,6 +5,7 @@ import { AsyncResult } from "effect/reactivity";
import { act, type ReactElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { page, userEvent } from "vite-plus/test/browser";
import { filesystemEnvironment } from "../state/filesystem";
import { useRightPanelStore } from "../rightPanelStore";
@@ -64,11 +65,25 @@ vi.mock(import("./chat/MermaidDiagram"), async (original) => {
};
});
+const settingsOverrides = vi.hoisted(() => ({ mathRenderingEnabled: false }));
+vi.mock(import("../hooks/useSettings"), async (original) => {
+ const actual = await original();
+ type Settings = ReturnType<typeof actual.getClientSettings>;
+ function useClientSettings<T = Settings>(select?: (settings: Settings) => T): T {
+ const settings = { ...actual.getClientSettings(), ...settingsOverrides };
+ return select ? select(settings) : (settings as T);
+ }
+ return { ...actual, useClientSettings };
+});
+
import ChatMarkdown from "./ChatMarkdown";
+import { serializeTableElementToCsv, chatMarkdownClipboardPayload } from "../markdown-clipboard";
+import { captureAssistantTextSelection } from "../lib/assistantTextSelection";
const roots: Root[] = [];
beforeEach(() => {
+ settingsOverrides.mathRenderingEnabled = false;
renderDiagram.mockReset();
workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] }));
@@ -1129,3 +1144,168 @@ describe("ChatMarkdown thread find", () => {
},
);
});
+
+describe("ChatMarkdown math", () => {
+ const renderMath = async (
+ text: string,
+ options: Partial<Parameters<typeof ChatMarkdown>[0]> = {},
+ ) => {
+ settingsOverrides.mathRenderingEnabled = true;
+ const { container: host } = await render(
+ <ChatMarkdown cwd="/tmp/project" text={text} {...options} />,
+ );
+ host.setAttribute("data-assistant-citation-source", "assistant");
+ await act(async () => {
+ await import("./chat/MathTypeset");
+ });
+ return { host };
+ };
+
+ it.each(["$x$", "$$x$$", "```math\nx\n```", "$\\notACommand{x}$"])(
+ "keeps keyboard focus on the parent control in compact previews of %s",
+ async (formula) => {
+ settingsOverrides.mathRenderingEnabled = true;
+ const { container } = await render(
+ <>
+ <button type="button">
+ Preview <ChatMarkdown inline text={formula} cwd={undefined} />
+ </button>
+ <button type="button">After preview</button>
+ </>,
+ );
+ await act(async () => {
+ await import("./chat/MathTypeset");
+ });
+ const [preview, after] = container.querySelectorAll("button");
+ preview!.focus();
+ await act(() => userEvent.tab());
+ expect(document.activeElement).toBe(after);
+ if (formula.includes("notACommand")) {
+ expect(page.getByRole("button", { name: /notACommand/ }).element()).toBe(preview);
+ }
+ },
+ );
+
+ it("keeps message formulas reachable by keyboard", async () => {
+ settingsOverrides.mathRenderingEnabled = true;
+ const { container } = await render(
+ <>
+ <button type="button">Before equation</button>
+ <ChatMarkdown text="$x$" cwd={undefined} />
+ </>,
+ );
+ container.querySelector("button")!.focus();
+ await act(() => userEvent.tab());
+ expect(document.activeElement).toBe(
+ container.querySelector('[aria-label="Scroll inline equation"]'),
+ );
+ });
+
+ it("renders table formulas and exports their TeX instead of duplicate glyph text", async () => {
+ const rendered = await renderMath(
+ "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ and \\(\\|y\\|\\) |\n| Price | $5 and $10 |",
+ );
+
+ const table = rendered.host.querySelector("table")!;
+ expect([...table.rows].map((row) => row.cells.length)).toEqual([2, 2, 2]);
+ expect(table.querySelectorAll(".katex")).toHaveLength(2);
+ const norm = table.querySelectorAll(".katex")[1]!;
+ expect([...norm.querySelectorAll(".katex-mathml mi")].map((node) => node.textContent)).toEqual([
+ "∥",
+ "y",
+ "∥",
+ ]);
+ expect(serializeTableElementToCsv(table)).toBe(
+ "Name,Formula\nNorm,\\(|x|\\) and \\(\\|y\\|\\)\nPrice,$5 and $10",
+ );
+ const glyph = table.querySelector(".katex-mathml mi")!.firstChild!;
+ const range = document.createRange();
+ range.setStart(glyph, 0);
+ range.setEnd(glyph, 1);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ const payload = chatMarkdownClipboardPayload(selection)!;
+ expect(payload.text).toBe("\\(|x|\\)");
+ expect(payload.html).toContain("\\(|x|\\)");
+ expect(payload.html).not.toContain("katex");
+ expect(captureAssistantTextSelection(rendered.host, selection)?.selector.text).toBe(
+ "\\(|x|\\)",
+ );
+ });
+
+ it("renders explicit math fences and keeps unfinished streamed fences readable", async () => {
+ const rendered = await renderMath("```math\nx_i^2\n```\n\n`$literal$`\n\n$unfinished");
+
+ expect(rendered.host.querySelectorAll(".katex")).toHaveLength(1);
+ expect(rendered.host.textContent).toContain("$literal$");
+ expect(rendered.host.textContent).toContain("$unfinished");
+
+ const streamed = await renderMath("```math\nx_i^2", { isStreaming: true });
+
+ expect(streamed.host.querySelector(".katex")).toBeNull();
+ expect(streamed.host.textContent).toContain("x_i^2");
+ });
+
+ it.each(["$$\nx^2\n", "\\[\nx^2\n"])(
+ "keeps unfinished display %s and following prose readable while streaming",
+ async (source) => {
+ for (const text of [source, `${source}\nFollowing prose.`]) {
+ const { host } = await renderMath(text, { isStreaming: true });
+ expect(host.querySelector(".katex")).toBeNull();
+ expect(host.querySelector("[data-markdown-math]")).toBeNull();
+ expect(host.textContent).toContain("x^2");
+ if (text.includes("Following prose."))
+ expect(host.textContent).toContain("Following prose.");
+ }
+ },
+ );
+
+ it.each(["$$x^2$$", "$$\nx^2\n$$", "\\[\nx^2\n\\]", "```math\nx^2\n```"])(
+ "renders completed %s while the response is streaming",
+ async (source) => {
+ const { host } = await renderMath(source, { isStreaming: true });
+ expect(host.querySelectorAll(".katex")).toHaveLength(1);
+ expect(host.querySelector('[data-markdown-math="display"]')).not.toBeNull();
+ },
+ );
+
+ it("shows unsupported TeX as source and keeps active TeX commands inert", async () => {
+ const rendered = await renderMath(
+ "\\(\\notACommand{x}\\) and \\(\\href{https://example.com}{x}\\)",
+ );
+
+ expect(rendered.host.textContent).toContain("\\(\\notACommand{x}\\)");
+ expect(rendered.host.querySelector('a[href="https://example.com"]')).toBeNull();
+ });
+
+ it("typesets only when enabled, keeping prices and task offsets intact", async () => {
+ const text = "Area $\\pi r^2$ costs $5 and $10.\n\n\\[\nE = mc^2\n\\]\n\n- [ ] check \\(x\\)";
+ const off = await renderText(text);
+ expect(off.querySelector("[data-markdown-math]")).toBeNull();
+ const html = await renderText('<code class="language-math math-inline">x</code>');
+ expect(html.querySelector("[data-markdown-math]")).toBeNull();
+ for (const parseRawHtml of [true, false]) {
+ let editedText = text;
+ const { host } = await renderMath(text, {
+ parseRawHtml,
+ onTaskListChange: ({ markerOffset, checked }) => {
+ editedText = setMarkdownTaskChecked(text, markerOffset, checked);
+ },
+ });
+ expect(
+ [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
+ node.getAttribute("data-markdown-copy"),
+ ),
+ ).toEqual(["\\(\\pi r^2\\)", "\\[\nE = mc^2\n\\]\n\n", "\\(x\\)"]);
+ await act(() => host.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());
+ expect(editedText).toBe(text.replace("- [ ]", "- [x]"));
+ }
+ const { host } = await renderMath("- intro\n\n $$\n x^2\n $$");
+ expect(
+ [...host.querySelectorAll("[data-markdown-math]")].map((node) =>
+ node.getAttribute("data-markdown-copy"),
+ ),
+ ).toEqual(["\\[\nx^2\n\\]\n\n"]);
+ });
+});
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index 4517ffe5bf5..e8461925b36 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -110,11 +110,14 @@ import { parseComposerContextHref } from "@t3tools/shared/composerContextReferen
import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
import { AssistantCitationChip } from "./chat/AssistantCitationChip";
import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";
+import { mathKind } from "@t3tools/shared/markdownMath";
+import remarkMath from "remark-math";
import {
artifactTemplateFromHastProperties,
renderCodexInlineDirectivesAsMarkdown,
} from "@t3tools/shared/codexMarkdownDirectives";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
+import { MarkdownMath } from "./chat/MarkdownMath";
import {
resolveMarkdownMediaPreview,
type ExpandedImagePreview,
@@ -226,6 +229,8 @@ import { resolveLinkTarget } from "../browser/browserLinkTarget";
import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
interface ChatMarkdownProps {
+ /** Compact markdown transforms remove blocks before rendering inside a label. */
+ inline?: boolean;
text: string;
cwd: string | undefined;
threadRef?: ScopedThreadRef | undefined;
@@ -2354,6 +2359,7 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId
function useChatMarkdownState({
text,
+ inline = false,
cwd,
threadRef,
pullRequestPanelRef,
@@ -2371,7 +2377,7 @@ function useChatMarkdownState({
githubMedia = false,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
- const markdownRef = useRef<HTMLDivElement>(null);
+ const markdownRef = useRef<HTMLElement>(null);
const mediaRequestId = useRef(0);
// A preview opened from another thread or workspace never carries over.
const mediaScopeKey = [
@@ -2545,7 +2551,7 @@ function useChatMarkdownState({
if (isWindowsDrivePathHref(href)) return href;
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
};
- const handleCopy = (event: ReactClipboardEvent<HTMLDivElement>) => {
+ const handleCopy = (event: ReactClipboardEvent<HTMLElement>) => {
const selection = window.getSelection();
if (!selection || selection.isCollapsed || !event.clipboardData) return;
const payload = chatMarkdownClipboardPayload(selection);
@@ -2566,6 +2572,7 @@ function useChatMarkdownState({
// synchronously whether to intercept its `_blank`, and a subscription is what
// makes a persisted "app" apply once settings hydrate after launch.
const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
+ const mathEnabled = useClientSettings((settings) => settings.mathRenderingEnabled);
const resolveThreadPullRequest = (
href: string,
): (ThreadPullRequestKey & { readonly url: string }) | null => {
@@ -2779,6 +2786,8 @@ function useChatMarkdownState({
imageBaseDir,
workspaceMutationId,
inlineCodeFileLinkMetaByText,
+ inline,
+ mathEnabled,
isStreaming,
linkTargetPreference,
markdownFileLinkMetaByHref,
@@ -3196,9 +3205,18 @@ const CHAT_MARKDOWN_COMPONENTS = {
);
},
code: function MarkdownCode({ node, children, className, ...props }) {
- const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use(
- ChatMarkdownRendererContext,
- );
+ const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } =
+ use(ChatMarkdownRendererContext);
+ const math = mathEnabled ? mathKind(className) : null;
+ if (math) {
+ return (
+ <MarkdownMath
+ tex={nodeToPlainText(children)}
+ display={math === "display"}
+ focusable={!inline}
+ />
+ );
+ }
if (node?.properties?.dataInlineCode != null) {
const codeText = nodeToPlainText(children);
const fileLinkMeta =
@@ -3352,9 +3370,15 @@ const CHAT_MARKDOWN_COMPONENTS = {
return <MarkdownDetails open={detailsOpen}>{children}</MarkdownDetails>;
},
pre: function MarkdownPre({ node, children, ...props }) {
- const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use(
- ChatMarkdownRendererContext,
- );
+ const {
+ resolvedTheme,
+ diffThemeName,
+ expandMedia,
+ isStreaming,
+ onRunShellCommand,
+ inline,
+ mathEnabled,
+ } = use(ChatMarkdownRendererContext);
const text = use(ChatMarkdownTextContext);
const codeBlock = extractCodeBlock(children);
if (!codeBlock) {
@@ -3362,6 +3386,15 @@ const CHAT_MARKDOWN_COMPONENTS = {
}
const language = extractFenceLanguage(codeBlock.className);
+ if (
+ mathEnabled &&
+ language === "math" &&
+ (!isStreaming ||
+ mathKind(codeBlock.className) === "display" ||
+ isClosedCodeFence(node, text, codeBlock.code))
+ ) {
+ return <MarkdownMath tex={codeBlock.code} display focusable={!inline} />;
+ }
const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));
const highlightedCode = (
<RenderErrorBoundary
@@ -3419,6 +3452,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
function ChatMarkdown({
text,
className,
+ inline = false,
lineBreaks = false,
parseRawHtml = true,
extraRemarkPlugins = EMPTY_REMARK_PLUGINS,
@@ -3431,22 +3465,30 @@ function ChatMarkdown({
markdownUrlTransform,
localMediaPreview,
closeLocalMediaPreview,
- } = useChatMarkdownState({ text, ...props });
+ } = useChatMarkdownState({ text, inline, ...props });
const incrementalParsing =
props.isStreaming === true &&
extraRemarkPlugins.length === 0 &&
/(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text);
+ const Root = inline ? "span" : "div";
+ const bindMarkdownRef = (node: HTMLElement | null) => {
+ markdownRef.current = node;
+ };
const remarkPlugins = [
...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),
...extraRemarkPlugins,
...(incrementalParsing ? [createIncrementalMarkdownPlugin()] : []),
];
+ if (componentState.mathEnabled)
+ remarkPlugins.unshift([remarkMath, { singleDollarTextMath: true }]);
return (
- <div
- ref={markdownRef}
+ <Root
+ ref={bindMarkdownRef}
className={cn(
- "chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)] [overflow-wrap:anywhere] [word-break:break-word]",
+ "chat-markdown w-full min-w-0 [overflow-wrap:anywhere] [word-break:break-word]",
+ !inline &&
+ "text-sm leading-relaxed text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)]",
className,
)}
data-streaming={componentState.isStreaming ? "" : undefined}
@@ -3472,7 +3514,7 @@ function ChatMarkdown({
{localMediaPreview ? (
<ExpandedImageDialog preview={localMediaPreview} onClose={closeLocalMediaPreview} />
) : null}
- </div>
+ </Root>
);
}
diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx
new file mode 100644
index 00000000000..7f6af570a32
--- /dev/null
+++ b/apps/web/src/components/chat/MarkdownMath.tsx
@@ -0,0 +1,59 @@
+import { lazy, memo, Suspense } from "react";
+
+import { RenderErrorBoundary } from "../RenderErrorBoundary";
+
+const MathTypeset = lazy(() => import("./MathTypeset"));
+
+/**
+ * One formula from `remark-math`. Shows its TeX until KaTeX loads, and
+ * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying
+ * any part of a formula copies its whole TeX source.
+ */
+export const MarkdownMath = memo(function MarkdownMath(props: {
+ tex: string;
+ display: boolean;
+ focusable?: boolean;
+}) {
+ const tex = props.tex.trim();
+ const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`;
+ const fallback = <span className="whitespace-pre-wrap">{source}</span>;
+ return (
+ <span
+ className={
+ props.display
+ ? "chat-markdown-math-display my-[0.65rem] block in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible"
+ : "inline-block max-w-full align-middle whitespace-nowrap wrap-normal break-normal in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible"
+ }
+ data-markdown-math={props.display ? "display" : "inline"}
+ data-markdown-copy={props.display ? `${source}\n\n` : source}
+ role={props.focusable === false ? undefined : "group"}
+ aria-label={
+ props.focusable === false
+ ? undefined
+ : props.display
+ ? "Display equation"
+ : "Inline equation"
+ }
+ >
+ <span
+ className="block max-w-full overflow-x-auto overflow-y-hidden in-[.chat-markdown-table-container]:max-w-none in-[.chat-markdown-table-container]:overflow-visible px-0.5 py-0.75 focus-visible:outline-1 focus-visible:outline-solid focus-visible:-outline-offset-1 focus-visible:outline-border [&::-webkit-scrollbar]:h-2 [&::-webkit-scrollbar-thumb]:rounded [&::-webkit-scrollbar-thumb]:border [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-content"
+ tabIndex={props.focusable === false ? -1 : 0}
+ aria-label={
+ props.focusable === false
+ ? undefined
+ : props.display
+ ? "Scroll display equation"
+ : "Scroll inline equation"
+ }
+ >
+ <span className={props.display ? "inline-block w-max min-w-full" : "inline-block w-max"}>
+ <RenderErrorBoundary resetKeys={[tex]} fallback={fallback}>
+ <Suspense fallback={fallback}>
+ <MathTypeset tex={tex} display={props.display} fallback={fallback} />
+ </Suspense>
+ </RenderErrorBoundary>
+ </span>
+ </span>
+ </span>
+ );
+});
diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx
new file mode 100644
index 00000000000..9934c1e3393
--- /dev/null
+++ b/apps/web/src/components/chat/MathTypeset.tsx
@@ -0,0 +1,40 @@
+import katex from "katex";
+import "katex/dist/katex.min.css";
+import type { ReactNode } from "react";
+
+import { LRUCache } from "../../lib/lruCache";
+
+// Virtualized threads remount messages while scrolling; cached markup keeps
+// that from typesetting the same formulas again. "" records a parse error.
+const typesetCache = new LRUCache<string>(1000, 4 * 1024 * 1024);
+
+function typeset(tex: string, display: boolean): string {
+ const key = `${display ? "display" : "inline"}:${tex}`;
+ const cached = typesetCache.get(key);
+ if (cached !== null) return cached;
+ let html = "";
+ try {
+ html = katex.renderToString(tex, {
+ displayMode: display,
+ output: "htmlAndMathml",
+ throwOnError: true,
+ // No \href, \url, \htmlClass, or other commands that emit active HTML.
+ trust: false,
+ strict: "ignore",
+ maxSize: 20,
+ maxExpand: 1000,
+ });
+ } catch {
+ // Unfinished or unsupported TeX stays readable as its source.
+ }
+ typesetCache.set(key, html, (key.length + html.length) * 2);
+ return html;
+}
+
+/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */
+export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) {
+ const html = typeset(props.tex, props.display);
+ if (!html) return props.fallback;
+ // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes.
+ return <span dangerouslySetInnerHTML={{ __html: html }} />;
+}
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 79013513dc1..df1a612c1c1 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -18,7 +18,8 @@ import "~/index.css";
import { serverEnvironment } from "../../state/server";
import { PullRequestLinkPreview } from "../pullRequest/PullRequestLinkPreview";
import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "../ui/tooltip";
-import { MessagesTimeline } from "./MessagesTimeline";
+import { MessagesTimeline, remarkThoughtPreview } from "./MessagesTimeline";
+import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
import { readTimelinePosition } from "./timelineScrollAnchoring";
import { useComposerFocusState } from "./useComposerFocusState";
@@ -1480,3 +1481,22 @@ describe("MessagesTimeline send anchor", () => {
expect(onAnchorReady).not.toHaveBeenCalled();
});
});
+
+describe("compact reasoning math", () => {
+ it("keeps formulas while flattening compact reasoning previews", () => {
+ const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
+ remarkThoughtPreview("Reasoning")(tree);
+ expect(tree.children.map((node) => node.type)).toEqual([
+ "text",
+ "inlineMath",
+ "text",
+ "inlineMath",
+ ]);
+ expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
+ "Reasoning Use norm ",
+ "|x|",
+ " and ",
+ "x^2",
+ ]);
+ });
+});
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 4e1308dedfc..a3ea12f24ac 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -1,9 +1,7 @@
+import type { Root, RootContent } from "mdast";
import { ThreadFindTimelineContext } from "./ThreadFindProvider";
import { shallow } from "zustand/vanilla/shallow";
-import {
- remarkKeepWindowsPaths,
- shouldPreserveAssistantLineBreaks,
-} from "@t3tools/shared/markdownPipeline";
+import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
import { MarkdownFindContext, findRevealRef } from "./markdownFindContext";
import { useChatCanvas } from "./ChatCanvasContext";
import { WorkLogBlock, WorkLogButton, WorkLogDetails, WorkLogList, WorkLogRow } from "./WorkLog";
@@ -119,9 +117,6 @@ import {
} from "../../lib/diffRendering";
import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
-import type { Root, RootContent } from "mdast";
import { T3Wordmark } from "../T3Wordmark";
import { ThreadContextChip } from "../ThreadContextChip";
import {
@@ -302,7 +297,7 @@ import { SecretRequestCard } from "./SecretRequestCard";
import { TimelineSystemDivider } from "./TimelineSystemDivider";
import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
-import { SkillChipIcon, SkillInlineText } from "./SkillInlineText";
+import { SkillChipIcon } from "./SkillInlineText";
import * as DateTime from "effect/DateTime";
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
import { forwardWheelToTimeline } from "./timelineMinimapWheel";
@@ -3861,7 +3856,17 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "
/>
</span>
}
- label={<span className="line-clamp-4">{thoughtLine}</span>}
+ label={
+ <span className="line-clamp-4">
+ <ChatMarkdown
+ inline
+ text={thoughtLine}
+ cwd={ctx.markdownCwd}
+ parseRawHtml={false}
+ extraRemarkPlugins={[[remarkThoughtPreview, "Thought"]]}
+ />
+ </span>
+ }
wrapLabel
/>
) : null}
@@ -3881,15 +3886,13 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "
</span>
</span>
) : row.entry.itemType === "reasoning" ? (
- <ReactMarkdown
- remarkPlugins={[
- remarkGfm,
- remarkKeepWindowsPaths,
- [remarkThoughtPreview, row.active ? "Thinking" : "Thought"],
- ]}
- >
- {row.entry.detail ?? label}
- </ReactMarkdown>
+ <ChatMarkdown
+ inline
+ text={row.entry.detail ?? label}
+ cwd={ctx.markdownCwd}
+ parseRawHtml={false}
+ extraRemarkPlugins={[[remarkThoughtPreview, row.active ? "Thinking" : "Thought"]]}
+ />
) : threadLabel ? (
<ThreadReadLabel
label={threadLabel}
@@ -4688,8 +4691,14 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
</div>
</div>
{comment.text.length > 0 && (
- <div className="whitespace-pre-wrap wrap-break-word text-sm">
- <SkillInlineText text={comment.text} skills={ctx.skills} />
+ <div className="wrap-break-word text-sm">
+ <ChatMarkdown
+ text={comment.text}
+ cwd={ctx.markdownCwd}
+ skills={ctx.skills}
+ parseRawHtml={false}
+ lineBreaks
+ />
</div>
)}
{fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
@@ -5195,25 +5204,50 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
-function remarkThoughtPreview(fallback: string) {
+/** Compact reasoning keeps formulas while flattening other Markdown into label text. */
+export function remarkThoughtPreview(fallback: string) {
return (tree: Root) => {
- const plainText = (node: Root | RootContent): string => {
- if (node.type === "html" || node.type === "definition") return "";
- if ("alt" in node) return node.alt ?? "";
- if ("value" in node) return node.value;
- if ("children" in node) {
- const separator = ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(
- node.type,
- )
- ? " "
- : "";
- return node.children.map(plainText).join(separator);
- }
- return node.type === "break" ? " " : "";
+ const children: RootContent[] = [];
+ const append = (value: string) => {
+ const last = children.at(-1);
+ const text = value.replace(/\s+/g, " ");
+ if (last?.type === "text") last.value = (last.value + text).replace(/\s+/g, " ");
+ else children.push({ type: "text", value: text });
};
- tree.children = [
- { type: "text", value: plainText(tree).replace(/\s+/g, " ").trim() || fallback },
- ];
+ const visit = (node: Root | RootContent) => {
+ if (node.type === "html" || node.type === "definition") return;
+ if (node.type === "math" || node.type === "inlineMath") {
+ children.push({
+ type: "inlineMath",
+ value: node.value,
+ position: node.position,
+ data: {
+ hName: "code",
+ hProperties: { className: ["language-math", "math-inline"] },
+ hChildren: [{ type: "text", value: node.value }],
+ },
+ });
+ } else if ("alt" in node) append(node.alt ?? "");
+ else if ("value" in node) append(node.value);
+ else if ("children" in node) {
+ node.children.forEach((child, index) => {
+ if (
+ index &&
+ ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type)
+ )
+ append(" ");
+ visit(child);
+ });
+ } else if (node.type === "break") append(" ");
+ };
+ visit(tree);
+ const first = children[0];
+ const last = children.at(-1);
+ if (first?.type === "text") first.value = first.value.trimStart();
+ if (last?.type === "text") last.value = last.value.trimEnd();
+ tree.children = children.some((child) => child.type !== "text" || child.value)
+ ? children
+ : [{ type: "text", value: fallback }];
};
}
@@ -5512,18 +5546,18 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
className={cn(answerPreview ? "min-w-0" : "min-w-0 flex-1", "truncate", headingClass)}
>
{isReasoning && !expanded ? (
- <ReactMarkdown
- remarkPlugins={[
- remarkGfm,
- remarkKeepWindowsPaths,
+ <ChatMarkdown
+ inline
+ text={workEntry.detail ?? previewText}
+ cwd={ctx.markdownCwd}
+ parseRawHtml={false}
+ extraRemarkPlugins={[
[
remarkThoughtPreview,
workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought",
],
]}
- >
- {workEntry.detail ?? previewText}
- </ReactMarkdown>
+ />
) : threadLabel ? (
<ThreadReadLabel
label={threadLabel}
diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsx
index bdf2aad0aba..7df047815c5 100644
--- a/apps/web/src/components/chat/SkillInlineText.tsx
+++ b/apps/web/src/components/chat/SkillInlineText.tsx
@@ -5,7 +5,7 @@ import { matchInlineSkills, type InlineSkill } from "@t3tools/shared/inlineSkill
import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip";
import { ContextChip, ContextChipLabel } from "../ContextChip";
-export function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {
+function SkillInlineText(props: { text: string; skills: ReadonlyArray<InlineSkill> }) {
const nodes: ReactNode[] = [];
let cursor = 0;
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index b88dbbf5e97..ce336db9aee 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -543,6 +543,9 @@ export function useSettingsRestore(onRestored?: () => void) {
? ["Diff colors"]
: []),
...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? ["Chat width"] : []),
+ ...(settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled
+ ? ["Render math"]
+ : []),
...(settings.panelAnimationDurationMs !== DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs
? ["Panel animations"]
: []),
@@ -717,6 +720,7 @@ export function useSettingsRestore(onRestored?: () => void) {
appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast,
diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme,
chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth,
+ mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled,
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode,
inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled,
@@ -1374,6 +1378,31 @@ export function AppearanceSettingsPanel() {
</div>
}
/>
+ <SettingsRow
+ {...searchableSetting("math-rendering")}
+ description="Typeset LaTeX math, such as $x^2$ or \[x^2\], in messages and Markdown previews. The composer keeps TeX source editable."
+ resetAction={
+ settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled ? (
+ <SettingResetButton
+ label="math rendering"
+ onClick={() =>
+ updateSettings({
+ mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled,
+ })
+ }
+ />
+ ) : null
+ }
+ control={
+ <Switch
+ checked={settings.mathRenderingEnabled}
+ onCheckedChange={(checked) =>
+ updateSettings({ mathRenderingEnabled: Boolean(checked) })
+ }
+ aria-label="Render math"
+ />
+ }
+ />
</SettingsSection>
<SettingsSection id="motion" title="Motion">
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 960ae60cea8..cd3cb34b5d2 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -238,6 +238,12 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/appearance",
searchTerms: ["wide full width column layout messages composer monitor"],
},
+ {
+ id: "math-rendering",
+ title: "Render math",
+ to: "/settings/appearance",
+ searchTerms: ["latex tex katex equations formulas markdown"],
+ },
{
id: "panel-animations",
title: "Panel animations",
diff --git a/apps/web/src/composer-rich-text-doc.test.ts b/apps/web/src/composer-rich-text-doc.test.ts
index 0a0ae5d732f..9b0cbf5cf38 100644
--- a/apps/web/src/composer-rich-text-doc.test.ts
+++ b/apps/web/src/composer-rich-text-doc.test.ts
@@ -86,6 +86,54 @@ function roundTrip(value: string) {
return serializeEditorDoc(doc);
}
+describe("editable math source", () => {
+ it.each([
+ "Area $x_i^2$ after",
+ "before \\(\\frac{1}{2}\\) after",
+ "before $$x^2$$ after",
+ "\\[\nx = 1\ny = 2\n\\]",
+ "\\[\\text{use $browser then @README.md and **literal**}\\]",
+ "```math\nx_i + y_i\n```",
+ "- **use** $x_i$ then @README.md",
+ "**$x_i$** and **A $x_i$ B**",
+ "| Name | Formula |\n| --- | --- |\n| Norm | $|x|$ |",
+ "| Name | Formula |\n| --- | --- |\n| Norm | \\(\\|x\\|\\) |",
+ ])("keeps TeX editable and round trips its source: %s", (source) => {
+ const map = roundTrip(source);
+ expect(map.value).toBe(source);
+ expect(map.runs.some((run) => run.nodeName === "composer-math")).toBe(false);
+ const doc = schema.nodeFromJSON(
+ buildDocJson(source, (name) => ({ label: name, description: null })),
+ );
+ expect(serializeSelection(doc, 1, doc.content.size - 1)).toBe(source);
+ });
+
+ it("edits a command character directly without replacing a formula node", () => {
+ const source = "before \\(\\frac{a}{b}\\) after";
+ const doc = schema.nodeFromJSON(
+ buildDocJson(source, (name) => ({ label: name, description: null })),
+ );
+ const map = serializeEditorDoc(doc);
+ const offset = source.indexOf("{a}") + 1;
+ const position = flatToPm(map, offset);
+ const state = EditorState.create({ doc });
+ const next = state.apply(state.tr.insertText("c", position, position + 1));
+ expect(serializeEditorDoc(next.doc).value).toBe(source.replace("{a}", "{c}"));
+ });
+ it("preserves formula source as text when styling is disabled", () => {
+ const source =
+ "\\[\n\\text{use $browser, @README.md and [file](t3-context://v1/file/ctx_1)}\n\\]";
+ const doc = plainSchema.nodeFromJSON(
+ buildDocJson(source, (name) => ({ label: name, description: null }), { styling: false }),
+ );
+ const map = serializeEditorDoc(doc);
+ expect(map.value).toBe(source);
+ expect(map.runs.some((run) => run.kind === "token")).toBe(false);
+ });
+});
+
+// Plain mode: the same engine with the mark extensions off. Markers stay
+// literal characters and task lines stay paragraphs.
const plainSchema = getSchemaByResolvedExtensions(
resolveExtensions([
StarterKit.configure({
diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.ts
index 2c71de4a150..af7fd8c566d 100644
--- a/apps/web/src/composer-rich-text-doc.ts
+++ b/apps/web/src/composer-rich-text-doc.ts
@@ -28,6 +28,7 @@ import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
import { nextOrderedMarkerText } from "~/composer-list-continuation";
import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
import { collectInlineContextIds } from "~/lib/composerContextReferences";
+import { markdownMathRanges } from "@t3tools/shared/markdownMath";
export type SkillMeta = { label: string; description: string | null };
@@ -541,12 +542,32 @@ export function buildTiptapContent(
const atoms: InlineJson[] = [];
const atomSources: string[] = [];
const literal = value.slice(0, options?.literalLength ?? 0);
- const text = splitPromptIntoComposerSegments(value.slice(literal.length))
- .map((segment) => {
- if (segment.type === "text") return segment.text;
- atoms.push(atomJsonForSegment(segment, skillLabelFor));
- atomSources.push(segment.source);
- return sentinel;
+ const remainder = value.slice(literal.length);
+ const formulas = markdownMathRanges(remainder);
+ let offset = 0;
+ const chunks: Array<{ text: string } | { source: string }> = [];
+ for (const formula of formulas) {
+ chunks.push({ text: remainder.slice(offset, formula.start) }, { source: formula.source });
+ offset = formula.end;
+ }
+ chunks.push({ text: remainder.slice(offset) });
+ // Math stays editable source. Shield its commands and Markdown-like markers
+ // from styling and context-chip parsing, then restore ordinary text nodes.
+ const text = chunks
+ .map((chunk) => {
+ if ("source" in chunk) {
+ atoms.push(textJsonForSpan(chunk.source, []));
+ atomSources.push(chunk.source);
+ return sentinel;
+ }
+ return splitPromptIntoComposerSegments(chunk.text)
+ .map((segment) => {
+ if (segment.type === "text") return segment.text;
+ atoms.push(atomJsonForSegment(segment, skillLabelFor));
+ atomSources.push(segment.source);
+ return sentinel;
+ })
+ .join("");
})
.join("");
let atomIndex = 0;
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 01346413a07..76ad4037306 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -1801,6 +1801,10 @@ code {
margin: 0.65rem 0;
}
+.chat-markdown-math-display .katex-display {
+ margin: 0;
+}
+
:is(.chat-markdown, .composer-tiptap) h1,
:is(.chat-markdown, .composer-tiptap) h2,
:is(.chat-markdown, .composer-tiptap) h3,
@@ -2101,6 +2105,12 @@ code {
overflow-wrap: anywhere;
}
+/* Formula cells keep their natural width and scroll with the table. */
+.chat-markdown .chat-markdown-table-container td:has([data-markdown-math]) {
+ max-width: none;
+ overflow: visible;
+}
+
:root {
--diff-addition: var(--success);
--diff-deletion: var(--destructive);
diff --git a/apps/web/src/lib/assistantTextSelection.ts b/apps/web/src/lib/assistantTextSelection.ts
index ecc9a0ab0b8..0ae02f8be4b 100644
--- a/apps/web/src/lib/assistantTextSelection.ts
+++ b/apps/web/src/lib/assistantTextSelection.ts
@@ -1,5 +1,7 @@
import { ASSISTANT_CITATION_CONTEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
+import { mathWrapperOf } from "../markdown-clipboard";
+
export type AssistantTextSelector = {
readonly text: string;
readonly start: number;
@@ -122,7 +124,10 @@ export function findAssistantCitationText(
return match ?? (quoteCount === 1 ? onlyQuote : null);
}
-type TextChunk = { node: Text; start: number; end: number };
+/** A text node, or a whole rendered formula standing for its TeX. */
+type TextChunk = { node: Text | Element; start: number; end: number };
+
+const isText = (node: Node): node is Text => node.nodeType === 3;
function readAssistantText(root: HTMLElement) {
const parts: string[] = [];
@@ -130,18 +135,21 @@ function readAssistantText(root: HTMLElement) {
let length = 0;
let separator = false;
+ const append = (node: Text | Element, text: string) => {
+ if (separator && length > 0) {
+ parts.push("\n");
+ length += 1;
+ }
+ separator = false;
+ chunks.push({ node, start: length, end: length + text.length });
+ parts.push(text);
+ length += text.length;
+ };
+
const visit = (node: Node) => {
if (node.nodeType === 3) {
const text = node as Text;
- if (text.length === 0) return;
- if (separator && length > 0) {
- parts.push("\n");
- length += 1;
- }
- separator = false;
- chunks.push({ node: text, start: length, end: length + text.length });
- parts.push(text.data);
- length += text.length;
+ if (text.length > 0) append(text, text.data);
return;
}
if (node.nodeType !== 1) return;
@@ -149,7 +157,11 @@ function readAssistantText(root: HTMLElement) {
if (element.matches(EXCLUDED_SELECTOR)) return;
const block = element.matches(BLOCK_SELECTOR);
if (block || element.tagName === "BR") separator = true;
- for (const child of element.childNodes) visit(child);
+ if (element.matches("[data-markdown-math]")) {
+ append(element, element.getAttribute("data-markdown-copy")?.trim() ?? "");
+ } else {
+ for (const child of element.childNodes) visit(child);
+ }
if (block) separator = true;
};
@@ -176,7 +188,7 @@ function isUsableRange(root: HTMLElement, range: Range): boolean {
}
function isUnselectable(text: Text): boolean {
- const element = text.parentElement;
+ const element = mathWrapperOf(text.parentElement) ?? text.parentElement;
const view = element?.ownerDocument?.defaultView;
return !!element && !!view && view.getComputedStyle(element).userSelect === "none";
}
@@ -216,8 +228,13 @@ export function captureAssistantTextSelection(
// Paragraph selection can end at the next block's offset 0 or a parent
// boundary. Validate the text actually selected, not that empty endpoint.
- range.setStart(first, first === range.startContainer ? range.startOffset : 0);
- range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
+ // An endpoint inside a formula's glyphs takes in the whole formula.
+ const startFormula = mathWrapperOf(first.parentElement);
+ const endFormula = mathWrapperOf(last.parentElement);
+ if (startFormula) range.setStartBefore(startFormula);
+ else range.setStart(first, first === range.startContainer ? range.startOffset : 0);
+ if (endFormula) range.setEndAfter(endFormula);
+ else range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
if (!isUsableRange(source, range)) return null;
const stream = readAssistantText(source);
@@ -226,7 +243,7 @@ export function captureAssistantTextSelection(
for (const chunk of stream.chunks) {
if (!range.intersectsNode(chunk.node)) continue;
const start = range.startContainer === chunk.node ? range.startOffset : 0;
- const end = range.endContainer === chunk.node ? range.endOffset : chunk.node.length;
+ const end = range.endContainer === chunk.node ? range.endOffset : chunk.end - chunk.start;
if (start === end) continue;
rawStart ??= chunk.start + start;
rawEnd = chunk.start + end;
@@ -268,7 +285,10 @@ export function resolveAssistantCitationRange(
if (first === undefined || last === undefined) return null;
const range = root.ownerDocument.createRange();
- range.setStart(first.node, Math.max(0, start - first.start));
- range.setEnd(last.node, Math.min(last.node.length, end - last.start));
+ // A match that touches a formula covers the formula as rendered.
+ if (isText(first.node)) range.setStart(first.node, Math.max(0, start - first.start));
+ else range.setStartBefore(first.node);
+ if (isText(last.node)) range.setEnd(last.node, Math.min(last.node.length, end - last.start));
+ else range.setEndAfter(last.node);
return isUsableRange(root, range) ? range : null;
}
diff --git a/apps/web/src/markdown-clipboard.math.browser.test.ts b/apps/web/src/markdown-clipboard.math.browser.test.ts
new file mode 100644
index 00000000000..66ac988b6cc
--- /dev/null
+++ b/apps/web/src/markdown-clipboard.math.browser.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { chatMarkdownClipboardPayload } from "./markdown-clipboard";
+
+function select(start: Node, startOffset: number, end: Node, endOffset: number) {
+ const range = document.createRange();
+ range.setStart(start, startOffset);
+ range.setEnd(end, endOffset);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ return selection;
+}
+
+describe("copying rendered math", () => {
+ it("copies a formula's TeX whether the selection spans it or starts inside it", () => {
+ document.body.innerHTML = `<div class="chat-markdown"><p>Area <span data-markdown-math="" data-markdown-copy="$\\pi r^2$"><span class="katex"><span class="katex-mathml">πr2</span><span class="katex-html" aria-hidden="true">πr2</span></span></span> grows.</p></div>`;
+ const paragraph = document.querySelector("p")!;
+ const glyphs = document.querySelector(".katex-mathml")!.firstChild!;
+
+ expect(
+ chatMarkdownClipboardPayload(select(paragraph.firstChild!, 0, paragraph.lastChild!, 7))?.text,
+ ).toBe("Area $\\pi r^2$ grows.");
+ expect(chatMarkdownClipboardPayload(select(glyphs, 0, glyphs, 1))?.text).toBe("$\\pi r^2$");
+ });
+});
diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts
index 013284bec78..698aaf2952c 100644
--- a/apps/web/src/markdown-clipboard.ts
+++ b/apps/web/src/markdown-clipboard.ts
@@ -324,6 +324,24 @@ export function serializeTableElementToMarkdown(table: Element): string {
return serializeTable(table).trim();
}
+// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops
+// the attribute from authored HTML.
+const MATH_SELECTOR = "[data-markdown-math]";
+
+export function mathWrapperOf(element: Element | null): Element | null {
+ return element?.closest(MATH_SELECTOR) ?? null;
+}
+
+/** A cell's text, with each formula as its TeX. */
+function csvCellText(cell: Element): string {
+ if (!cell.querySelector(MATH_SELECTOR)) return cell.textContent ?? "";
+ const copy = cell.cloneNode(true) as Element;
+ for (const wrapper of copy.querySelectorAll(MATH_SELECTOR)) {
+ wrapper.replaceWith(wrapper.getAttribute("data-markdown-copy")?.trim() ?? "");
+ }
+ return copy.textContent ?? "";
+}
+
function csvCell(value: string): string {
const normalized = value.replace(/\s+/g, " ").trim();
return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
@@ -337,12 +355,24 @@ export function serializeTableElementToCsv(table: Element): string {
(cell) => cell.tagName === "TH" || cell.tagName === "TD",
);
if (cells.length === 0) continue;
- lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
+ lines.push(cells.map((cell) => csvCell(csvCellText(cell))).join(","));
}
return lines.join("\n");
}
+function mathSourceElement(wrapper: Element): Element {
+ const code = document.createElement("code");
+ code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
+ if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
+ const pre = document.createElement("pre");
+ pre.append(code);
+ return pre;
+}
+
function sanitizedHtmlFrom(container: Element): string {
+ for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
+ wrapper.replaceWith(mathSourceElement(wrapper));
+ }
for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
if (
node.classList.contains("chat-markdown-file-link") ||
@@ -371,6 +401,13 @@ export function chatMarkdownClipboardPayload(
const ancestor = range.commonAncestorContainer;
const ancestorElement =
ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
+ // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
+ const math = mathWrapperOf(ancestorElement);
+ if (math) {
+ texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
+ htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
+ continue;
+ }
if (ancestorElement?.closest("pre")) {
const text = range.toString();
if (text) {
diff --git a/docs/user/appearance.md b/docs/user/appearance.md
index ec02a28ed78..49d8e02d79a 100644
--- a/docs/user/appearance.md
+++ b/docs/user/appearance.md
@@ -29,6 +29,18 @@ The controls retreat as the composer docks after you send the first message.
Turn on **Composer context** to keep those controls visible after the thread starts. This preference
applies to the web and desktop clients.
+## Math
+
+Turn on **Render math** in **Settings → Appearance** to typeset LaTeX in messages and Markdown
+previews on web, desktop, and mobile. It reads `$…$`, `$$…$$`, `\(…\)`, and `\[…\]`, outside of code.
+Fenced `math` blocks also render. Formulas work in tables, including absolute-value bars.
+Dollar amounts such as `$5 and $10` stay text; write `\$` to keep any other dollar sign literal.
+Wide formulas scroll horizontally while the surrounding text wraps. Copying a formula or
+exporting a table preserves the TeX.
+
+The composer keeps TeX source editable, including when rich text is enabled. The Render math
+preference is saved separately on each device.
+
## Motion
The main sidebar, right panel, and terminal drawer open and close immediately by default. Move the
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 562bc7a54a1..c92b3a6a8e1 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -150,6 +150,15 @@ describe("storage cleanup settings", () => {
});
describe("ClientSettings rich text composer", () => {
+ it("keeps math opt-in and preserves its preference through patches and persistence", () => {
+ expect(decodeClientSettings({}).mathRenderingEnabled).toBe(false);
+ for (const mathRenderingEnabled of [true, false]) {
+ const preference = { mathRenderingEnabled };
+ expect(decodeClientSettingsPatch(preference)).toEqual(preference);
+ expect(encodeClientSettings(decodeClientSettings(preference))).toMatchObject(preference);
+ }
+ expect(() => decodeClientSettingsPatch({ mathRenderingEnabled: "yes" })).toThrow();
+ });
it("enables rich text for new and existing settings without a saved preference", () => {
expect(decodeClientSettings({}).composerRichTextEnabled).toBe(true);
expect(decodeClientSettings({ sendShortcut: "mod-enter" }).composerRichTextEnabled).toBe(true);
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 61ca1140504..3de6188d41c 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -479,6 +479,9 @@ export const ClientSettingsSchema = Schema.Struct({
snapShotFlash: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
snapShotAnimations: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ // Opt-in TeX typesetting in rendered Markdown. Off keeps math parsing and
+ // KaTeX out of the render path entirely.
+ mathRenderingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
@@ -1648,5 +1651,6 @@ export const ClientSettingsPatch = Schema.Struct({
snapShotFlash: Schema.optionalKey(Schema.Boolean),
snapShotAnimations: Schema.optionalKey(Schema.Boolean),
wordWrap: Schema.optionalKey(Schema.Boolean),
+ mathRenderingEnabled: Schema.optionalKey(Schema.Boolean),
});
export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 22f240aa163..b90af1a9b2c 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -490,6 +490,10 @@
"./PtyAdapter": {
"types": "./src/PtyAdapter.ts",
"import": "./src/PtyAdapter.ts"
+ },
+ "./markdownMath": {
+ "types": "./src/markdownMath.ts",
+ "import": "./src/markdownMath.ts"
}
},
"scripts": {
@@ -503,12 +507,14 @@
"effect": "catalog:",
"jose": "catalog:",
"mdast-util-directive": "catalog:",
+ "mdast-util-to-hast": "^13.2.1",
"micromark-extension-directive": "catalog:",
"micromark-util-character": "catalog:",
"rehype-raw": "catalog:",
"rehype-sanitize": "catalog:",
"remark-breaks": "catalog:",
"remark-gfm": "catalog:",
+ "remark-math": "6.0.0",
"remark-parse": "catalog:",
"remark-rehype": "catalog:",
"unified": "catalog:",
@@ -517,6 +523,7 @@
"devDependencies": {
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
+ "@types/mdast": "^4.0.4",
"@types/node": "catalog:",
"micromark-util-types": "catalog:",
"vite-plus": "catalog:"
diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts
index 1025fc77041..20700b06e60 100644
--- a/packages/shared/src/composerInlineTokens.test.ts
+++ b/packages/shared/src/composerInlineTokens.test.ts
@@ -210,4 +210,11 @@ describe("collectComposerInlineTokens", () => {
expect(collectComposerInlineTokens(" [[".repeat(40_000))).toEqual([]);
expect(performance.now() - started).toBeLessThan(1_000);
});
+
+ it("keeps skill and mention sources inside TeX out of the context chip list", () => {
+ const source = "\\[\\text{use $browser and @README.md here}\\] then $real-skill ";
+ expect(collectComposerInlineTokens(source).map((token) => token.source)).toEqual([
+ "$real-skill",
+ ]);
+ });
});
diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts
index d54b39317e8..60624625bc7 100644
--- a/packages/shared/src/composerInlineTokens.ts
+++ b/packages/shared/src/composerInlineTokens.ts
@@ -1,3 +1,5 @@
+import { markdownMathRanges } from "./markdownMath.ts";
+
export type ComposerInlineToken =
| {
readonly type: "mention";
@@ -134,5 +136,12 @@ export function collectComposerInlineTokens(
}
}
- return [...matches].sort((left, right) => left.start - right.start);
+ // TeX can contain literal skill and file tokens, especially inside \text{}.
+ // They remain formula source rather than becoming composer context chips.
+ const math = matches.length > 0 ? markdownMathRanges(text) : [];
+ return matches
+ .filter(
+ (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start),
+ )
+ .sort((left, right) => left.start - right.start);
}
diff --git a/packages/shared/src/markdownMath.test.ts b/packages/shared/src/markdownMath.test.ts
new file mode 100644
index 00000000000..358f69b3c5d
--- /dev/null
+++ b/packages/shared/src/markdownMath.test.ts
@@ -0,0 +1,386 @@
+import type { Nodes } from "mdast";
+import { describe, expect, it } from "vite-plus/test";
+
+import { mathKind } from "./markdownMath.ts";
+import { markdownMathRanges, parseMarkdownWithMath } from "./markdownMath.ts";
+
+const parse = parseMarkdownWithMath;
+
+function collect(node: Nodes, out: Nodes[] = []): Nodes[] {
+ out.push(node);
+ if ("children" in node) for (const child of node.children) collect(child, out);
+ return out;
+}
+
+/** Formulas as `[kind, tex]`, in document order. */
+function formulas(markdown: string) {
+ return collect(parse(markdown)).flatMap((node) => {
+ if (node.type === "math") return [["display", node.value]];
+ if (node.type !== "inlineMath") return [];
+ const className = node.data?.hProperties?.className;
+ return [[mathKind(Array.isArray(className) ? className.join(" ") : undefined), node.value]];
+ });
+}
+
+function text(markdown: string) {
+ return collect(parse(markdown))
+ .flatMap((node) => (node.type === "text" ? [node.value] : []))
+ .join("");
+}
+
+describe("chat math parsing", () => {
+ it("keeps GFM autolink destinations intact while restoring literal dollars", () => {
+ const source = "Query www.example.com/?$select=id and $x$.";
+ const link = collect(parse(source)).find((node) => node.type === "link");
+ expect(link).toMatchObject({ url: "http://www.example.com/?$select=id" });
+ expect(formulas(source)).toEqual([["inline", "x"]]);
+ });
+
+ it.each(["&#57344;", "&#xE000;", "&#xe000;"])(
+ "preserves decoded private-use reference %s",
+ (reference) => {
+ const source = `${reference} [${reference}](https://example.com/?q=${reference}) $x$`;
+ const nodes = collect(parse(source));
+ expect(
+ nodes
+ .filter((node) => node.type === "text")
+ .map((node) => node.value)
+ .join(""),
+ ).toBe("\uE000 \uE000 ");
+ expect(nodes.find((node) => node.type === "link")).toMatchObject({
+ url: "https://example.com/?q=\uE000",
+ });
+ expect(formulas(source)).toEqual([["inline", "x"]]);
+ },
+ );
+
+ it.each(["\\(x\\)", "\\[x\\]", "$x$", "$$x$$"])(
+ "preserves indented code containing %s",
+ (formula) => {
+ const source = ` ${formula}`;
+ expect(collect(parse(source)).find((node) => node.type === "code")).toMatchObject({
+ value: formula,
+ });
+ expect(markdownMathRanges(source)).toEqual([]);
+ },
+ );
+
+ it("parses formulas without reserving private-use characters", () => {
+ const characters = Array.from({ length: 6400 }, (_, index) =>
+ String.fromCharCode(0xe000 + index),
+ ).join("");
+ const source = "$x$ " + characters;
+ expect(formulas(source)).toEqual([["inline", "x"]]);
+ expect(text(source)).toBe(" " + characters);
+ });
+
+ it("only exposes closed explicit math fences to editors and native rendering", () => {
+ expect(markdownMathRanges("```math\nx^2")).toEqual([]);
+ expect(markdownMathRanges("```math\nx^2\n```")[0]?.tex).toBe("x^2");
+ expect(markdownMathRanges("> ```math\n> x^2\n> ```")[0]?.tex).toBe("x^2");
+ });
+ it("reads the four delimiters models emit", () => {
+ expect(formulas("Inline $x^2$ and \\(y_1\\), display $$a+b$$ and \\[c\\].")).toEqual([
+ ["inline", "x^2"],
+ ["inline", "y_1"],
+ ["display", "a+b"],
+ ["display", "c"],
+ ]);
+ });
+
+ it("reads display blocks on their own lines", () => {
+ expect(formulas("$$\n\\frac{a}{b}\n$$")).toEqual([["display", "\\frac{a}{b}"]]);
+ expect(
+ formulas("Where\n\\[\n\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}\n\\]\nholds."),
+ ).toEqual([["display", "\\begin{aligned} a &= b \\\\ c &= d \\end{aligned}"]]);
+ });
+
+ it.each([" is the first formula.", ", followed by prose.", " \tthen more text."])(
+ "keeps text after a same-line formula separate from later display math: %s",
+ (trailing) => {
+ const source = `$$a$$${trailing}\nSome prose.\n$$\nb\n$$`;
+ const nodes = collect(parse(source));
+ expect(
+ nodes.filter((node) => node.type === "inlineMath" || node.type === "math"),
+ ).toMatchObject([
+ { type: "inlineMath", value: "a" },
+ { type: "math", value: "b" },
+ ]);
+ expect(text(source)).toContain(`${trailing}\nSome prose.`);
+ expect(markdownMathRanges(source).map((formula) => formula.source)).toEqual([
+ "$$a$$",
+ "$$\nb\n$$",
+ ]);
+ },
+ );
+
+ it("keeps block syntax inside display blocks as TeX", () => {
+ expect(formulas("\\[\nx\n- y\n# z\n\\]\nafter")).toEqual([["display", "x\n- y\n# z"]]);
+ expect(formulas("> $$\n> x\n> $$")).toEqual([["display", "x"]]);
+ // Same-line content is not a fence; it stays one formula.
+ expect(formulas("$$x^2\n+y^2$$")).toEqual([["display", "x^2\n+y^2"]]);
+ expect(text("$$E=mc^2")).toBe("$$E=mc^2");
+ });
+
+ it("keeps prices, shell variables, and skill tokens as prose", () => {
+ for (const prose of [
+ "It costs $5 and $10.",
+ "Budget $5-$10 per seat, or $20,000-$30,000 a year.",
+ "Plans are $5/$10 monthly.",
+ "Run $browser then $deploy on it.",
+ "Set $HOME before running.",
+ ]) {
+ expect(formulas(prose), prose).toEqual([]);
+ expect(text(prose), prose).toBe(prose);
+ }
+ });
+
+ it("keeps prices as prose when math follows on the same line", () => {
+ for (const price of ["$5-$10", "$5 and $10", "$5/$10", "$20,000-$30,000"]) {
+ const source = `Price ${price} stays literal. The formula is $x_i$ and $5$.`;
+ expect(formulas(source)).toEqual([
+ ["inline", "x_i"],
+ ["inline", "5"],
+ ]);
+ expect(text(source)).toBe(`Price ${price} stays literal. The formula is and .`);
+ }
+ });
+
+ it("leaves code, escapes, links, and citations alone", () => {
+ for (const [markdown, rendered] of [
+ ["Use `$x$` in code.", "Use in code."],
+ ["It costs $5 and $10, and `$HOME` stays code.", "It costs $5 and $10, and stays code."],
+ ["Export $PATH, then `$HOME`.", "Export $PATH, then ."],
+ ["\\(a `\\)` b", "(a b"],
+ [
+ "Set $TOKEN, then open [users](https://graph.microsoft.com/v1.0/users?$select=id).",
+ "Set $TOKEN, then open users.",
+ ],
+ [
+ "Set $TOKEN, then open <https://graph.microsoft.com/v1.0/users?$select=id>.",
+ "Set $TOKEN, then open https://graph.microsoft.com/v1.0/users?$select=id.",
+ ],
+ ["```\n$x$ \\(y\\)\n```", ""],
+ ["Escaped \\$x\\$ stays.", "Escaped $x$ stays."],
+ ["Escaped \\\\(x\\\\) stays.", "Escaped \\(x\\) stays."],
+ ["See [docs](https://example.com/\\(a\\)) here.", "See docs here."],
+ ["As shown in \\[1\\] and \\[2, 3\\].", "As shown in [1] and [2, 3]."],
+ ] as const) {
+ expect(formulas(markdown), markdown).toEqual([]);
+ expect(text(markdown), markdown).toBe(rendered);
+ }
+ });
+
+ it("starts a formula right after an escaped dollar", () => {
+ expect(formulas("Pay \\$$x$ now.")).toEqual([["inline", "x"]]);
+ });
+
+ it.each([
+ ["$a`$HOME`", "$HOME"],
+ ["\\(a`\\)`", "\\)"],
+ ["\\(a\\alpha`\\)`", "\\)"],
+ ["text \\[a`\\]`", "\\]"],
+ ])("preserves an adjacent code span in %s", (source, code) => {
+ expect(formulas(source)).toEqual([]);
+ expect(collect(parse(source)).find((node) => node.type === "inlineCode")).toMatchObject({
+ value: code,
+ });
+ });
+
+ it.each([
+ ["$$ $$", ""],
+ ["$$ $$", ""],
+ ["$$\n$\n$$", "$"],
+ ["$$\n$$\n", ""],
+ ])("parses display math without empty content tokens in %j", (source, tex) => {
+ expect(formulas(source)).toEqual([["display", tex]]);
+ });
+
+ it.each([1, 2, 3, 4])("respects %i backslashes before a display fence", (count) => {
+ const prefix = "a+" + "\\".repeat(count);
+ for (const opening of ["$$", "$$\n"]) {
+ const source = `${opening}${prefix}$$\nb\n$$`;
+ expect(formulas(source)).toEqual([["display", count % 2 === 1 ? `${prefix}$$\nb` : prefix]]);
+ expect(markdownMathRanges(source)[0]?.source).toBe(
+ count % 2 === 1 ? source : `${opening}${prefix}$$`,
+ );
+ }
+ });
+
+ it("keeps TeX escapes inside formulas", () => {
+ expect(formulas("Cost $a\\$b$ and \\(\\left(x\\right)\\).")).toEqual([
+ ["inline", "a\\$b"],
+ ["inline", "\\left(x\\right)"],
+ ]);
+ });
+
+ it("keeps source offsets of the original message", () => {
+ const markdown = "- [ ] check \\(x\\)\n- [x] then $y$";
+ const offsets = collect(parse(markdown)).flatMap((node) =>
+ node.type === "inlineMath" || node.type === "listItem"
+ ? [[node.type, node.position?.start.offset]]
+ : [],
+ );
+ expect(offsets).toEqual([
+ ["listItem", 0],
+ ["inlineMath", markdown.indexOf("\\(")],
+ ["listItem", markdown.indexOf("- [x]")],
+ ["inlineMath", markdown.indexOf("$y$")],
+ ]);
+ });
+
+ it.each(["\n", "\r\n", "\r"])("keeps authored lines and UTF-16 offsets with %j", (eol) => {
+ const source = `😀 \\(x${eol}+y\\)${eol}${eol}- [ ] check $z$`;
+ const nodes = collect(parse(source));
+ const formula = nodes.find(
+ (node) => node.type === "inlineMath" && node.value === "x" + eol + "+y",
+ );
+ expect(formula?.position?.start).toEqual({ line: 1, column: 4, offset: 3 });
+ expect(formula?.position?.end).toEqual({
+ line: 2,
+ column: 5,
+ offset: source.indexOf(eol + eol),
+ });
+ expect(nodes.find((node) => node.type === "listItem")?.position?.start).toEqual({
+ line: 4,
+ column: 1,
+ offset: source.indexOf("- [ ]"),
+ });
+ });
+
+ it("shows unfinished formulas as text while a response streams", () => {
+ const message = "Energy \\(E = mc^2\\) and $$\\sum_i x_i$$ done.";
+ for (let end = 0; end <= message.length; end++) {
+ expect(() => parse(message.slice(0, end))).not.toThrow();
+ }
+ expect(text("Energy \\(E = mc")).toBe("Energy (E = mc");
+ expect(formulas("$$\nx^2")).toEqual([]);
+ expect(formulas("\\[\nx^2\n- y")).toEqual([]);
+ expect(formulas(message)).toEqual([
+ ["inline", "E = mc^2"],
+ ["display", "\\sum_i x_i"],
+ ]);
+ });
+});
+
+describe("math in GFM tables", () => {
+ it("renders math in link labels while retaining dollars in their destinations", () => {
+ const row = "| [norm $|x|$](https://example.com/$path) | y$ |";
+ for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
+ const tree = parse(source);
+ const table = tree.children[0];
+ expect(table?.type).toBe("table");
+ if (table?.type !== "table") throw new Error("Missing table");
+ expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
+ expect(markdownMathRanges(source, tree).map((range) => range.tex)).toEqual(["|x|"]);
+ expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
+ url: "https://example.com/$path",
+ });
+ }
+ });
+
+ it.each([
+ "[a](https://example.com/$x)",
+ '[a](https://example.com "title $x")',
+ "<https://example.com/$x>",
+ "`$x`",
+ '<span title="$x">a</span>',
+ ])("preserves table separators after literal dollars in %s", (literal) => {
+ const row = `| ${literal} | y$ |`;
+ for (const source of [`${row}\n| --- | --- |`, `| First | Second |\n| --- | --- |\n${row}`]) {
+ const tree = parse(source);
+ const table = tree.children[0];
+ expect(table?.type).toBe("table");
+ if (table?.type !== "table") throw new Error("Missing table");
+ expect(table.children.every((entry) => entry.children.length === 2)).toBe(true);
+ expect(markdownMathRanges(source, tree)).toEqual([]);
+ if (literal.startsWith("[a](https://example.com/$x)")) {
+ expect(collect(tree).find((node) => node.type === "link")).toMatchObject({
+ url: "https://example.com/$x",
+ });
+ }
+ }
+ });
+
+ it("retains multiline math after a prose pipe outside tables", () => {
+ const source = "a | b: \\(x\n+y\\)";
+ expect(formulas(source)).toEqual([["inline", "x\n+y"]]);
+ expect(markdownMathRanges(source)).toEqual([
+ expect.objectContaining({ source: "\\(x\n+y\\)", inTable: false }),
+ ]);
+ });
+ it.each(["\\(", "\\["])("keeps table rows intact when %s closes in a later row", (opener) => {
+ const closer = opener === "\\(" ? "\\)" : "\\]";
+ const source = `| Name | Value |\n| --- | --- |\n| first | ${opener}x |\n| second | y${closer} |\n| valid | $|z|$ |`;
+ const tree = parseMarkdownWithMath(source);
+ const table = tree.children[0];
+ expect(table?.type).toBe("table");
+ if (table?.type !== "table") throw new Error("Missing table");
+ expect(table.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2]);
+ expect(
+ collect(tree)
+ .filter((node) => node.type === "text")
+ .map((node) => node.value),
+ ).toEqual([
+ "Name",
+ "Value",
+ "first",
+ opener.slice(1) + "x",
+ "second",
+ "y" + closer.slice(1),
+ "valid",
+ ]);
+ expect(markdownMathRanges(source)).toEqual([
+ expect.objectContaining({ source: "$|z|$", tex: "|z|" }),
+ ]);
+ expect(JSON.stringify(tree)).not.toMatch(/[\uE000-\uF8FF]/);
+ });
+
+ it("retains multiline math pipes outside tables", () => {
+ const source = "Outside \\(x|y\n+z\\) remains math.\n\n\\[\n|a|\n+|b|\n\\]";
+ expect(markdownMathRanges(source).map((range) => range.tex)).toEqual(["x|y\n+z", "|a|\n+|b|"]);
+ });
+ it.each(["\\(\\frac{1}{|x|}\\)", "$$|x|$$", "$|x|$", "\\[|x|\\]"])(
+ "keeps pipes inside %s in one cell and preserves source offsets",
+ (formula) => {
+ const source = `| Name | Value |\n| --- | --- |\n| x | ${formula} |\n\n- [ ] next`;
+ const tree = parseMarkdownWithMath(source);
+ const table = tree.children[0];
+ expect(table?.type).toBe("table");
+ if (table?.type !== "table") throw new Error("Missing table");
+ expect(table.children.map((row) => row.children.length)).toEqual([2, 2]);
+ expect(markdownMathRanges(source)).toEqual([
+ expect.objectContaining({ source: formula, start: source.indexOf(formula) }),
+ ]);
+ const checkbox = collect(tree).find((node) => node.type === "listItem");
+ expect(checkbox?.position?.start.offset).toBe(source.indexOf("- [ ]"));
+ },
+ );
+
+ it("preserves TeX pipe commands inside and outside tables", () => {
+ const source = "| Formula |\n| --- |\n| \\(\\|x\\|\\) |\n\n\\(\\|x\\|\\)";
+ expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual([
+ "\\|x\\|",
+ "\\|x\\|",
+ ]);
+ });
+
+ it("leaves code, URLs, incomplete math, and private-use text unchanged", () => {
+ const source =
+ "| Value | Other |\n| --- | --- |\n| `\\(a\\|b\\)` | \\(x|y\\) |\n\n\uE000\n\n[link](https://example.com/$x|y$)\n\nUnclosed \\(x|y";
+ const tree = parseMarkdownWithMath(source);
+ expect(markdownMathRanges(source).map((formula) => formula.tex)).toEqual(["x|y"]);
+ expect(JSON.stringify(tree)).toContain("https://example.com/$x|y$");
+ expect(collect(tree).find((node) => node.type === "inlineCode")).toMatchObject({
+ value: "\\(a|b\\)",
+ });
+ expect(JSON.stringify(tree)).toContain("\uE000");
+ });
+
+ it("keeps a display equation's equality line out of Markdown headings", () => {
+ const source = "\\[\na\n=\nb\n\\]";
+ expect(parseMarkdownWithMath(source).children).toEqual([
+ expect.objectContaining({ type: "math", value: "a\n=\nb" }),
+ ]);
+ });
+});
diff --git a/packages/shared/src/markdownMath.ts b/packages/shared/src/markdownMath.ts
new file mode 100644
index 00000000000..96e401ce1c9
--- /dev/null
+++ b/packages/shared/src/markdownMath.ts
@@ -0,0 +1,67 @@
+/// <reference types="mdast-util-to-hast" />
+import type { Root } from "mdast";
+import remarkMath from "remark-math";
+import remarkParse from "remark-parse";
+import remarkGfm from "remark-gfm";
+import { unified } from "unified";
+
+const mathParser = unified()
+ .use(remarkParse)
+ .use(remarkGfm)
+ .use(remarkMath, { singleDollarTextMath: true })
+ .freeze();
+
+export function parseMarkdownWithMath(source: string) {
+ return mathParser.parse(source);
+}
+
+/** Closed, parser-owned formulas with authored source for editors. */
+export function markdownMathRanges(source: string, tree?: Root) {
+ const ranges: Array<{
+ start: number;
+ end: number;
+ source: string;
+ tex: string;
+ display: boolean;
+ inTable: boolean;
+ }> = [];
+ if (!mayContainMath(source)) return ranges;
+ const visit = (node: Root | Root["children"][number], inTable = false) => {
+ const table = inTable || node.type === "tableCell";
+ if (
+ node.type === "math" ||
+ node.type === "inlineMath" ||
+ (node.type === "code" && node.lang === "math")
+ ) {
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (start === undefined || end === undefined) return;
+ const authored = source.slice(start, end);
+ if (node.type === "code") {
+ const open = /^[ \t]*(`{3,}|~{3,})/.exec(authored)?.[1];
+ const close = /\n[ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(authored)?.[1];
+ if (!open || !close || open[0] !== close[0] || close.length < open.length) return;
+ }
+ const display = node.type !== "inlineMath" || /^(?:\$\$|\\\[)/.test(authored);
+ ranges.push({ start, end, source: authored, tex: node.value, display, inTable: table });
+ } else if ("children" in node) node.children.forEach((child) => visit(child, table));
+ };
+ visit(tree ?? parseMarkdownWithMath(source));
+ return ranges;
+}
+
+/** Messages without these characters skip math parsing entirely. */
+function mayContainMath(text: string): boolean {
+ return (
+ text.includes("$") ||
+ text.includes("\\(") ||
+ text.includes("\\[") ||
+ /(?:`{3,}|~{3,})[ \t]*math\b/.test(text)
+ );
+}
+
+export function mathKind(className: string | undefined): "inline" | "display" | null {
+ if (!className?.includes("language-math")) return null;
+ if (className.includes("math-display")) return "display";
+ return className.includes("math-inline") ? "inline" : null;
+}
diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts
index d8717c6273f..a3282584064 100644
--- a/packages/shared/src/markdownPipeline.ts
+++ b/packages/shared/src/markdownPipeline.ts
@@ -132,7 +132,12 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
attributes: {
...defaultSchema.attributes,
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
- code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
+ // Fence languages plus the two math classes the web chat's math plugin emits.
+ code: [
+ ["className", /^language-./, "math-inline", "math-display"],
+ "dataCodeMeta",
+ "dataInlineCode",
+ ],
blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
@@ -279,7 +284,7 @@ function keepWindowsPathEscape(this: EscapeCompileContext) {
* Prose paths end at whitespace: past that, nothing tells a path from a sentence, and
* `C:\x and \*this\*` must still read `*this*`.
*/
-export function remarkKeepWindowsPaths(this: Processor) {
+function remarkKeepWindowsPaths(this: Processor) {
const data = this.data();
(data.fromMarkdownExtensions ??= []).push({
exit: {
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000000..ace1131cf26
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,14 @@
+diff --git a/lib/index.js b/lib/index.js
+--- a/lib/index.js
++++ b/lib/index.js
+@@ -144,6 +144,10 @@
+ const data = this.resume()
+ const node = this.stack[this.stack.length - 1]
+ assert(node.type === 'inlineMath')
++ const source = this.sliceSerialize(token)
++ if (source.startsWith('$$') || source.startsWith('\\[')) {
++ node.data.hProperties.className = ['language-math', 'math-display']
++ }
+ this.exit(token)
+ node.value = data
+ const children = /** @type {Array<HastElementContent>} */ (
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000000..78cda546653
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,146 @@
+diff --git a/dev/lib/syntax.js b/dev/lib/syntax.js
+--- a/dev/lib/syntax.js
++++ b/dev/lib/syntax.js
+@@ -46,6 +46,10 @@
+ let sizeB = 0
+ /** @type {boolean | undefined} */
+ let seen
++ let mathEnd = 0
++ let afterMath
++ let literalRow = -1
++ let literalRanges = []
+
+ return start
+
+@@ -223,6 +227,21 @@
+ * @type {State}
+ */
+ function headRowData(code) {
++ const construct = (self.parser.constructs.text[code] || []).find(
++ (entry) => entry.name === 'mathText' || entry.name === 'mathTexText'
++ )
++ if (construct && (!construct.previous || construct.previous.call(self, self.previous))) {
++ afterMath = headRowData
++ return effects.check({tokenize: checkMath}, mathData, ordinaryData)(code)
++ }
++ return ordinaryData(code)
++
++ function ordinaryData(code) {
++ return headRowDataOrdinary(code)
++ }
++ }
++
++ function headRowDataOrdinary(code) {
+ if (
+ code === codes.eof ||
+ code === codes.verticalBar ||
+@@ -585,6 +604,21 @@
+ * @type {State}
+ */
+ function bodyRowData(code) {
++ const construct = (self.parser.constructs.text[code] || []).find(
++ (entry) => entry.name === 'mathText' || entry.name === 'mathTexText'
++ )
++ if (construct && (!construct.previous || construct.previous.call(self, self.previous))) {
++ afterMath = bodyRowData
++ return effects.check({tokenize: checkMath}, mathData, ordinaryData)(code)
++ }
++ return ordinaryData(code)
++
++ function ordinaryData(code) {
++ return bodyRowDataOrdinary(code)
++ }
++ }
++
++ function bodyRowDataOrdinary(code) {
+ if (
+ code === codes.eof ||
+ code === codes.verticalBar ||
+@@ -618,6 +652,75 @@
+
+ return bodyRowData(code)
+ }
++ function checkMath(effects, ok, nok) {
++ const context = this
++ const startLine = context.now().line
++ const mathStart = context.now().offset
++ const row = self.events.findLast(
++ (event) => event[0] === 'enter' && event[1].type === 'tableRow'
++ )[1]
++ return startMath
++
++ function startMath(code) {
++ const construct = context.parser.constructs.text[code].find(
++ (entry) => entry.name === 'mathText' || entry.name === 'mathTexText'
++ )
++ const inlineContext = Object.create(context)
++ inlineContext.mathSingleLine = true
++ return effects.attempt({
++ partial: true,
++ tokenize: (effects, ok, nok) => construct.tokenize.call(inlineContext, effects, ok, nok)
++ }, done, nok)(code)
++ }
++
++ function done(code) {
++ if (context.now().line !== startLine) return nok(code)
++ mathEnd = context.now().offset
++ if (literalRow === row.start.offset) return acceptMath(code)
++ if (code === codes.eof || markdownLineEnding(code)) return inspectRow(code)
++ effects.enter(types.data)
++ return rowEnd(code)
++ }
++
++ function rowEnd(code) {
++ if (code !== codes.eof && !markdownLineEnding(code)) {
++ effects.consume(code)
++ return rowEnd
++ }
++ effects.exit(types.data)
++ return inspectRow(code)
++ }
++
++ function inspectRow(code) {
++ // Inline parsing owns destinations, code, autolinks and tag attributes.
++ const events = context.parser.text(row.start).write([
++ ...context.sliceStream({start: row.start, end: context.now()}),
++ codes.eof
++ ])
++ literalRanges = events.flatMap(([kind, token]) =>
++ kind === 'enter' &&
++ (token.type === 'resource' || token.type === 'codeText' ||
++ token.type === 'autolink' || token.type === 'htmlText')
++ ? [[token.start.offset, token.end.offset]]
++ : []
++ )
++ literalRow = row.start.offset
++ return acceptMath(code)
++ }
++
++ function acceptMath(code) {
++ return literalRanges.some(([start, end]) => start <= mathStart && mathStart < end)
++ ? nok(code)
++ : ok(code)
++ }
++ }
++
++ function mathData(code) {
++ if (self.now().offset >= mathEnd) return afterMath(code)
++ effects.consume(code)
++ return mathData
++ }
++
+ }
+
+ /** @type {Resolver} */
+diff --git a/package.json b/package.json
+--- a/package.json
++++ b/package.json
+@@ -27,7 +27,7 @@
+ },
+ "exports": {
+ "development": "./dev/index.js",
+- "default": "./index.js"
++ "default": "./dev/index.js"
+ },
+ "files": [
+ "dev/",
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000000..335ce4c11d5
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,343 @@
+diff --git a/dev/lib/math-flow.js b/dev/lib/math-flow.js
+--- a/dev/lib/math-flow.js
++++ b/dev/lib/math-flow.js
+@@ -4,7 +4,7 @@
+
+ import {ok as assert} from 'devlop'
+ import {factorySpace} from 'micromark-factory-space'
+-import {markdownLineEnding} from 'micromark-util-character'
++import {markdownLineEnding, markdownSpace} from 'micromark-util-character'
+ import {codes, constants, types} from 'micromark-util-symbol'
+
+ /** @type {Construct} */
+@@ -32,6 +32,9 @@
+ ? tail[2].sliceSerialize(tail[1], true).length
+ : 0
+ let sizeOpen = 0
++ let closed = false
++ let slashes = 0
++ let trailingAfterClose = false
+
+ return start
+
+@@ -79,7 +82,32 @@
+ }
+
+ effects.exit('mathFlowFenceSequence')
+- return factorySpace(effects, metaBefore, types.whitespace)(code)
++
++ return factorySpace(effects, afterOpeningWhitespace, types.whitespace)(code)
++ }
++
++ /**
++ * After opening fence whitespace, check for same-line content.
++ *
++ * ```markdown
++ * > | $$ 1 + 1 $$
++ * ^
++ * ```
++ *
++ * @type {State}
++ */
++ function afterOpeningWhitespace(code) {
++ if (code === codes.eof || markdownLineEnding(code)) {
++ return metaAfter(code)
++ }
++
++ effects.exit('mathFlowFence')
++
++ if (self.interrupt) {
++ return ok(code)
++ }
++
++ return beforeContentChunk(code)
+ }
+
+ /**
+@@ -230,6 +258,14 @@
+ )(code)
+ }
+
++ if (code === codes.dollarSign) {
++ return effects.attempt(
++ {tokenize: tokenizeInlineClosingFence, partial: true},
++ after,
++ resumeContentAfterFailedClose
++ )(code)
++ }
++
+ effects.enter('mathFlowValue')
+ return contentChunk(code)
+ }
+@@ -247,13 +283,74 @@
+ * @type {State}
+ */
+ function contentChunk(code) {
++ const escaped = slashes % 2 === 1
++ slashes = code === codes.backslash ? slashes + 1 : 0
+ if (code === codes.eof || markdownLineEnding(code)) {
+ effects.exit('mathFlowValue')
+ return beforeContentChunk(code)
+ }
+
++ if (code === codes.dollarSign && !escaped) {
++ effects.exit('mathFlowValue')
++ return effects.attempt(
++ {tokenize: tokenizeInlineClosingFence, partial: true},
++ after,
++ resumeContentAfterFailedClose
++ )(code)
++ }
++
+ effects.consume(code)
+ return contentChunk
++ }
++
++ /**
++ * Resume content after a failed inline closing fence attempt.
++ *
++ * @type {State}
++ */
++ function resumeContentAfterFailedClose(code) {
++ if (trailingAfterClose) return nok(code)
++ effects.enter('mathFlowValue')
++ effects.consume(code)
++ return contentChunk
++ }
++
++ /** @type {Tokenizer} */
++ function tokenizeInlineClosingFence(effects, ok, nok) {
++ let size = 0
++ return sequenceStart
++
++ function sequenceStart(code) {
++ effects.enter('mathFlowFence')
++ effects.enter('mathFlowFenceSequence')
++ return sequenceClose(code)
++ }
++
++ function sequenceClose(code) {
++ if (code === codes.dollarSign) {
++ size++
++ effects.consume(code)
++ return sequenceClose
++ }
++
++ if (size < sizeOpen) {
++ return nok(code)
++ }
++
++ effects.exit('mathFlowFenceSequence')
++ return factorySpace(effects, afterSequenceClose, types.whitespace)(code)
++ }
++
++ function afterSequenceClose(code) {
++ if (code === codes.eof || markdownLineEnding(code)) {
++ effects.exit('mathFlowFence')
++ closed = true
++ return ok(code)
++ }
++
++ trailingAfterClose = true
++ return nok(code)
++ }
+ }
+
+ /**
+@@ -269,6 +366,7 @@
+ * @type {State}
+ */
+ function after(code) {
++ if (!closed) return nok(code)
+ effects.exit('mathFlow')
+ return ok(code)
+ }
+@@ -357,6 +455,7 @@
+ function afterSequenceClose(code) {
+ if (code === codes.eof || markdownLineEnding(code)) {
+ effects.exit('mathFlowFence')
++ closed = true
+ return ok(code)
+ }
+
+diff --git a/dev/lib/math-tex-flow.js b/dev/lib/math-tex-flow.js
+--- a/dev/lib/math-tex-flow.js
++++ b/dev/lib/math-tex-flow.js
+@@ -26,6 +26,7 @@
+ */
+ function tokenizeMathFenced(effects, ok, nok) {
+ const self = this
++ let closed = false
+ const tail = self.events[self.events.length - 1]
+ const initialSize =
+ tail && tail[1].type === types.linePrefix
+@@ -90,6 +91,7 @@
+ * @type {State}
+ */
+ function metaAfter(code) {
++ if (code !== codes.eof && !markdownLineEnding(code)) return nok(code)
+ effects.exit('mathFlowFence')
+
+ if (self.interrupt) {
+@@ -245,6 +247,7 @@
+ * @type {State}
+ */
+ function after(code) {
++ if (!closed) return nok(code)
+ effects.exit('mathFlow')
+ return ok(code)
+ }
+@@ -327,6 +330,7 @@
+ function afterSequenceClose(code) {
+ if (code === codes.eof || markdownLineEnding(code)) {
+ effects.exit('mathFlowFence')
++ closed = true
+ return ok(code)
+ }
+
+diff --git a/dev/lib/math-tex-text.js b/dev/lib/math-tex-text.js
+--- a/dev/lib/math-tex-text.js
++++ b/dev/lib/math-tex-text.js
+@@ -25,6 +25,7 @@
+ let token
+ /** @type {number} */
+ let openSequenceCode
++ let substantive = false
+
+ return start
+
+@@ -83,7 +84,7 @@
+ * @type {State}
+ */
+ function between(code) {
+- if (code === codes.eof) {
++ if (code === codes.eof || code === codes.graveAccent || (self.mathSingleLine && markdownLineEnding(code))) {
+ return nok(code)
+ }
+
+@@ -124,6 +125,8 @@
+ * @type {State}
+ */
+ function data(code) {
++ if (code === codes.graveAccent) return nok(code)
++ if (code !== codes.backslash && code !== codes.eof && code !== codes.space && code !== codes.comma && !markdownLineEnding(code) && !(code >= codes.digit0 && code <= codes.digit9)) substantive = true
+ if (
+ code === codes.eof ||
+ code === codes.space ||
+@@ -155,6 +158,7 @@
+ ? codes.rightParenthesis
+ : codes.rightSquareBracket
+ if (code === closeSequenceCode) {
++ if (openSequenceCode === codes.leftSquareBracket && !substantive) return nok(code)
+ effects.consume(code)
+ effects.exit('mathTextSequence')
+ effects.exit('mathText')
+diff --git a/dev/lib/math-text.js b/dev/lib/math-text.js
+--- a/dev/lib/math-text.js
++++ b/dev/lib/math-text.js
+@@ -42,6 +42,13 @@
+ let size
+ /** @type {Token} */
+ let token
++ /** @type {boolean} */
++ let openWhitespace
++ /** @type {number | undefined} */
++ let charBeforeClose
++ let slashes = 0
++ let previousData
++ let beforeData
+
+ return start
+
+@@ -89,6 +96,16 @@
+ }
+
+ effects.exit('mathTextSequence')
++ // Reject if opening is followed by line ending
++ if (markdownLineEnding(code)) {
++ return nok(code)
++ }
++ // Track if opening sequence is followed by whitespace
++ openWhitespace =
++ code === codes.space ||
++ code === codes.horizontalTab ||
++ code === codes.comma
++ if (sizeOpen === 1 && openWhitespace) return nok(code)
+ return between(code)
+ }
+
+@@ -103,13 +120,14 @@
+ * @type {State}
+ */
+ function between(code) {
+- if (code === codes.eof) {
++ if (code === codes.eof || code === codes.graveAccent || ((sizeOpen === 1 || self.mathSingleLine) && markdownLineEnding(code))) {
+ return nok(code)
+ }
+
+ if (code === codes.dollarSign) {
+ token = effects.enter('mathTextSequence')
+ size = 0
++ charBeforeClose = self.previous
+ return sequenceClose(code)
+ }
+
+@@ -144,6 +162,16 @@
+ * @type {State}
+ */
+ function data(code) {
++ if (code === codes.graveAccent) return nok(code)
++ if (code === codes.dollarSign && slashes % 2 === 1) {
++ slashes = 0
++ effects.consume(code)
++ return data
++ }
++ if (code === codes.slash && previousData === codes.slash && beforeData === codes.colon) return nok(code)
++ beforeData = previousData
++ previousData = code
++ slashes = code === codes.backslash ? slashes + 1 : 0
+ if (
+ code === codes.eof ||
+ code === codes.space ||
+@@ -179,9 +207,26 @@
+
+ // Done!
+ if (size === sizeOpen) {
+- effects.exit('mathTextSequence')
+- effects.exit('mathText')
+- return ok(code)
++ // Reject if closing is preceded by line ending
++ if (markdownLineEnding(charBeforeClose)) {
++ return nok(code)
++ }
++ // Reject if closing is followed by a digit
++ if (code !== null && code >= codes.digit0 && code <= codes.digit9) {
++ return nok(code)
++ }
++ // Check if closing sequence has matching whitespace pattern
++ const closeWhitespace =
++ charBeforeClose === codes.space ||
++ charBeforeClose === codes.horizontalTab ||
++ charBeforeClose === codes.comma
++ if (openWhitespace === closeWhitespace) {
++ effects.exit('mathTextSequence')
++ effects.exit('mathText')
++ return ok(code)
++ }
++ // Whitespace mismatch: mark as data
++ return nok(code)
+ }
+
+ // More or less accents: mark as data.
+diff --git a/package.json b/package.json
+--- a/package.json
++++ b/package.json
+@@ -27,7 +27,7 @@
+ "type": "module",
+ "exports": {
+ "development": "./dev/index.js",
+- "default": "./index.js"
++ "default": "./dev/index.js"
+ },
+ "files": [
+ "dev/",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 01e7f2be6dc..6bba33a50c6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -139,6 +139,8 @@ overrides:
expo-sharing>@expo/config-plugins: 58.0.9
expo-sharing>@expo/config-types: 58.0.3
'@pierre/diffs>@shikijs/transformers': ^4.2.0
+ remark-math>micromark-extension-math: npm:[email protected]
+ micromark-extension-gfm-table: 2.1.1
'@tailwindcss/node': 4.3.3
'@tailwindcss/oxide': 4.3.3
'@tailwindcss/vite': 4.3.3
@@ -177,6 +179,9 @@ patchedDependencies:
[email protected]: 2c2f8c73a23d48804c8b537b8cd73c25eb331aa47d82eaa481c6766cb81e5add
[email protected]: ad248759641ddd71b8331c09dbb3b18c8a551785f2df507533805babd3c0c124
[email protected]: 8623cb034b720c5ef2da8012c765805a7298909bd92eaf8381f64dbde41b77dd
+ [email protected]: afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c
+ [email protected]: 9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8
+ [email protected]: 49ab4815c18b003f6af998dcc6c258c17a21b50b2cc87745f12d4bd8b6d591f9
[email protected]: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651
[email protected]: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626
[email protected]: f28d08f1233e3cce8b9324b4357d2b10f1ee040b8051bc87235b0fb95069b9bb
@@ -556,8 +561,8 @@ importers:
specifier: 0.25.1
react-native-enriched-markdown:
- specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.15.tgz
+ specifier: file:deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz
+ version: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
react-native-gesture-handler:
specifier: ~3.3.0
version: 3.3.0(patch_hash=abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
@@ -944,6 +949,9 @@ importers:
jszip:
specifier: 3.10.1
version: 3.10.1
+ katex:
+ specifier: ^0.16.47
+ version: 0.16.47
lucide:
specifier: ^0.564.0
version: 0.564.0
@@ -968,6 +976,9 @@ importers:
remark-gfm:
specifier: 'catalog:'
version: 4.0.1
+ remark-math:
+ specifier: 6.0.0
+ version: 6.0.0
tailwind-merge:
specifier: ^3.4.0
version: 3.6.0
@@ -1560,6 +1571,9 @@ importers:
mdast-util-directive:
specifier: 'catalog:'
version: 3.1.0
+ mdast-util-to-hast:
+ specifier: ^13.2.1
+ version: 13.2.1
micromark-extension-directive:
specifier: 'catalog:'
version: 4.0.0
@@ -1578,6 +1592,9 @@ importers:
remark-gfm:
specifier: 'catalog:'
version: 4.0.1
+ remark-math:
+ specifier: 6.0.0
+ version: 6.0.0
remark-parse:
specifier: 'catalog:'
version: 11.0.0
@@ -1597,6 +1614,9 @@ importers:
'@effect/vitest':
specifier: 4.0.5
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/node':
specifier: 24.12.4
version: 24.12.4
@@ -6676,9 +6696,6 @@ packages:
resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
-
resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==}
@@ -6700,6 +6717,9 @@ packages:
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==}
+
resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}
@@ -10094,6 +10114,9 @@ packages:
resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
+ resolution: {integrity: sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==}
+
resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
@@ -10235,6 +10258,9 @@ packages:
resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}
+ resolution: {integrity: sha512-VIYHuIEk0gpHrojEtNGaxGwdpSLtdWYlLL2vu9PM4M1ilEtak10S8F9zzbNAPBNRoWFs/bjs+J7R3yUBoIQUEA==}
+
resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}
@@ -11163,8 +11189,8 @@ packages:
react: '*'
react-native: '*'
- react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz:
- resolution: {integrity: sha512-p9o8zNoVoNwqdlG8a9Fvhj0RFUjmpE6VecwOVsO6a8Alj2HPfCDzeLBq0SFn2KdUYX32MC2fH1gJJs/HyfP5Mg==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz}
+ react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz:
+ resolution: {integrity: sha512-dFBqwCTfgVXNU1wxwwZidHdpMxGCd+8jCPunbdO8fNG0uYVr3RQZmTwX/bC5JdgzFODZ8A7heqNBoukNpPiNtA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz}
version: 1.2.0-t3.15
peerDependencies:
katex: '>=0.16.0'
@@ -11356,6 +11382,9 @@ packages:
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
+ resolution: {integrity: sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==}
+
resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
@@ -12110,6 +12139,9 @@ packages:
resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
+ resolution: {integrity: sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==}
+
resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
@@ -17367,10 +17399,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]':
- dependencies:
- '@types/unist': 3.0.3
-
dependencies:
'@types/unist': 3.0.3
@@ -17391,6 +17419,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 24.12.4
@@ -20345,7 +20375,7 @@ snapshots:
dependencies:
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/unist': 3.0.3
ccount: 2.0.1
comma-separated-tokens: 2.0.3
@@ -20360,7 +20390,7 @@ snapshots:
dependencies:
'@types/estree': 1.0.9
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/unist': 3.0.3
comma-separated-tokens: 2.0.3
devlop: 1.1.0
@@ -20389,7 +20419,7 @@ snapshots:
dependencies:
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
dependencies:
@@ -21012,10 +21042,22 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ [email protected](patch_hash=afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c):
+ dependencies:
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ longest-streak: 3.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ unist-util-remove-position: 5.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/estree-jsx': 1.0.5
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/mdast': 4.0.4
devlop: 1.1.0
mdast-util-from-markdown: 2.0.3
@@ -21026,7 +21068,7 @@ snapshots:
dependencies:
'@types/estree-jsx': 1.0.5
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/mdast': 4.0.4
'@types/unist': 3.0.3
ccount: 2.0.1
@@ -21043,7 +21085,7 @@ snapshots:
dependencies:
'@types/estree-jsx': 1.0.5
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/mdast': 4.0.4
devlop: 1.1.0
mdast-util-from-markdown: 2.0.3
@@ -21063,7 +21105,7 @@ snapshots:
dependencies:
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/mdast': 4.0.4
'@ungap/structured-clone': 1.3.1
devlop: 1.1.0
@@ -21359,7 +21401,7 @@ snapshots:
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
+ [email protected](patch_hash=9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8):
dependencies:
devlop: 1.1.0
micromark-factory-space: 2.0.1
@@ -21384,12 +21426,22 @@ snapshots:
micromark-extension-gfm-autolink-literal: 2.1.0
micromark-extension-gfm-footnote: 2.1.0
micromark-extension-gfm-strikethrough: 2.1.0
- micromark-extension-gfm-table: 2.1.1
+ micromark-extension-gfm-table: 2.1.1(patch_hash=9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8)
micromark-extension-gfm-tagfilter: 2.0.0
micromark-extension-gfm-task-list-item: 2.1.0
micromark-util-combine-extensions: 2.0.1
micromark-util-types: 2.0.2
+ [email protected](patch_hash=49ab4815c18b003f6af998dcc6c258c17a21b50b2cc87745f12d4bd8b6d591f9):
+ dependencies:
+ '@types/katex': 0.16.8
+ devlop: 1.1.0
+ katex: 0.16.47
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
dependencies:
micromark-util-character: 2.1.1
@@ -22501,7 +22553,7 @@ snapshots:
dependencies:
- '@types/hast': 3.0.4
+ '@types/hast': 3.0.5
'@types/mdast': 4.0.4
'@types/react': 19.3.0
devlop: 1.1.0
@@ -22523,7 +22575,7 @@ snapshots:
react: 19.3.0
- react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
+ react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):
dependencies:
react: 19.3.0
@@ -22787,6 +22839,15 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-math: 3.0.0(patch_hash=afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c)
+ micromark-extension-math: [email protected](patch_hash=49ab4815c18b003f6af998dcc6c258c17a21b50b2cc87745f12d4bd8b6d591f9)
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 4.0.4
@@ -23669,6 +23730,11 @@ snapshots:
dependencies:
'@types/unist': 3.0.3
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-visit: 5.1.0
+
dependencies:
'@types/unist': 3.0.3
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index bb94794604b..5800efc6c64 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -20,7 +20,7 @@ allowBuilds:
node-pty: true
# Ships N-API prebuilds; its install script only rebuilds from source.
objc-js: false
- "react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15.tgz": true
+ "react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.15-fee84114.tgz": true
sharp: true
tsc-rs: true
utf-8-validate: false
@@ -271,6 +271,9 @@ overrides:
"expo-sharing>@expo/config-plugins": 58.0.9
"expo-sharing>@expo/config-types": 58.0.3
"@pierre/diffs>@shikijs/transformers": ^4.2.0
+ # Resolve below remark-math so Vite, Metro and Node use the same tokenizer.
+ "remark-math>micromark-extension-math": npm:[email protected]
+ micromark-extension-gfm-table: 2.1.1
# Keep one copy of these native-binary packages. lightningcss ships 11 platform binaries per
# version, and the workspaces' tailwindcss ^4 ranges drift into two 4.3.x copies of the family.
"@tailwindcss/node": "catalog:"
@@ -314,6 +317,9 @@ packageExtensions:
vite-plus: "catalog:"
patchedDependencies:
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts
index c8faf49221a..aafe04677b8 100644
--- a/scripts/build-desktop-artifact.test.ts
+++ b/scripts/build-desktop-artifact.test.ts
@@ -516,7 +516,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
const { allowBuilds = {} } = yield* readWorkspaceConfig();
const repoRoot = path.join(import.meta.dirname, "..");
for (const key of Object.keys(allowBuilds)) {
- const tarball = key.split("@file:")[1];
+ const tarball = key.split("@file:")[1]?.replace(/\(patch_hash=[a-f0-9]+\)$/, "");
if (tarball === undefined) continue;
assert.isTrue(
yield* fs.exists(path.join(repoRoot, tarball)),
diff --git a/third-party-licenses.config.json b/third-party-licenses.config.json
index abdde60fe16..180a7bb3b15 100644
--- a/third-party-licenses.config.json
+++ b/third-party-licenses.config.json
@@ -159,9 +159,62 @@
"name": "Expo text editor implementation",
"noticeFile": "apps/mobile/modules/t3-composer-editor/LICENSE",
"sourceUrl": "https://github.com/expo/expo"
+ },
+ {
+ "bundles": ["ios", "android", "mobile"],
+ "license": "MIT",
+ "name": "RaTeX",
+ "version": "0.1.15",
+ "sourceUrl": "https://github.com/erweixin/RaTeX/tree/v0.1.15",
+ "generatedNotices": [
+ {
+ "licenseId": "MIT",
+ "copyrights": ["Copyright (c) erweixin"]
+ }
+ ]
+ },
+ {
+ "bundles": ["ios", "android", "mobile", "web", "desktop"],
+ "license": "MIT",
+ "name": "micromark-extension-llm-math",
+ "version": "3.1.0",
+ "sourceUrl": "https://github.com/ofk/micromark-extension-llm-math",
+ "generatedNotices": [
+ {
+ "licenseId": "MIT",
+ "copyrights": ["Copyright (c) 2020 Titus Wormer <[email protected]>"]
+ }
+ ]
+ },
+ {
+ "bundles": ["ios", "android", "mobile", "web", "desktop"],
+ "license": "OFL-1.1",
+ "name": "KaTeX mathematical fonts",
+ "sourceUrl": "https://github.com/KaTeX/KaTeX",
+ "generatedNotices": [
+ {
+ "licenseId": "OFL-1.1",
+ "copyrights": [
+ "Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)",
+ "Copyright (c) 2014-2018 Khan Academy (<www.khanacademy.org>)"
+ ],
+ "preamble": [
+ "Unmodified KaTeX_* mathematical fonts. Reserved Font Names include KaTeX_Main, KaTeX_Math, KaTeX_AMS, and KaTeX_Caligraphic."
+ ]
+ }
+ ]
}
],
"packageOverrides": [
+ {
+ "name": "remark-math",
+ "version": "6.0.0",
+ "sourceUrl": "https://github.com/remarkjs/remark-math/blob/main/license",
+ "generatedNotice": {
+ "licenseId": "MIT",
+ "copyrights": ["Copyright (c) Junyoung Choi <[email protected]>"]
+ }
+ },
{
"name": "@react-native-async-storage/async-storage",
"version": "3.1.1",