Skip to content

Build your personal knowledge base with Trilium Notes

feat(markdown): preserve non-default text colours through Markdown export

Elian Doranf5006c805997
diff --git a/apps/client/src/widgets/sidebar/HighlightsList.spec.ts b/apps/client/src/widgets/sidebar/highlights_extract.spec.ts
similarity index 100%
rename from apps/client/src/widgets/sidebar/HighlightsList.spec.ts
rename to apps/client/src/widgets/sidebar/highlights_extract.spec.ts
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
index bb1d8d0221..7cda45f5dc 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
@@ -250,4 +250,10 @@ describe("renderWithSourceLines", () => {
expect(html("==hi==")).toBe('<p><span style="background-color:hsl(60, 75%, 60%);">hi</span></p>');
expect(html("a == b")).toBe("<p>a == b</p>");
});
+
+ it("renders a colour the exporter preserved as inline HTML", () => {
+ // Non-default colours survive a Markdown export as a span, so the preview has to show them.
+ expect(html(`a <span style="color:#ff0000">**red**</span> b`))
+ .toBe(`<p>a <span style="color:#ff0000"><strong>red</strong></span> b</p>`);
+ });
});
diff --git a/packages/commons/src/lib/marked_extensions.ts b/packages/commons/src/lib/marked_extensions.ts
index 4cc054f92b..5fa6d228d0 100644
--- a/packages/commons/src/lib/marked_extensions.ts
+++ b/packages/commons/src/lib/marked_extensions.ts
@@ -101,13 +101,17 @@ export function createTransclusionExtension(options: TransclusionOptions = {}):
}
/**
- * Background colour for highlights: CKEditor's default yellow highlight marker (`==…==`
- * carries no colour of its own). Matches the `<span style="background-color:…">` markup
- * CKEditor's Font Background Color feature emits, so a highlight rendered into a text note
- * round-trips as an editable highlight. Deliberately not `<mark>`: the editor has no
- * Highlight plugin, so it would drop the element on the next edit.
+ * Background colour for highlights: CKEditor's stock palette yellow (`==…==` carries no colour
+ * of its own). Matches the `<span style="background-color:…">` markup CKEditor's Font
+ * Background Color feature emits, so a highlight rendered into a text note round-trips as an
+ * editable highlight. Deliberately not `<mark>`: the editor has no Highlight plugin, so it
+ * would drop the element on the next edit.
+ *
+ * The Markdown exporter compares against this to decide which highlights can collapse back to
+ * `==…==` and which have to keep their colour as inline HTML, so the two directions must agree
+ * on the exact value.
*/
-const HIGHLIGHT_BACKGROUND = "hsl(60, 75%, 60%)";
+export const HIGHLIGHT_BACKGROUND = "hsl(60, 75%, 60%)";
/**
* Creates an extension for highlights: `==text==` → a background-coloured `<span>`.
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.ts
index 5f1e41ead3..5392ba602f 100644
--- a/packages/trilium-core/src/services/export/markdown.spec.ts
+++ b/packages/trilium-core/src/services/export/markdown.spec.ts
@@ -772,43 +772,76 @@ describe("Markdown export", () => {
expect(markdownExportService.toMarkdown(html)).toBe(expected);
});
- describe("highlights", () => {
- it("renders a background-coloured span and a <mark> as ==text==", () => {
+ describe("highlights and coloured text", () => {
+ it("renders a default-yellow highlight and a bare <mark> as ==text==", () => {
expect(markdownExportService.toMarkdown(
/*html*/`<p>A <span style="background-color:hsl(60, 75%, 60%);">highlight</span> here.</p>`
)).toBe("A ==highlight== here.");
- // Whatever the colour, and however the style attribute is spelled.
+ // The same colour however the sanitizer or the editor spaced it out.
expect(markdownExportService.toMarkdown(
- /*html*/`<p><span style="color:#ff0000;background-color:rgb(0, 255, 0)">green</span></p>`
- )).toBe("==green==");
+ /*html*/`<p><span style="BACKGROUND-COLOR: hsl(60,75%,60%)">highlight</span></p>`
+ )).toBe("==highlight==");
expect(markdownExportService.toMarkdown(/*html*/`<p>A <mark>highlight</mark> here.</p>`))
.toBe("A ==highlight== here.");
});
+ it("keeps any other colour as inline HTML rather than repainting it yellow", () => {
+ // A different background colour...
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p>A <span style="background-color:rgb(0, 255, 0)">green</span> one.</p>`
+ )).toBe(`A <span style="background-color:rgb(0, 255, 0)">green</span> one.`);
+
+ // ...a foreground colour, which used to be dropped entirely...
+ expect(markdownExportService.toMarkdown(/*html*/`<p><span style="color:#ff0000">red</span></p>`))
+ .toBe(`<span style="color:#ff0000">red</span>`);
+
+ // ...and both at once.
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p><span style="color:#ffffff;background-color:#000000">both</span></p>`
+ )).toBe(`<span style="color:#ffffff;background-color:#000000">both</span>`);
+
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<mark style="background-color:rgb(0, 255, 0)">green</mark>`
+ )).toBe(`<mark style="background-color:rgb(0, 255, 0)">green</mark>`);
+ });
+
+ it("keeps a default-yellow highlight whole when it carries anything ==…== cannot", () => {
+ // A second declaration would be lost by `==…==`, so the element is kept as-is.
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p><span style="background-color:hsl(60, 75%, 60%);font-family:serif">y</span></p>`
+ )).toBe(`<span style="background-color:hsl(60, 75%, 60%);font-family:serif">y</span>`);
+
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p><span class="tag" style="background-color:hsl(60, 75%, 60%)">y</span></p>`
+ )).toBe(`<span class="tag" style="background-color:hsl(60, 75%, 60%)">y</span>`);
+ });
+
+ it("converts the content to Markdown inside a preserved colour", () => {
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p><span style="color:#ff0000"><strong>bold</strong> and <em>italic</em></span></p>`
+ )).toBe(`<span style="color:#ff0000">**bold** and _italic_</span>`);
+ });
+
it("keeps inline formatting inside and around a highlight", () => {
expect(markdownExportService.toMarkdown(
- /*html*/`<p><span style="background-color:yellow"><strong>bold</strong></span></p>`
+ /*html*/`<p><span style="background-color:hsl(60, 75%, 60%)"><strong>bold</strong></span></p>`
)).toBe("==**bold**==");
expect(markdownExportService.toMarkdown(
- /*html*/`<p><strong><span style="background-color:yellow">bold</span></strong></p>`
+ /*html*/`<p><strong><span style="background-color:hsl(60, 75%, 60%)">bold</span></strong></p>`
)).toBe("**==bold==**");
});
it("hoists whitespace out of the delimiters so the result parses back", () => {
expect(markdownExportService.toMarkdown(
- /*html*/`<p>a<span style="background-color:yellow"> hi </span>b</p>`
+ /*html*/`<p>a<span style="background-color:hsl(60, 75%, 60%)"> hi </span>b</p>`
)).toBe("a ==hi== b");
});
- it("leaves a font colour, a coloured block and a highlighted formula alone", () => {
- // `color` without a background is a font colour, not a highlight.
- expect(markdownExportService.toMarkdown(/*html*/`<p><span style="color:#ff0000">red</span></p>`))
- .toBe("red");
-
- // Only inline highlights are representable; a coloured block would wrap its whole text.
+ it("leaves a coloured block and a highlighted formula alone", () => {
+ // Only inline colours are handled; a coloured block would wrap its whole text.
expect(markdownExportService.toMarkdown(/*html*/`<p style="background-color:yellow">para</p>`))
.toBe("para");
@@ -817,9 +850,16 @@ describe("Markdown export", () => {
)).toBe("$x^2$");
});
+ it("ignores a border colour, which is not a text colour", () => {
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p><span style="border-color:#ff0000">plain</span></p>`
+ )).toBe("plain");
+ });
+
it("emits no delimiters for a highlight with no text of its own", () => {
- expect(markdownExportService.toMarkdown(/*html*/`<p>a<span style="background-color:yellow"><br></span>b</p>`))
- .not.toContain("==");
+ expect(markdownExportService.toMarkdown(
+ /*html*/`<p>a<span style="background-color:hsl(60, 75%, 60%)"><br></span>b</p>`
+ )).not.toContain("==");
});
it("does not touch == inside a code block", () => {
diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.ts
index 673fa10f00..5a624ea5e2 100644
--- a/packages/trilium-core/src/services/export/markdown.ts
+++ b/packages/trilium-core/src/services/export/markdown.ts
@@ -1,5 +1,6 @@
import { safeLinkPreviewHref, type TaskStateDef } from "@triliumnext/commons";
import { ADMONITION_TYPE_MAPPINGS } from "@triliumnext/commons/src/lib/markdown_renderer.js";
+import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons/src/lib/marked_extensions.js";
import { gfm, serializeStructuralHtml } from "@triliumnext/turndown-plugin-gfm";
import escapeHtml from "escape-html";
import { parse as parseHtml } from "node-html-parser";
@@ -412,33 +413,95 @@ function buildMathFilter(): Rule {
}
/**
- * `==text==` for highlighted text, in both shapes it reaches the exporter: CKEditor's Font
- * Background Color emits `<span style="background-color:…">`, and `<mark>` arrives from pasted
- * or imported HTML. Neither has a rule of its own, so without this the wrapper is dropped and
- * only the text survives — the highlight is silently lost on export.
+ * Coloured inline text, in every shape it reaches the exporter: CKEditor's Font Color and Font
+ * Background Color emit `<span style="color:…">` / `<span style="background-color:…">`, and
+ * `<mark>` arrives from pasted or imported HTML. None has a rule of its own, so without this
+ * the wrapper is dropped and only the text survives — the colour is silently lost on export.
*
- * Markdown cannot express *which* colour, so every colour collapses to a plain highlight and
- * re-imports as the default yellow. A font colour (`color:` with no background) is not a
- * highlight and is deliberately left alone.
+ * A *plain default-yellow* highlight collapses to `==text==`: that is the colour `==…==`
+ * imports to and CKEditor's stock Yellow, so the syntax survives a round-trip unchanged. Every
+ * other colour is kept as inline HTML, which Markdown passes through and the importer accepts
+ * verbatim — lossless, where `==…==` would silently repaint it yellow.
+ *
+ * "Plain" means the element carries nothing else that `==…==` cannot express: no second
+ * declaration, no class. Anything more and the element is kept whole rather than partly lost.
+ * The content is Markdown either way, since Markdown inside an inline tag is still parsed.
*/
function buildHighlightFilter(): Rule {
+ // Only a `color`/`background-color` declaration of its own — `border-color` and friends have
+ // a `-` before "color" rather than the start of the attribute or a `;`.
+ const COLOR_DECLARATION = /(?:^|;)\s*(?:background-)?color\s*:/i;
+
return {
filter(node) {
- if (node.nodeName === "MARK") {
- return true;
- }
-
- return node.nodeName === "SPAN"
- && /(?:^|;)\s*background-color\s*:/i.test(node.getAttribute("style") ?? "");
+ return node.nodeName === "MARK"
+ || (node.nodeName === "SPAN" && COLOR_DECLARATION.test(node.getAttribute("style") ?? ""));
},
- replacement(content: string) {
+ replacement(content: string, node: HTMLElement) {
// Turnish hoists flanking whitespace out of the delimiters, but an element whose only
// content is a `<br>` still lands here; `== ==` would not parse back as a highlight.
- return content.trim() ? `==${content}==` : content;
+ if (!content.trim()) {
+ return content;
+ }
+
+ if (isPlainDefaultHighlight(node)) {
+ return `==${content}==`;
+ }
+
+ const attributes = Array.from(node.attributes)
+ .map((attribute) => ` ${attribute.name}="${escapeHtml(attribute.value)}"`)
+ .join("");
+ const tag = node.nodeName.toLowerCase();
+
+ return `<${tag}${attributes}>${content}</${tag}>`;
}
};
}
+/** Whether the element is a highlight in the default colour and carries nothing else. */
+function isPlainDefaultHighlight(node: HTMLElement): boolean {
+ if (Array.from(node.attributes).some((attribute) => attribute.name !== "style")) {
+ return false;
+ }
+
+ const declarations = parseStyleDeclarations(node.getAttribute("style"));
+
+ // A bare `<mark>` is a highlight with no colour of its own; a span always has a declaration,
+ // since that is what the filter matched on.
+ if (declarations.length === 0) {
+ return true;
+ }
+
+ if (declarations.length > 1) {
+ return false;
+ }
+
+ const [ declaration ] = declarations;
+
+ return declaration.property === "background-color"
+ && normalizeColor(declaration.value) === normalizeColor(HIGHLIGHT_BACKGROUND);
+}
+
+function parseStyleDeclarations(style: string | null) {
+ return (style ?? "")
+ .split(";")
+ .map((declaration) => declaration.trim())
+ .filter((declaration) => declaration.length > 0)
+ .map((declaration) => {
+ const [ property, ...value ] = declaration.split(":");
+
+ return {
+ property: property.trim().toLowerCase(),
+ value: value.join(":").trim()
+ };
+ });
+}
+
+/** Colours are compared ignoring case and the spacing browsers and sanitizers move around. */
+function normalizeColor(color: string) {
+ return color.replace(/\s+/g, "").toLowerCase();
+}
+
// Taken from upstream since it's not exposed.
// https://github.com/mixmark-io/turndown/blob/master/src/commonmark-rules.js
function cleanAttribute(attribute: string | null | undefined) {
diff --git a/packages/trilium-core/src/services/note_format_conversion.spec.ts b/packages/trilium-core/src/services/note_format_conversion.spec.ts
index c0cd4d2f9e..f333216788 100644
--- a/packages/trilium-core/src/services/note_format_conversion.spec.ts
+++ b/packages/trilium-core/src/services/note_format_conversion.spec.ts
@@ -60,15 +60,25 @@ describe("note format conversion", () => {
expect(convertNoteContent("html", html, "title").content).toBe(original);
});
- it("preserves a highlight applied in the editor across an HTML -> Markdown -> HTML round-trip", () => {
- // Any highlight colour collapses to the default yellow, since Markdown cannot carry one.
- const original = '<p>Some <span style="background-color:rgb(0, 255, 0);">highlighted</span> text.</p>';
+ it("preserves a default-yellow highlight applied in the editor across an HTML -> Markdown -> HTML round-trip", () => {
+ const original = '<p>Some <span style="background-color:hsl(60, 75%, 60%)">highlighted</span> text.</p>';
const { content: markdown } = convertNoteContent("html", original, "title");
expect(markdown).toBe("Some ==highlighted== text.");
- expect(convertNoteContent("markdown", markdown, "title").content)
- .toContain('<span style="background-color:hsl(60, 75%, 60%)">highlighted</span>');
+ expect(convertNoteContent("markdown", markdown, "title").content).toBe(original);
+ });
+
+ it("preserves a non-default colour exactly, rather than repainting it the highlight yellow", () => {
+ // `==…==` carries no colour, so these keep their own markup in the Markdown form.
+ for (const original of [
+ '<p>Some <span style="background-color:rgb(0, 255, 0)">green</span> text.</p>',
+ '<p>Some <span style="color:#ff0000">red</span> text.</p>',
+ '<p>Some <span style="color:#ffffff;background-color:#000000">inverted</span> text.</p>'
+ ]) {
+ const { content: markdown } = convertNoteContent("html", original, "title");
+ expect(convertNoteContent("markdown", markdown, "title").content).toBe(original);
+ }
});
});