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(markdown): keep dollar amounts out of inline math (closes #5682)
Suliman Abdulrazzaqda8066076a05
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.tsindex a90cbe7a5b..7eec091b03 100644--- a/packages/commons/src/lib/markdown_renderer.spec.ts+++ b/packages/commons/src/lib/markdown_renderer.spec.ts@@ -586,6 +586,16 @@ describe("renderToHtml", () => {expect(render("$$e=mc^2$")).not.toContain("math-tex");});+ it("leaves dollar amounts as literal text (#5682)", () => {+ expect(render("An Avg cost of $15. Components cost $6 and $4 each."))+ .toBe("<p>An Avg cost of $15. Components cost $6 and $4 each.</p>");+ expect(render("Split $5,$10 between them")).toBe("<p>Split $5,$10 between them</p>");++ const html = render("The $4,000 grows to $7,414.40 by the formula $FV = PV (1 + i)$.");+ expect(html).toContain("The $4,000 grows to $7,414.40 by the formula ");+ expect(html).toContain('<span class="math-tex">\\(FV = PV (1 + i)\\)</span>');+ });+it("does not treat dollars in a blockquoted code block as formulas (#10268)", () => {// The fence lines carry a `> ` prefix, so the code block must still be shielded// from formula extraction — otherwise `${VAR} ${VAR2}` is mangled into a math span.diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex 1c61eba0c5..f33878f7af 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -332,13 +332,16 @@ function extractFormulas(text: string): { processedText: string; placeholderMap:// another `$` — and the body may not contain a `$`. This mirrors GitHub: mismatched// runs like `$$e=mc^2$` stay literal text rather than producing a malformed formula// (a stray `$` inside the body would otherwise crash KaTeX with "Can't use '$'").+ // As in Pandoc, an inline opening `$` is followed by a non-space character and the closing+ // `$` follows a non-space character and is not followed by a digit, so prices such as+ // `$15 and $6` stay literal text.let processedText = noCodeText.replace(/(?<![\\$])\$\$(?!\$)((?:(?!\n{2,})[^$])+?)\$\$(?!\$)/g, (_, formula: string) => {const key = `<!--FORMULA_BLOCK_${timestamp}_${id++}-->`;formulaMap.set(key, `<span class="math-tex">\\[${escapeMathFormula(formula)}\\]</span>`);return key;})- .replace(/(?<![\\$])\$(?!\$)([^$\n]+?)\$(?!\$)/g, (_, formula: string) => {+ .replace(/(?<![\\$])\$(?![\s$])([^$\n]*?[^\s$])\$(?![$\d])/g, (_, formula: string) => {const key = `<!--FORMULA_INLINE_${timestamp}_${id++}-->`;formulaMap.set(key, `<span class="math-tex">\\(${escapeMathFormula(formula)}\\)</span>`);return key;diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex 5e5aa5de2c..6a1f3ea4cd 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -511,6 +511,11 @@ describe("Markdown export", () => {expect(markdownExportService.toMarkdown(html)).toBe(expected);});+ it("trims the spaces inside inline math delimiters, so the import reads it back as math", () => {+ const html = /*html*/String.raw`<p>Area: <span class="math-tex">\( \pi r^2 \)</span></p>`;+ expect(markdownExportService.toMarkdown(html)).toBe(String.raw`Area: $\pi r^2$`);+ });+it("keeps a math expression without delimiters verbatim", () => {// Neither \( \) nor \[ \] — nothing can be inferred, so the raw text is passed through// rather than guessed into the wrong math mode.diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex 55cac236cb..0972271e95 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -444,9 +444,10 @@ function buildMathFilter(): Rule {// We have to use the raw HTML text, otherwise the content is escaped too much.const content = (node as HTMLElement).innerText;- // Inline math+ // Inline math. The import only reads `$…$` as math when no space touches a delimiter,+ // so the equation is trimmed, as CKEditor does when it loads one.if (content.startsWith(MATH_INLINE_PREFIX) && content.endsWith(MATH_INLINE_SUFFIX)) {- return `$${content.substring(MATH_INLINE_PREFIX.length, content.length - MATH_INLINE_SUFFIX.length)}$`;+ return `$${content.substring(MATH_INLINE_PREFIX.length, content.length - MATH_INLINE_SUFFIX.length).trim()}$`;}// Display mathdiff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.tsindex cc2f38c04a..cc5c8d962b 100644--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts@@ -486,6 +486,12 @@ describe("inline formulas", () => {expect(renderInlineText("Costs $5 today", [])).toBe("Costs $5 today");expect(renderInlineText("$$e=mc^2$", [])).toBe("$$e=mc^2$");});++ it("leaves dollar amounts as literal text next to a formula", () => {+ expect(renderInlineText("It costs $15, parts cost $6 and $4", [])).toBe("It costs $15, parts cost $6 and $4");+ expect(renderInlineText("$4,000 grows by $FV=PV$", []))+ .toBe('$4,000 grows by <span class="math-tex">\\( FV=PV \\)</span>');+ });});describe("inline mentions", () => {diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.tsindex 807ffe4de4..8835d65cd6 100644--- a/packages/trilium-core/src/services/import/anytype/content.ts+++ b/packages/trilium-core/src/services/import/anytype/content.ts@@ -526,10 +526,12 @@ export function renderLatexBlock(text: string, processor: string | undefined): s* Finds the inline-math runs in a text block. Anytype carries an inline formula as literal `$…$` (inline) or* `$$…$$` (display) text with no mark. The delimiter rules mirror Trilium's markdown renderer: a delimiter* `$`/`$$` may not sit next to another `$` (so `${VAR}` and mismatched `$$x$` stay literal) and the body may- * not contain a `$` or a blank line. Ranges are returned in document order with their original offsets.+ * not contain a `$` or a blank line. An inline `$` pair also needs a non-space character inside each+ * delimiter and no digit after the closing one, so prices such as `$15 and $6` stay literal. Ranges are+ * returned in document order with their original offsets.*/function splitInlineFormulas(text: string): { from: number; to: number; body: string; display: boolean }[] {- const pattern = /(?<![\\$])\$\$(?!\$)((?:(?!\n{2,})[^$])+?)\$\$(?!\$)|(?<![\\$])\$(?!\$)([^$\n]+?)\$(?!\$)/g;+ const pattern = /(?<![\\$])\$\$(?!\$)((?:(?!\n{2,})[^$])+?)\$\$(?!\$)|(?<![\\$])\$(?![\s$])([^$\n]*?[^\s$])\$(?![$\d])/g;const formulas: { from: number; to: number; body: string; display: boolean }[] = [];for (const match of text.matchAll(pattern)) {const display = match[1] !== undefined;diff --git a/packages/trilium-core/src/services/import/markdown.spec.ts b/packages/trilium-core/src/services/import/markdown.spec.tsindex 0a9328a92d..617926af95 100644--- a/packages/trilium-core/src/services/import/markdown.spec.ts+++ b/packages/trilium-core/src/services/import/markdown.spec.ts@@ -286,6 +286,12 @@ $$`;<pre><code class="language-text-x-trilium-auto">$$a+b$$</code></pre>`);});+ it("imports dollar amounts as literal text (#5682)", () => {+ const input = `Assembled Item A has an Avg cost of $15. A Raw Material has an Avg cost of $6.`;+ const expected = /*html*/`<p>Assembled Item A has an Avg cost of $15. A Raw Material has an Avg cost of $6.</p>`;+ expect(markdownService.renderToHtml(input, "Title")).toStrictEqual(expected);+ });+it("converts specific inline math expression into Mathtex format", () => {const input = `This is a formula: $\\mathcal{L}_{task} + \\mathcal{L}_{od}$ inside a sentence.`;const expected = /*html*/`<p>This is a formula: <span class="math-tex">\\(\\mathcal{L}_{task} + \\mathcal{L}_{od}\\)</span> inside a sentence.</p>`;