Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(math): render MathLive commands unsupported by KaTeX (closes #9523)
Elian Doran6059da9bfb15
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex c26ad6b04d..06db074dd7 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -1,3 +1,5 @@+import { KATEX_MACROS } from "@triliumnext/commons";+import FAttachment from "../entities/fattachment.js";import FNote from "../entities/fnote.js";import { default as content_renderer, type RenderOptions } from "./content_renderer.js";@@ -45,7 +47,8 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere// throwOnError: false makes KaTeX render invalid formulas as an inline red error// (with the parse message as a tooltip) instead of throwing and leaving raw `$…$`// text plus a console error — matching the editor's behavior.- renderMathInElement($renderedContent[0], { trust: true, throwOnError: false });+ // Spread KATEX_MACROS into a fresh object: KaTeX may mutate it (e.g. via `\gdef`).+ renderMathInElement($renderedContent[0], { trust: true, throwOnError: false, macros: { ...KATEX_MACROS } });}const getNoteIdFromLink = (el: HTMLElement) => tree.getNoteIdFromUrl($(el).attr("href") || "");diff --git a/apps/client/src/services/katex_macros.spec.ts b/apps/client/src/services/katex_macros.spec.tsnew file mode 100644index 0000000000..d35cc76f77--- /dev/null+++ b/apps/client/src/services/katex_macros.spec.ts@@ -0,0 +1,27 @@+import { KATEX_MACROS } from "@triliumnext/commons";+import katex from "katex";+import { describe, expect, it } from "vitest";++// Guards against the MathLive→KaTeX mismatch from issue #9523: the visual math editor+// emits commands KaTeX doesn't define, so they must be mapped to valid KaTeX. These tests+// render against the real KaTeX engine so a typo in a macro value would surface as a throw.+describe("KaTeX MathLive compatibility macros", () => {+ it("renders every mapped MathLive command without erroring", () => {+ for (const [command, replacement] of Object.entries(KATEX_MACROS)) {+ // throwOnError makes KaTeX throw on an unknown command rather than emitting red+ // error text, so a successful render proves both the macro key is needed (the+ // bare command is unknown) and its replacement is valid KaTeX.+ expect(() => katex.renderToString(command, { throwOnError: true }), `${command} should be unknown to KaTeX`).toThrow();+ expect(() => katex.renderToString(command, { throwOnError: true, macros: { ...KATEX_MACROS } }), `${command} → ${replacement}`).not.toThrow();+ }+ });++ it("renders a differential integral expression that previously failed (issue #9523)", () => {+ const html = katex.renderToString("\\int f(x) \\differentialD x", {+ throwOnError: true,+ macros: { ...KATEX_MACROS }+ });+ // \mathrm{d} produces an upright "d", wrapped by KaTeX in a `mathrm` span.+ expect(html).toContain("mathrm");+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex ac154bdf86..810874aefd 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -146,6 +146,15 @@ describe("CK config", () => {expect(languages).not.toContain("application-javascript-env-frontend");expect(languages).not.toContain("application-javascript-env-backend");});++ it("wires the MathLive→KaTeX compatibility macros into the math engine", async () => {+ const config = await buildConfig(baseOpts());++ const macros = (config.math as { katexRenderOptions?: { macros?: Record<string, string> } } | undefined)+ ?.katexRenderOptions?.macros;+ // Without this mapping, MathLive's \differentialD renders as raw error text (issue #9523).+ expect(macros?.["\\differentialD"]).toBe("\\mathrm{d}");+ });});describe("CK config - licensing", () => {diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex bfbbe7cdce..6e064717ec 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,6 +1,6 @@import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, TemplateDefinition } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";-import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";+import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import { copyTextWithToast } from "../../../services/clipboard_ext.js";import { t } from "../../../services/i18n.js";@@ -41,7 +41,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi(window as any).katex = (await import("../../../services/math.js")).default;},forceOutputType: false, // forces output to use outputType- enablePreview: true // Enable preview view+ enablePreview: true, // Enable preview view+ // Map MathLive-only commands (e.g. \differentialD) onto KaTeX equivalents so+ // formulas produced by the visual editor render instead of erroring out (#9523).+ katexRenderOptions: { macros: KATEX_MACROS }},mermaid: {lazyLoad: async () => (await import("mermaid")).default, // FIXMEdiff --git a/packages/ckeditor5-math/src/utils.ts b/packages/ckeditor5-math/src/utils.tsindex 05df08fcec..f93af7777c 100644--- a/packages/ckeditor5-math/src/utils.ts+++ b/packages/ckeditor5-math/src/utils.ts@@ -133,7 +133,8 @@ export async function renderEquation(katex.render( equation, el, {throwOnError: false,displayMode: display,- ...katexRenderOptions+ ...katexRenderOptions,+ ...normalizeKatexMacros( katexRenderOptions )} );}if ( preview ) {@@ -215,6 +216,18 @@ export function getBalloonPositionData( editor: Editor ): {}}+// CKEditor stores plain-object config values with a null prototype (`Object.create( null )`),+// but KaTeX calls `macros.hasOwnProperty()` directly while expanding macros, which throws on a+// prototype-less object. Rebuild `macros` as an ordinary object so the lookup works (this also+// hands KaTeX a disposable copy it can safely mutate, e.g. via `\gdef`).+function normalizeKatexMacros( options: KatexOptions ): { macros?: object } {+ const { macros } = options;+ if ( macros && typeof macros === 'object' ) {+ return { macros: { ...macros } };+ }+ return {};+}+function selectRenderMode(element: HTMLElement,preview: boolean,diff --git a/packages/ckeditor5-math/tests/utils.ts b/packages/ckeditor5-math/tests/utils.tsnew file mode 100644index 0000000000..09c31d9126--- /dev/null+++ b/packages/ckeditor5-math/tests/utils.ts@@ -0,0 +1,43 @@+import katex from 'katex';+import { renderEquation } from '../src/utils.js';+import { describe, beforeEach, afterEach, it, expect } from "vitest";++describe( 'renderEquation (KaTeX)', () => {+ let element: HTMLDivElement;+ const globalWithKatex = window as unknown as { katex: typeof katex | undefined };+ const originalKatex = globalWithKatex.katex;++ beforeEach( () => {+ // The lazy loader installs KaTeX on the global; renderEquation reads it from there.+ globalWithKatex.katex = katex;+ element = document.createElement( 'div' );+ document.body.appendChild( element );+ } );++ afterEach( () => {+ element.remove();+ globalWithKatex.katex = originalKatex;+ } );++ // Regression for #9523: CKEditor stores config objects with a null prototype+ // (`Object.create( null )`), and KaTeX calls `macros.hasOwnProperty()` directly while+ // expanding macros, which throws "hasOwnProperty is not a function" on such an object.+ it( 'renders with a prototype-less macros object (as produced by CKEditor config)', async () => {+ const macros = Object.assign( Object.create( null ), { '\\differentialD': '\\mathrm{d}' } );++ // Confirms the root cause: passing the raw null-prototype object straight to KaTeX throws.+ expect( () => katex.renderToString( '\\differentialD', { macros, throwOnError: true } ) ).to.throw();++ await renderEquation( '\\int f(x) \\differentialD x', element, 'katex', undefined, false, false, '', [], { macros } );++ // renderEquation normalizes the object, so the formula renders instead of erroring.+ expect( element.querySelector( '.katex' ) ).to.not.be.null;+ expect( element.textContent ?? '' ).to.not.contain( 'hasOwnProperty' );+ } );++ it( 'renders without any custom macros', async () => {+ await renderEquation( 'x^2', element, 'katex', undefined, false, false, '', [], {} );++ expect( element.querySelector( '.katex' ) ).to.not.be.null;+ } );+} );diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 6039ca8ca7..e7c407a104 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -1,4 +1,5 @@export * from "./lib/i18n.js";+export * from "./lib/katex_macros.js";export * from "./lib/options_interface.js";export * from "./lib/keyboard_actions_interface.js";export * from "./lib/hidden_subtree.js";diff --git a/packages/commons/src/lib/katex_macros.ts b/packages/commons/src/lib/katex_macros.tsnew file mode 100644index 0000000000..19e7fdbab7--- /dev/null+++ b/packages/commons/src/lib/katex_macros.ts@@ -0,0 +1,33 @@+/**+ * KaTeX macros that map commands emitted by the MathLive visual math editor+ * (used in the rich-text editor's math dialog) onto equivalents that KaTeX — the+ * engine Trilium uses to *render* math — actually understands.+ *+ * MathLive produces commands that are not part of KaTeX's command set, so without+ * these macros the formula renders as raw red error text. Defining them here means+ * both newly typed and already-stored formulas render correctly, regardless of how+ * the LaTeX was produced (visual editor, LaTeX textarea, paste, import or sync).+ *+ * This covers every command a user can trigger just by typing — MathLive's inline+ * shortcuts auto-insert `\differentialD` (`dx`/`dy`/`dt`), `\questeq` (`?=`) and+ * `\Colon` (`::`) — plus the rest of the ISO 80000-2 upright-operator family that+ * shares the same definition (`\exponentialE`, `\imaginaryI`, …). Upright operators+ * map to `\mathrm{…}` to match MathLive's own rendering. Obscure macros that only+ * appear when a user deliberately types them are intentionally not mirrored here.+ *+ * This list must be applied to every KaTeX render path: the rich-text editor+ * (`katexRenderOptions`), read-only note rendering, and the share theme.+ *+ * @see https://github.com/TriliumNext/Trilium/issues/9523+ */+export const KATEX_MACROS: Record<string, string> = {+ // ISO 80000-2 upright operators (mathlive MACROS table)+ "\\differentialD": "\\mathrm{d}",+ "\\capitalDifferentialD": "\\mathrm{D}",+ "\\exponentialE": "\\mathrm{e}",+ "\\imaginaryI": "\\mathrm{i}",+ "\\imaginaryJ": "\\mathrm{j}",+ // Relational shortcuts (mathlive inline shortcuts: `?=` and `::`)+ "\\questeq": "\\stackrel{?}{=}", // U+225F questioned-equal: "?" over "="+ "\\Colon": "\\dblcolon" // U+2237 proportion / double colon+};diff --git a/packages/share-theme/package.json b/packages/share-theme/package.jsonindex 6ef7ffa06d..229b73fe25 100644--- a/packages/share-theme/package.json+++ b/packages/share-theme/package.json@@ -24,6 +24,7 @@],"license": "Apache-2.0","dependencies": {+ "@triliumnext/commons": "workspace:*","fuse.js": "7.4.2","katex": "0.17.0","mermaid": "11.15.0"diff --git a/packages/share-theme/src/scripts/modules/math.ts b/packages/share-theme/src/scripts/modules/math.tsindex dadd92122d..6a8ad2e393 100644--- a/packages/share-theme/src/scripts/modules/math.ts+++ b/packages/share-theme/src/scripts/modules/math.ts@@ -1,3 +1,4 @@+import { KATEX_MACROS } from "@triliumnext/commons/src/lib/katex_macros.js";import "katex/dist/katex.min.css";export default async function setupMath() {@@ -13,6 +14,8 @@ export default async function setupMath() {if (!contentEl) return;// throwOnError: false renders invalid formulas as an inline red error instead of// throwing and leaving raw `$…$` text plus a console error (matches the editor).- renderMathInElement(contentEl, { throwOnError: false });+ // macros map MathLive-only commands (e.g. \differentialD) onto KaTeX equivalents.+ // Spread into a fresh object: KaTeX may mutate it (e.g. via `\gdef`).+ renderMathInElement(contentEl, { throwOnError: false, macros: { ...KATEX_MACROS } });document.body.classList.add("math-loaded");}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6518c9f19e..48ea775179 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1568,6 +1568,9 @@ importers:packages/share-theme:dependencies:+ '@triliumnext/commons':+ specifier: workspace:*+ version: link:../commonsfuse.js:specifier: 7.4.2version: 7.4.2