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(markdown): pretty-print raw-HTML tables in exported Markdown
Elian Doran524194af1c37
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex a164d156be..c3d96497b4 100644--- a/packages/trilium-core/src/services/export/markdown.spec.ts+++ b/packages/trilium-core/src/services/export/markdown.spec.ts@@ -179,7 +179,18 @@ describe("Markdown export", () => {> [!IMPORTANT]> This is a very important information.>${space}- > <table><tbody><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></tbody></table>+ > <table>+ > <tbody>+ > <tr>+ > <td>1</td>+ > <td>2</td>+ > </tr>+ > <tr>+ > <td>3</td>+ > <td>4</td>+ > </tr>+ > </tbody>+ > </table>> [!CAUTION]> This is a caution.@@ -218,11 +229,19 @@ describe("Markdown export", () => {</table>`;- const expected = trimIndentation`\- <table><tbody><tr><td>Row 1</td><td><p>Allows displaying the value of one or more attributes in the calendar like this: </p><p><img src="13_Calendar View_image.png" alt=""></p><pre><code class="language-text-x-trilium-auto">#weight="70"- #Mood="Good"- #calendar:displayedAttributes="weight,Mood"</code></pre><p>It can also be used with relations, case in which it will display the title of the target note:</p><pre><code class="language-text-x-trilium-auto">~assignee=@My assignee- #calendar:displayedAttributes="assignee"</code></pre></td></tr></tbody></table>`;+ // Structural tags are indented for readability; cell contents (including the+ // <pre> code with its own newlines and indentation) are emitted verbatim.+ const expected = `<table>+ <tbody>+ <tr>+ <td>Row 1</td>+ <td><p>Allows displaying the value of one or more attributes in the calendar like this: </p><p><img src="13_Calendar View_image.png" alt=""></p><pre><code class="language-text-x-trilium-auto">#weight="70"+ #Mood="Good"+ #calendar:displayedAttributes="weight,Mood"</code></pre><p>It can also be used with relations, case in which it will display the title of the target note:</p><pre><code class="language-text-x-trilium-auto">~assignee=@My assignee+ #calendar:displayedAttributes="assignee"</code></pre></td>+ </tr>+ </tbody>+</table>`;expect(markdownExportService.toMarkdown(html)).toBe(expected);});@@ -412,7 +431,18 @@ describe("Markdown export", () => {</table></figure>`;- const expected = `<table><tbody><tr><td>Hi</td><td>there</td></tr><tr><td>Hi</td><td>there</td></tr></tbody></table>`;+ const expected = `<table>+ <tbody>+ <tr>+ <td>Hi</td>+ <td>there</td>+ </tr>+ <tr>+ <td>Hi</td>+ <td>there</td>+ </tr>+ </tbody>+</table>`;expect(markdownExportService.toMarkdown(html)).toBe(expected);});@@ -490,9 +520,19 @@ describe("Markdown export", () => {</table></figure>`;- const expected = trimIndentation`\- <table><thead><tr><th>Code</th></tr></thead><tbody><tr><td><pre><code class="language-text-x-trilium-auto">this.$widget = $("<div>");</code>- </pre></td></tr></tbody></table>`;+ const expected = `<table>+ <thead>+ <tr>+ <th>Code</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td><pre><code class="language-text-x-trilium-auto">this.$widget = $("<div>");</code>+ </pre></td>+ </tr>+ </tbody>+</table>`;expect(markdownExportService.toMarkdown(html)).toBe(expected);});diff --git a/packages/trilium-core/src/services/import/markdown.spec.ts b/packages/trilium-core/src/services/import/markdown.spec.tsindex af13896290..cc1936b7d0 100644--- a/packages/trilium-core/src/services/import/markdown.spec.ts+++ b/packages/trilium-core/src/services/import/markdown.spec.ts@@ -329,10 +329,26 @@ $$`;});// The exporter keeps headerless tables (and heading-column-only tables) as raw- // HTML rather than inventing a phantom empty header row. Confirm the import side- // passes that HTML through unchanged, so the round-trip introduces no blank row.+ // HTML rather than inventing a phantom empty header row, pretty-printed across+ // multiple indented lines. Confirm the import side passes that exact multi-line+ // HTML through unchanged (no blank lines means it stays a single HTML block), so+ // the round-trip introduces no blank row.it("preserves a headerless table (heading columns only) without a phantom header row", () => {- const html = /*html*/`<table><tbody><tr><th>Heading</th><td>Not a heading</td></tr><tr><td>Heading</td><td>Not a heading</td></tr></tbody></table>`;+ // Exactly what the Markdown exporter emits for such a table.+ const html = [+ `<table>`,+ ` <tbody>`,+ ` <tr>`,+ ` <th>Heading</th>`,+ ` <td>Not a heading</td>`,+ ` </tr>`,+ ` <tr>`,+ ` <td>Heading</td>`,+ ` <td>Not a heading</td>`,+ ` </tr>`,+ ` </tbody>`,+ `</table>`+ ].join("\n");const result = markdownService.renderToHtml(html, "Title");expect(result).toStrictEqual(html);// No synthesized empty header row leaked in.diff --git a/packages/turndown-plugin-gfm/src/lib/tables.js b/packages/turndown-plugin-gfm/src/lib/tables.jsindex c69937398d..c53db57b6a 100644--- a/packages/turndown-plugin-gfm/src/lib/tables.js+++ b/packages/turndown-plugin-gfm/src/lib/tables.js@@ -81,7 +81,7 @@ rules.table = {// Only convert tables that can result in valid Markdown// Other tables are kept as HTML using `keep` (see below).if (tableShouldBeHtml(node, options_)) {- return node.outerHTML;+ return prettyPrintTable(node);} else {if (tableShouldBeSkipped(node)) return content;@@ -279,6 +279,49 @@ function tableColCount(node) {return maxColCount}+// Structural table elements whose children are themselves structural and are+// therefore broken onto their own indented lines. Every other element (td, th,+// caption, col) is a leaf: its content is emitted verbatim on a single line.+var TABLE_CONTAINER_TAGS = ['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'COLGROUP'];++// Serializes a table that is kept as raw HTML into indented, multi-line markup so+// it stays readable inside the exported Markdown file. Only structural tags are+// placed on their own lines; cell contents are emitted verbatim (never re-indented)+// so whitespace-significant content such as <pre> code survives untouched. No blank+// lines are produced, so the result stays a single raw-HTML block on reimport.+// Inter-element whitespace text nodes are dropped, which makes the output stable+// across repeated export/import cycles.+function prettyPrintTable(node) {+ return serializeStructuralNode(node, 0);+}++function serializeStructuralNode(node, depth) {+ const indent = ' '.repeat(depth);+ const closeTag = '</' + node.nodeName.toLowerCase() + '>';++ // Use the DOM's own serializer for the opening tag so attribute quoting/escaping+ // matches the rest of the output. A shallow clone has no children, so its+ // outerHTML is exactly the opening tag plus (for non-void elements) the closing tag.+ const shallowHtml = node.cloneNode(false).outerHTML;+ const isVoid = !shallowHtml.endsWith(closeTag);+ const openTag = isVoid ? shallowHtml : shallowHtml.slice(0, shallowHtml.length - closeTag.length);++ if (TABLE_CONTAINER_TAGS.indexOf(node.nodeName) === -1) {+ // Leaf structural element (td/th/caption/col): keep its content on one line.+ return isVoid ? indent + openTag : indent + openTag + node.innerHTML.trim() + closeTag;+ }++ const lines = [indent + openTag];+ for (let i = 0; i < node.childNodes.length; i++) {+ const child = node.childNodes[i];+ if (child.nodeType === 1) { // ELEMENT_NODE — whitespace-only text nodes are skipped+ lines.push(serializeStructuralNode(child, depth + 1));+ }+ }+ lines.push(indent + closeTag);+ return lines.join('\n');+}+export default function tables (turndownService) {isCodeBlock_ = turndownService.isCodeBlock;options_ = turndownService.options;diff --git a/packages/turndown-plugin-gfm/test/gfm.spec.ts b/packages/turndown-plugin-gfm/test/gfm.spec.tsindex a48466e9ba..4aec8afb3b 100644--- a/packages/turndown-plugin-gfm/test/gfm.spec.ts+++ b/packages/turndown-plugin-gfm/test/gfm.spec.ts@@ -263,13 +263,26 @@ describe("GFM plugin", () => {// GFM cannot represent a headerless table without inventing a phantom// empty header row, which reimports as a spurious blank row. Such tables- // are kept as raw HTML instead so they round-trip faithfully.+ // are kept as raw HTML instead so they round-trip faithfully. The HTML is+ // pretty-printed (structural tags indented, no blank lines) so it stays+ // readable in the exported Markdown while remaining a single HTML block.it("keeps a table with no heading row as HTML", () => {const input = `<table><tr><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr><tr><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr></table>`;- const expected = `<table><tbody><tr><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr><tr><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr></tbody></table>`;+ const expected = `<table>+ <tbody>+ <tr>+ <td>Row 1 Cell 1</td>+ <td>Row 1 Cell 2</td>+ </tr>+ <tr>+ <td>Row 2 Cell 1</td>+ <td>Row 2 Cell 2</td>+ </tr>+ </tbody>+</table>`;expect(turndown.turndown(input)).toBe(expected);});@@ -284,7 +297,50 @@ describe("GFM plugin", () => {<td>Not a heading</td></tr></table>`;- const expected = `<table><tbody><tr><th>Heading</th><td>Not a heading</td></tr><tr><td>Heading</td><td>Not a heading</td></tr></tbody></table>`;+ const expected = `<table>+ <tbody>+ <tr>+ <th>Heading</th>+ <td>Not a heading</td>+ </tr>+ <tr>+ <td>Heading</td>+ <td>Not a heading</td>+ </tr>+ </tbody>+</table>`;+ expect(turndown.turndown(input)).toBe(expected);+ });++ it("pretty-prints a caption, colgroup and thead kept as HTML", () => {+ // A table with block content in a cell (here a list) is kept as HTML;+ // the caption, colgroup/col and thead/tbody structure is all indented,+ // while the cell contents (including the list) stay inline.+ const input = `<table>+ <caption>My caption</caption>+ <colgroup><col style="width:50%"><col></colgroup>+ <thead><tr><th>H1</th><th>H2</th></tr></thead>+ <tbody><tr><td>A</td><td><ul><li>x</li></ul></td></tr></tbody>+ </table>`;+ const expected = `<table>+ <caption>My caption</caption>+ <colgroup>+ <col style="width:50%">+ <col>+ </colgroup>+ <thead>+ <tr>+ <th>H1</th>+ <th>H2</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>A</td>+ <td><ul><li>x</li></ul></td>+ </tr>+ </tbody>+</table>`;expect(turndown.turndown(input)).toBe(expected);});});