Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(editor): render Markdown math fences and preserve code dollars

tianma-if4dcb6194625d
diff --git a/apps/web/src/components/editor/math-formula.test.mjs b/apps/web/src/components/editor/math-formula.test.mjs
index 316b1b12..ecb4b6f7 100644
--- a/apps/web/src/components/editor/math-formula.test.mjs
+++ b/apps/web/src/components/editor/math-formula.test.mjs
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { Editor } from "@tiptap/core";
-import { createEdgeEverDocumentExtensions } from "@edgeever/shared";
+import { createEdgeEverDocumentExtensions, createEdgeEverMarkdownManager } from "@edgeever/shared";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
import { ensureTestWindowDom } from "../../lib/restore-test-global.mjs";
import {
@@ -21,6 +21,14 @@ const createEditor = (content) => {
};
describe("math formula commands", () => {
+ test("browser Markdown schema imports math fences as rendered formula nodes", () => {
+ const manager = createEdgeEverMarkdownManager({ mathematics: createEdgeEverMathematics() });
+ const content = manager.parse("```math\n\\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t}dt\\,.\n```");
+ const editor = createEditor(content);
+ expect(editor.getJSON().content[0].type).toBe("blockMath");
+ expect(manager.parse(manager.serialize(editor.getJSON()))).toEqual(editor.getJSON());
+ editor.destroy();
+ });
test("inserts inline math at the caret", () => {
const editor = createEditor({
type: "doc",
diff --git a/packages/shared/src/content.test.mjs b/packages/shared/src/content.test.mjs
index 57c05b2b..89f0f000 100644
--- a/packages/shared/src/content.test.mjs
+++ b/packages/shared/src/content.test.mjs
@@ -400,6 +400,59 @@ describe("Mermaid Markdown conversion", () => {
describe("LaTeX Markdown conversion", () => {
const markdown = "Euler: $e^{i\\pi}+1=0$.\n\n$$\n\\frac{a}{b}\n$$";
+ test("renders the issue #514 math fence while preserving its inline code example", () => {
+ const inline = "$\\Gamma(n) = (n-1)!\\quad\\forall n\\in\\mathbb N$";
+ const latex = "\\Gamma(z) = \\int_0^\\infty t^{z-1}e^{-t}dt\\,.";
+ const doc = markdownToDoc(`The Gamma function satisfying \`${inline}\`\n\n\`\`\`math\n${latex}\n\`\`\``);
+ expect(doc.content[0].content[1]).toMatchObject({ type: "text", text: inline, marks: [{ type: "code" }] });
+ expect(doc.content[1]).toEqual({ type: "blockMath", attrs: { latex } });
+ expect(markdownToDoc(docToMarkdown(doc))).toEqual(doc);
+ });
+
+ test("uses standard fence parsing for tilde, longer, nested, and ordinary fences", () => {
+ for (const fence of ["~~~", "````"]) {
+ expect(markdownToDoc(`${fence}math\nx^2\n${fence}`).content[0]).toEqual({
+ type: "blockMath", attrs: { latex: "x^2" },
+ });
+ }
+ expect(markdownToDoc("> ```math\n> x^2\n> ```").content[0].content[0].type).toBe("blockMath");
+ for (const language of ["", "latex", "javascript", "mermaid"]) {
+ expect(markdownToDoc(`\`\`\`${language}\n$x$\n\`\`\``).content[0].type).toBe("codeBlock");
+ }
+ expect(markdownToDoc("```math\n\n```").content[0].type).toBe("codeBlock");
+ expect(markdownToDoc("````markdown\n```math\nx^2\n```\n````").content[0].type).toBe("codeBlock");
+ });
+
+ test("keeps code dollar pairs unchanged through repeated Markdown round trips", () => {
+ for (const source of ["`$x$`", "```js\nconst cost = '$100$';\nconst formula = '$x$';\n```", "```\n$$x^2$$\n```"]) {
+ const original = markdownToDoc(source);
+ let current = original;
+ for (let i = 0; i < 3; i += 1) current = markdownToDoc(docToMarkdown(current));
+ expect(current).toEqual(original);
+ expect(docToMarkdown(original)).toBe(source);
+ }
+ });
+
+ test("upgrades legacy math code blocks without losing rich table cells or image widths", () => {
+ const legacy = {
+ type: "doc",
+ content: [
+ { type: "codeBlock", attrs: { language: "math" }, content: [{ type: "text", text: "x^2" }] },
+ { type: "table", content: [{ type: "tableRow", content: [{ type: "tableCell", content: [
+ { type: "paragraph", content: [{ type: "text", text: "Rich", marks: [{ type: "bold" }] }] },
+ { type: "image", attrs: { src: "/image.png", width: "50%" } },
+ ] }] }] },
+ { type: "paragraph", content: [{ type: "text", text: "$x$", marks: [{ type: "code" }] }] },
+ ],
+ };
+ const before = JSON.stringify(legacy);
+ const resolved = resolveMemoContentDoc(legacy, "```math\nx^2\n```");
+ expect(resolved.content[0]).toEqual({ type: "blockMath", attrs: { latex: "x^2" } });
+ expect(resolved.content.slice(1)).toEqual(legacy.content.slice(1));
+ expect(JSON.stringify(legacy)).toBe(before);
+ expect(resolveMemoContentDoc(resolved, docToMarkdown(resolved))).toEqual(resolved);
+ });
+
test("round-trips inline and block formula nodes", () => {
const doc = markdownToDoc(markdown);
diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts
index b5aacc13..7ed4586c 100644
--- a/packages/shared/src/content.ts
+++ b/packages/shared/src/content.ts
@@ -157,6 +157,22 @@ const docContainsNodeType = (doc: TiptapDoc, nodeType: string): boolean => {
return visit(doc.content);
};
+/** Upgrade only explicit math fences in older JSON, retaining rich-only content. */
+const upgradeMathCodeFences = (doc: TiptapDoc): TiptapDoc => {
+ const visit = (node: TiptapNode): TiptapNode => {
+ if (node.type === "codeBlock" && node.attrs?.language === "math"
+ && node.content?.every((child) => child.type === "text")) {
+ const latex = node.content.map((child) => (child as TiptapTextNode).text).join("").trim();
+ if (latex) return { type: BLOCK_MATH_NODE_TYPE, attrs: { latex } };
+ }
+ if (!node.content) return node;
+ const content = node.content.map(visit);
+ return content.some((child, index) => child !== node.content?.[index]) ? { ...node, content } : node;
+ };
+ const content = doc.content.map(visit);
+ return content.some((node, index) => node !== doc.content[index]) ? { ...doc, content } : doc;
+};
+
/**
* Recovers Markdown features that an older editor schema could not persist in
* contentJson. The stored Markdown remains the compatibility source in that
@@ -168,9 +184,9 @@ export const resolveMemoContentDoc = (
contentMarkdown: string | null | undefined
): TiptapDoc => {
const currentDoc = contentJson && Array.isArray(contentJson.content)
- ? normalizeImageGalleries(
+ ? upgradeMathCodeFences(normalizeImageGalleries(
upgradeStandaloneFileLinks(upgradeStandalonePdfLinks(upgradeLegacyAttachmentLinks(contentJson))),
- )
+ ))
: emptyDoc();
if (
!contentMarkdown?.trim() ||
@@ -376,7 +392,9 @@ const protectLiteralDollarPairs = (value: unknown): unknown => {
return value;
}
- const node = value as { type?: unknown; text?: unknown; content?: unknown };
+ const node = value as { type?: unknown; text?: unknown; content?: unknown; marks?: Array<{ type?: string }> };
+ // Markdown does not interpret escapes inside code; adding them changes the source.
+ if (node.type === "codeBlock" || node.marks?.some((mark) => mark.type === "code")) return value;
if (node.type === "text" && typeof node.text === "string") {
const dollarCount = Array.from(node.text).filter((character) => character === "$").length;
return dollarCount >= 2
diff --git a/packages/shared/src/document-extensions.ts b/packages/shared/src/document-extensions.ts
index e1f60a17..196727b0 100644
--- a/packages/shared/src/document-extensions.ts
+++ b/packages/shared/src/document-extensions.ts
@@ -13,6 +13,7 @@ import { PluginEmbed } from "./plugin-embed";
import { EmptyExternalLink } from "./empty-external-link";
import { EdgeEverLink } from "./editor-link";
import { createEdgeEverTaskItem } from "./task-item-input";
+import { MathCodeFence } from "./mathematics-markdown";
export type CreateEdgeEverDocumentExtensionsOptions = {
mathematics: AnyExtension[];
@@ -55,6 +56,7 @@ export const createEdgeEverDocumentExtensions = (
...createEdgeEverDetailsExtensions(),
...withOptional(options.pluginEmbed, PluginEmbed),
...options.mathematics,
+ MathCodeFence,
...(options.markdown
? [Markdown.configure({ markedOptions: { gfm: true } })]
: []),
diff --git a/packages/shared/src/mathematics-markdown.ts b/packages/shared/src/mathematics-markdown.ts
index 05a65242..b457e5cc 100644
--- a/packages/shared/src/mathematics-markdown.ts
+++ b/packages/shared/src/mathematics-markdown.ts
@@ -1,8 +1,19 @@
-import { mergeAttributes, Node } from "@tiptap/core";
+import { Extension, mergeAttributes, Node } from "@tiptap/core";
export const BLOCK_MATH_NODE_TYPE = "blockMath" as const;
export const INLINE_MATH_NODE_TYPE = "inlineMath" as const;
+/** Reuse the Markdown lexer's fence handling, including nesting and fence length. */
+export const MathCodeFence = Extension.create({
+ name: "mathCodeFence",
+ priority: 101,
+ markdownTokenName: "code",
+ parseMarkdown: (token) => {
+ if (token.lang !== "math" || !token.text?.trim()) return [];
+ return { type: BLOCK_MATH_NODE_TYPE, attrs: { latex: token.text.trim() } };
+ },
+});
+
const isEscaped = (source: string, index: number) => {
let backslashCount = 0;
for (let cursor = index - 1; cursor >= 0 && source[cursor] === "\\"; cursor -= 1) {