Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/anytype): render inline $…$ formulas as CKEditor math

Elian Doran4872dc90586b
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.ts
index 0be04b0cd8..5e3992f358 100644
--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts
@@ -334,6 +334,40 @@ describe("renderInlineText", () => {
});
});
+describe("inline formulas", () => {
+ it("converts an inline $…$ formula to a CKEditor inline math span (the real exported paragraph)", () => {
+ // Verbatim from the sample page: Anytype stores an inline formula as literal `$…$` text, no marks.
+ expect(renderInlineText("Inline formula: $e=mc^2$", [])).toBe('Inline formula: <span class="math-tex">\\( e=mc^2 \\)</span>');
+ });
+
+ it("renders the inline formula inside its paragraph through parseObject", () => {
+ const doc = listDoc(["p1"], [{ id: "p1", text: { text: "Inline formula: $e=mc^2$", style: "Paragraph", marks: { marks: [] } } }]);
+ expect(parseObject(doc).content).toBe('<p>Inline formula: <span class="math-tex">\\( e=mc^2 \\)</span></p>');
+ });
+
+ it("converts a $$…$$ run to a display math span", () => {
+ expect(renderInlineText("see $$a+b$$ done", [])).toBe('see <span class="math-tex">\\[ a+b \\]</span> done');
+ });
+
+ it("renders several formulas in one line", () => {
+ expect(renderInlineText("$x$ and $y$", [])).toBe('<span class="math-tex">\\( x \\)</span> and <span class="math-tex">\\( y \\)</span>');
+ });
+
+ it("escapes HTML inside the formula body so it can't inject markup", () => {
+ expect(renderInlineText("$a<b & c$", [])).toBe('<span class="math-tex">\\( a&lt;b &amp; c \\)</span>');
+ });
+
+ it("still applies inline marks to the text surrounding a formula", () => {
+ // Bold over "Mass" [0,4), formula follows untouched.
+ expect(renderInlineText("Mass: $e=mc^2$", [mark(0, 4, "Bold")])).toBe('<strong>Mass</strong>: <span class="math-tex">\\( e=mc^2 \\)</span>');
+ });
+
+ it("leaves a lone or mismatched $ as literal text", () => {
+ expect(renderInlineText("Costs $5 today", [])).toBe("Costs $5 today");
+ expect(renderInlineText("$$e=mc^2$", [])).toBe("$$e=mc^2$");
+ });
+});
+
describe("inline mentions", () => {
/** A resolver that maps any non-"missing" id to a note, so a Mention resolves unless it's "missing". */
const resolve: LinkResolver = (cid) => (cid === "missing" ? undefined : { noteId: `note-${cid}`, title: `Title ${cid}` });
diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.ts
index 81fd5b44c9..d7f59a8d89 100644
--- a/packages/trilium-core/src/services/import/anytype/content.ts
+++ b/packages/trilium-core/src/services/import/anytype/content.ts
@@ -278,8 +278,41 @@ interface AppliedMark {
* surfaced via `onLink` so the caller records the `internalLink` relation; an unresolved mention (or no
* resolver — parsing in isolation) leaves the text plain. Emoji are ignored, leaving their text as plain
* (escaped) content.
+ *
+ * Inline math is handled first: Anytype stores an inline formula as literal `$…$` (or display `$$…$$`) text
+ * with no mark, so {@link splitInlineFormulas} peels those runs out and emits them as CKEditor math spans —
+ * the surrounding text (and any marks over it) is rendered normally around them.
*/
export function renderInlineText(text: string, marks: AnytypeMark[], resolveLink?: LinkResolver, onLink?: (noteId: string) => void): string {
+ const formulas = splitInlineFormulas(text);
+ if (formulas.length === 0) {
+ return renderMarkedText(text, marks, resolveLink, onLink);
+ }
+
+ // Render the non-formula slices (with their marks, offset back to local coordinates) interleaved with the
+ // math spans, in document order.
+ let html = "";
+ let cursor = 0;
+ const renderSlice = (start: number, end: number) => {
+ if (end <= start) {
+ return;
+ }
+ const sliceMarks = marks
+ .map((m) => ({ ...m, range: { from: (m.range?.from ?? 0) - start, to: (m.range?.to ?? 0) - start } }))
+ .filter((m) => m.range.to > 0 && m.range.from < end - start);
+ html += renderMarkedText(text.slice(start, end), sliceMarks, resolveLink, onLink);
+ };
+ for (const formula of formulas) {
+ renderSlice(cursor, formula.from);
+ html += renderInlineFormula(formula.body, formula.display);
+ cursor = formula.to;
+ }
+ renderSlice(cursor, text.length);
+ return html;
+}
+
+/** Renders a text run's inline marks to HTML (no formula handling — {@link renderInlineText} peels those off first). */
+function renderMarkedText(text: string, marks: AnytypeMark[], resolveLink?: LinkResolver, onLink?: (noteId: string) => void): string {
const length = text.length;
// Keep only marks we render (known structural kind, a known colour name, or a resolvable mention link),
@@ -434,6 +467,28 @@ export function renderLatexBlock(text: string, processor: string | undefined): s
}
return `<span class="math-tex">\\[ ${escaped} \\]</span>`;
}
+
+/**
+ * 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.
+ */
+function splitInlineFormulas(text: string): { from: number; to: number; body: string; display: boolean }[] {
+ const pattern = /(?<![\\$])\$\$(?!\$)((?:(?!\n{2,})[^$])+?)\$\$(?!\$)|(?<![\\$])\$(?!\$)([^$\n]+?)\$(?!\$)/g;
+ const formulas: { from: number; to: number; body: string; display: boolean }[] = [];
+ for (const match of text.matchAll(pattern)) {
+ const display = match[1] !== undefined;
+ formulas.push({ from: match.index, to: match.index + match[0].length, body: display ? match[1] : match[2], display });
+ }
+ return formulas;
+}
+
+/** Renders one inline formula as a CKEditor math span (display `\[ … \]` or inline `\( … \)`), body escaped. */
+function renderInlineFormula(body: string, display: boolean): string {
+ const escaped = escapeHtml(body).replace(/&quot;/g, '"');
+ return display ? `<span class="math-tex">\\[ ${escaped} \\]</span>` : `<span class="math-tex">\\( ${escaped} \\)</span>`;
+}
// #endregion
// #region Tables