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
feat(import): map Obsidian callouts to admonitions
Elian Doranfa78a33f57da
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.tsindex eb1413a28f..f0e783f2e2 100644--- a/packages/commons/src/lib/markdown_renderer.spec.ts+++ b/packages/commons/src/lib/markdown_renderer.spec.ts@@ -381,6 +381,56 @@ describe("renderToHtml", () => {it("renders a plain blockquote", () => {expect(render("> just quote")).toBe("<blockquote><p>just quote</p></blockquote>");});++ it("matches the admonition type case-insensitively (Obsidian uses lowercase)", () => {+ expect(render("> [!note]\n> body")).toBe('<aside class="admonition note"><p>body</p></aside>');+ });++ describe("Obsidian callouts (obsidian: true)", () => {+ it("maps extended callout types to the nearest Trilium admonition type", () => {+ const obsidian = { obsidian: true };+ expect(render("> [!success]\n> done", "", obsidian))+ .toBe('<aside class="admonition tip"><p>done</p></aside>');+ expect(render("> [!question]\n> q", "", obsidian))+ .toBe('<aside class="admonition tip"><p>q</p></aside>');+ expect(render("> [!danger]\n> bad", "", obsidian))+ .toBe('<aside class="admonition caution"><p>bad</p></aside>');+ expect(render("> [!info]\n> i", "", obsidian))+ .toBe('<aside class="admonition note"><p>i</p></aside>');+ expect(render("> [!example]\n> e", "", obsidian))+ .toBe('<aside class="admonition important"><p>e</p></aside>');+ });++ it("renders an inline custom title as a bold lead paragraph", () => {+ expect(render("> [!note] Custom Title\n> body", "", { obsidian: true }))+ .toBe('<aside class="admonition note"><p><strong>Custom Title</strong></p><p>body</p></aside>');+ });++ it("supports a title separated from the body by a blank line", () => {+ expect(render("> [!tip] Heads up\n>\n> body", "", { obsidian: true }))+ .toBe('<aside class="admonition tip"><p><strong>Heads up</strong></p><p>body</p></aside>');+ });++ it("drops the fold marker (+/-) while keeping the title", () => {+ expect(render("> [!note]- Folded\n> body", "", { obsidian: true }))+ .toBe('<aside class="admonition note"><p><strong>Folded</strong></p><p>body</p></aside>');+ expect(render("> [!note]+\n> body", "", { obsidian: true }))+ .toBe('<aside class="admonition note"><p>body</p></aside>');+ });++ it("keeps an unknown callout type as a plain blockquote", () => {+ const html = render("> [!frobnicate]\n> body", "", { obsidian: true });+ expect(html).toContain("<blockquote>");+ expect(html).not.toContain("admonition");+ });+ });++ it("does not treat extended Obsidian callout types as admonitions without the obsidian flag", () => {+ const html = render("> [!success]\n> x");+ expect(html).toContain("<blockquote>");+ expect(html).not.toContain("admonition");+ expect(html).toContain("[!success]");+ });});describe("formulas", () => {diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex 03521ff4bd..b49c4b4fa6 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -1,4 +1,4 @@-import { Marked, Renderer, type Token, type Tokens } from "marked";+import { Marked, type MarkedOptions, Renderer, type Token, type Tokens } from "marked";import markedFootnote from "marked-footnote";import { DEFAULT_TASK_STATES, type TaskStateDef } from "./task_states.js";@@ -104,6 +104,46 @@ export const ADMONITION_TYPE_MAPPINGS: Record<string, string> = {warning: "WARNING"};+/**+ * Obsidian ships a much larger set of callout types than the five admonition+ * types Trilium's editor supports. Each extra type (and its Obsidian aliases) is+ * mapped onto the nearest native type. Types that already share a name with a+ * native type (`note`, `tip`, `important`, `caution`, `warning`) are handled by+ * {@link ADMONITION_TYPE_MAPPINGS} and intentionally omitted here.+ *+ * Only consulted when the `obsidian` option is enabled — generic Markdown import+ * keeps GitHub's five-type behaviour.+ */+export const OBSIDIAN_CALLOUT_ALIASES: Record<string, string> = {+ // Neutral / informational+ abstract: "note",+ summary: "note",+ tldr: "note",+ info: "note",+ todo: "note",+ quote: "note",+ cite: "note",+ // Advice / positive outcomes+ hint: "tip",+ success: "tip",+ check: "tip",+ done: "tip",+ question: "tip",+ help: "tip",+ faq: "tip",+ // Emphasis+ example: "important",+ // Mild warnings+ attention: "warning",+ // Errors / severe warnings+ failure: "caution",+ fail: "caution",+ missing: "caution",+ danger: "caution",+ error: "caution",+ bug: "caution"+};+/** Options for {@link renderToHtml}. */export interface RenderToHtmlOptions {/**@@ -324,6 +364,14 @@ function restoreFromMap(text: string, map: Map<string, string>): string {*/export class CustomMarkdownRenderer extends Renderer {+ /** Whether to recognise Obsidian's extended callout types, inline titles and fold markers. */+ readonly #obsidianCallouts: boolean;++ constructor(options?: MarkedOptions & { obsidianCallouts?: boolean }) {+ super(options);+ this.#obsidianCallouts = options?.obsidianCallouts ?? false;+ }+override heading(data: Tokens.Heading): string {if (data.depth === 1) {return `<h1>${data.text}</h1>`;@@ -413,24 +461,68 @@ export class CustomMarkdownRenderer extends Renderer {override blockquote({ tokens }: Tokens.Blockquote): string {const body = this.parser.parse(tokens);- const admonitionMatch = /^<p>\[\!([A-Z]+)\]/.exec(body);- if (Array.isArray(admonitionMatch) && admonitionMatch.length === 2) {- const type = admonitionMatch[1].toLowerCase();+ const callout = this.#parseCallout(body);+ if (callout) {+ // Trilium admonitions have no dedicated title slot, so an Obsidian inline+ // title is rendered as a bold lead paragraph.+ const titleHtml = callout.title ? `<p><strong>${callout.title}</strong></p>` : "";+ // Empty admonition (`> [!NOTE]` with no body) — keep a non-breaking space+ // so the callout still renders its title/icon row instead of collapsing.+ const inner = (titleHtml + callout.body) || " ";+ return `<aside class="admonition ${callout.type}">${inner}</aside>`;+ }- if (ADMONITION_TYPE_MAPPINGS[type]) {- const bodyWithoutHeader = body- .replace(/^<p>\[\!([A-Z]+)\]\s*/, "<p>")- .replace(/^<p><\/p>/, "")- .trim();+ return `<blockquote>${body}</blockquote>`;+ }- // Empty admonition (`> [!NOTE]` with no body) — keep a non-breaking space- // so the callout still renders its title/icon row instead of collapsing.- const inner = bodyWithoutHeader || " ";- return `<aside class="admonition ${type}">${inner}</aside>`;- }+ /**+ * Detects a `[!type]` callout at the start of a rendered blockquote. Matches the+ * type case-insensitively, drops Obsidian's fold marker (`+`/`-`), and splits off+ * an optional inline title from the body. Returns `null` for plain blockquotes and+ * for callout types that don't resolve to a supported admonition.+ */+ #parseCallout(body: string): { type: string; title: string; body: string } | null {+ const marker = /^<p>\[!([a-zA-Z]+)\]([-+]?)[ \t]*/.exec(body);+ if (!marker) {+ return null;}- return `<blockquote>${body}</blockquote>`;+ const type = this.#resolveAdmonitionType(marker[1].toLowerCase());+ if (!type) {+ return null;+ }++ const rest = body.slice(marker[0].length);+ const newlineIdx = rest.indexOf("\n");+ const paragraphEndIdx = rest.indexOf("</p>");++ let title: string;+ let inner: string;+ if (paragraphEndIdx !== -1 && (newlineIdx === -1 || paragraphEndIdx < newlineIdx)) {+ // The marker paragraph holds only an (optional) title; the body follows it.+ title = rest.slice(0, paragraphEndIdx);+ inner = rest.slice(paragraphEndIdx + "</p>".length);+ } else if (newlineIdx !== -1) {+ // A soft line break splits the title from the body within the marker paragraph.+ title = rest.slice(0, newlineIdx);+ inner = `<p>${rest.slice(newlineIdx + 1)}`;+ } else {+ title = rest;+ inner = "";+ }++ return { type, title: title.trim(), body: inner.trim() };+ }++ /** Resolves a lowercase callout keyword to a supported admonition type, or `null`. */+ #resolveAdmonitionType(type: string): string | null {+ if (ADMONITION_TYPE_MAPPINGS[type]) {+ return type;+ }+ if (this.#obsidianCallouts) {+ return OBSIDIAN_CALLOUT_ALIASES[type] ?? null;+ }+ return null;}override codespan({ text }: Tokens.Codespan): string {@@ -460,7 +552,7 @@ export function renderToHtml(content: string, title: string, options: RenderToHt}marked.use({ extensions });- const renderer = options.renderer ?? new CustomMarkdownRenderer({ async: false });+ const renderer = options.renderer ?? new CustomMarkdownRenderer({ async: false, obsidianCallouts: options.obsidian });let html = marked.parse(processedText, { async: false, renderer }) as string;html = restoreFromMap(html, formulaMap);diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.tsindex f3052603e3..dc0dc9c974 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -76,6 +76,16 @@ describe("Obsidian importer — integration", () => {expect(decodeUtf8(welcome?.getContent() ?? "")).toBe("<p>This is your new <em>vault</em>.</p>");});+ it("renders an Obsidian callout (with fold marker and custom title) as an admonition", async () => {+ const importRoot = await importObsidian({+ "Note.md": "> [!success]- Nicely done\n> It worked."+ });++ const note = importRoot.getChildNotes().find((n) => n.title === "Note");+ expect(decodeUtf8(note?.getContent() ?? ""))+ .toBe('<aside class="admonition tip"><p><strong>Nicely done</strong></p><p>It worked.</p></aside>');+ });+it("imports front matter properties as camelCased labels and strips the block from the note body", async () => {// Modeled on the vault's "Files with properties" note.const importRoot = await importObsidian({