Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): convert Obsidian highlights & comments during rendering

Elian Doran8da6118dc483
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.ts
index 84d94771b6..eb1413a28f 100644
--- a/packages/commons/src/lib/markdown_renderer.spec.ts
+++ b/packages/commons/src/lib/markdown_renderer.spec.ts
@@ -455,6 +455,44 @@ describe("renderToHtml", () => {
});
});
+ describe("Obsidian syntax (obsidian option)", () => {
+ it("renders ==text== as a background-coloured span only when the obsidian flag is set", () => {
+ expect(render("==hi==", "", { obsidian: true }))
+ .toBe('<p><span style="background-color:hsl(60, 75%, 60%);">hi</span></p>');
+ // Off by default so generic Markdown is untouched.
+ expect(render("==hi==")).toBe("<p>==hi==</p>");
+ });
+
+ it("parses inner markdown inside a highlight", () => {
+ expect(render("==**bold**==", "", { obsidian: true }))
+ .toBe('<p><span style="background-color:hsl(60, 75%, 60%);"><strong>bold</strong></span></p>');
+ });
+
+ it("leaves ==== and spaced == as literal text", () => {
+ expect(render("====", "", { obsidian: true })).toBe("<p>====</p>");
+ expect(render("a == b", "", { obsidian: true })).toBe("<p>a == b</p>");
+ });
+
+ it("does not highlight == inside inline code", () => {
+ expect(render("`==x==`", "", { obsidian: true }))
+ .toBe('<p><code spellcheck="false">==x==</code></p>');
+ });
+
+ it("turns %% comment %% into an HTML comment only when the obsidian flag is set", () => {
+ expect(render("a %%secret%% b", "", { obsidian: true })).toBe("<p>a <!-- secret --> b</p>");
+ // Off by default so generic Markdown is untouched.
+ expect(render("a %%secret%% b")).toBe("<p>a %%secret%% b</p>");
+ });
+
+ it("handles a single-block comment spanning lines", () => {
+ expect(render("%%\nhidden\nnote\n%%", "", { obsidian: true })).toBe("<p><!-- hidden\nnote --></p>");
+ });
+
+ it("neutralises a comment terminator in the body so it cannot break out", () => {
+ expect(render("%%a-->b%%", "", { obsidian: true })).toBe("<p><!-- a-- >b --></p>");
+ });
+ });
+
describe("footnotes", () => {
it("renders footnotes without throwing", () => {
const html = render("text[^1]\n\n[^1]: note");
diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.ts
index 2e4d65694c..03521ff4bd 100644
--- a/packages/commons/src/lib/markdown_renderer.ts
+++ b/packages/commons/src/lib/markdown_renderer.ts
@@ -81,6 +81,8 @@ function createTaskStateDetector(states: TaskStateDef[]): (token: Token) => void
import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "./mime_type.js";
import {
+ createCommentExtension,
+ createHighlightExtension,
createTransclusionExtension,
createWikiLinkExtension,
transclusionExtension,
@@ -140,6 +142,13 @@ export interface RenderToHtmlOptions {
* (e.g. `[/]`) in list items. Defaults to {@link DEFAULT_TASK_STATES}.
*/
taskStates?: TaskStateDef[];
+ /**
+ * Enable Obsidian-specific Markdown syntax: `==highlight==` → `<mark>` and
+ * `%% comment %%` → an HTML comment. Off by default so generic Markdown import,
+ * paste and the live editor preview are unaffected — only the Obsidian importer
+ * opts in.
+ */
+ obsidian?: boolean;
}
function escapeHtml(str: string): string {
@@ -441,13 +450,15 @@ export function renderToHtml(content: string, title: string, options: RenderToHt
const marked = new Marked({ async: false, gfm: true });
marked.use(markedFootnote());
marked.use({ walkTokens: createTaskStateDetector(options.taskStates ?? DEFAULT_TASK_STATES) });
- marked.use({
- // Order is important, especially for wikilinks.
- extensions: [
- options.transclusion ? createTransclusionExtension(options.transclusion) : transclusionExtension,
- options.wikiLink ? createWikiLinkExtension(options.wikiLink) : wikiLinkExtension
- ]
- });
+ // Order is important, especially for wikilinks.
+ const extensions = [
+ options.transclusion ? createTransclusionExtension(options.transclusion) : transclusionExtension,
+ options.wikiLink ? createWikiLinkExtension(options.wikiLink) : wikiLinkExtension
+ ];
+ if (options.obsidian) {
+ extensions.push(createHighlightExtension(), createCommentExtension());
+ }
+ marked.use({ extensions });
const renderer = options.renderer ?? new CustomMarkdownRenderer({ async: false });
let html = marked.parse(processedText, { async: false, renderer }) as string;
diff --git a/packages/commons/src/lib/marked_extensions.ts b/packages/commons/src/lib/marked_extensions.ts
index 413a8220e4..be096692c6 100644
--- a/packages/commons/src/lib/marked_extensions.ts
+++ b/packages/commons/src/lib/marked_extensions.ts
@@ -1,4 +1,4 @@
-import type { TokenizerAndRendererExtension } from "marked";
+import type { Token, TokenizerAndRendererExtension } from "marked";
/**
* Escapes HTML special characters to prevent XSS attacks.
@@ -100,6 +100,85 @@ export function createTransclusionExtension(options: TransclusionOptions = {}):
};
}
+/**
+ * Background colour for imported highlights: CKEditor's default yellow highlight marker
+ * (Obsidian highlights carry no colour of their own). Matches the `<span
+ * style="background-color:…">` markup CKEditor's Font Background Color feature emits, so the
+ * imported highlight round-trips as an editable highlight.
+ */
+const HIGHLIGHT_BACKGROUND = "hsl(60, 75%, 60%)";
+
+/**
+ * Creates an extension for Obsidian-style highlights: `==text==` → a background-coloured
+ * `<span>`.
+ *
+ * Inner markdown is parsed so `==**bold**==` highlights bold text. A non-space is required
+ * just inside each `==` (like emphasis), so `a == b` and `====` stay literal.
+ */
+export function createHighlightExtension(): TokenizerAndRendererExtension {
+ return {
+ name: "highlight",
+ level: "inline",
+
+ start(src: string) {
+ return src.indexOf("==");
+ },
+
+ tokenizer(src) {
+ const match = /^==(?=\S)([\s\S]*?\S)==/.exec(src);
+ if (match) {
+ return {
+ type: "highlight",
+ raw: match[0],
+ text: match[1],
+ tokens: this.lexer.inlineTokens(match[1])
+ };
+ }
+ },
+
+ renderer(token) {
+ return `<span style="background-color:${HIGHLIGHT_BACKGROUND};">${this.parser.parseInline(token.tokens as Token[])}</span>`;
+ }
+ };
+}
+
+/**
+ * Creates an extension for Obsidian comments: `%% comment %%` → an HTML comment.
+ *
+ * Obsidian comments are hidden from the reader. They're emitted as real HTML comments
+ * (rather than left as literal `%%…%%` text) so the authoring intent survives in the raw
+ * HTML — note that Trilium's sanitizer and the CKEditor editor will subsequently drop
+ * them, which is fine. Both the inline (`%%hidden%%`) and single-block (`%%\n…\n%%`)
+ * forms are matched; any comment terminator in the body is neutralised so it can't break
+ * out of the comment.
+ */
+export function createCommentExtension(): TokenizerAndRendererExtension {
+ return {
+ name: "obsidianComment",
+ level: "inline",
+
+ start(src: string) {
+ return src.indexOf("%%");
+ },
+
+ tokenizer(src) {
+ const match = /^%%([\s\S]*?)%%/.exec(src);
+ if (match) {
+ return {
+ type: "obsidianComment",
+ raw: match[0],
+ text: match[1]
+ };
+ }
+ },
+
+ renderer(token) {
+ const body = (token.text as string).replace(/--!?>/g, "-- >").trim();
+ return `<!-- ${body} -->`;
+ }
+ };
+}
+
/** Pre-configured wiki-link extension for server-side (uses /noteId format) */
export const wikiLinkExtension = createWikiLinkExtension();
diff --git a/packages/trilium-core/src/services/import/markdown.ts b/packages/trilium-core/src/services/import/markdown.ts
index 970605934c..26bd3ae04c 100644
--- a/packages/trilium-core/src/services/import/markdown.ts
+++ b/packages/trilium-core/src/services/import/markdown.ts
@@ -3,10 +3,11 @@ import { renderToHtml as renderToHtmlShared } from "@triliumnext/commons/src/lib
import { sanitizeHtml } from "../sanitizer.js";
import { getTaskStates } from "../task_states.js";
-function renderToHtml(content: string, title: string): string {
+function renderToHtml(content: string, title: string, opts?: { obsidian?: boolean }): string {
return renderToHtmlShared(content, title, {
sanitize: sanitizeHtml,
- taskStates: getTaskStates()
+ taskStates: getTaskStates(),
+ obsidian: opts?.obsidian
});
}
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.ts
index e373123660..eecaf78edc 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
@@ -69,6 +69,17 @@ describe("Obsidian importer — integration", () => {
expect(decodeUtf8(welcome?.getContent() ?? "")).toBe("<p>This is your new <em>vault</em>.</p>");
});
+ it("converts ==highlights== to a coloured span and %%comments%% to dropped HTML comments", async () => {
+ const importRoot = await importObsidian({
+ "Note.md": "A ==highlight== and a %%hidden%% comment."
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Note");
+ // The highlight survives sanitization as a CKEditor background-colour span (the sanitizer drops the
+ // trailing semicolon); the comment is rendered as an HTML comment, which the sanitizer then strips.
+ expect(decodeUtf8(note?.getContent() ?? "")).toBe('<p>A <span style="background-color:hsl(60, 75%, 60%)">highlight</span> and a comment.</p>');
+ });
+
it("drops attachments, the .base/.canvas files and the .obsidian config folder", async () => {
const importRoot = await importObsidian({
"Note.md": "Body.",
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.ts
index 000a250831..ea30330bd0 100644
--- a/packages/trilium-core/src/services/import/obsidian/importer.ts
+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts
@@ -10,8 +10,11 @@
* folder* (so everything is nested under `Vault name/`). The location of `.obsidian/` pins the true vault
* root either way, so the redundant wrapper folder is stripped and the import root is named after the vault.
*
- * Deferred to later passes (so they currently render as literal text or placeholder links): wikilinks
- * `[[…]]`, embeds `![[…]]`, frontmatter → labels, tags, callouts, highlights/comments, and attachments.
+ * Obsidian-specific inline syntax is handled during Markdown rendering (gated by the `obsidian` flag):
+ * `==highlight==` becomes `<mark>` and `%% comment %%` becomes an HTML comment.
+ *
+ * Deferred to later passes (so they currently render as literal text or placeholder links): frontmatter →
+ * labels, tags, and callouts.
*
* Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged
* `format=obsidian`, so progress, completion and failure are reported by that dispatcher's TaskContext —
@@ -114,7 +117,7 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map
// attachments saved. Content is persisted once, in the link pass, to avoid a second write per note.
for (const vaultNote of notes) {
const parent = ensureFolder(parentFolder(vaultNote.path), rootNote, folderNotes, isProtected);
- const rendered = markdownService.renderToHtml(vaultNote.markdown, vaultNote.title);
+ const rendered = markdownService.renderToHtml(vaultNote.markdown, vaultNote.title, { obsidian: true });
const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: rendered, type: "text", mime: "text/html", isProtected });
// Attachments hang off the note, so this runs after creation; it returns the content with embedded