From 5c2a528229ee06fc3087e862c5fe2a1e37233e49 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 30 Apr 2026 10:32:25 -0500 Subject: [PATCH] remove the standard markdown extra new lines --- src/app/components/editor/output.ts | 11 ++----- src/app/plugins/markdown/htmlToMarkdown.ts | 38 +++++++++++++++++++++- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 38f41958a..cf166c96d 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -126,7 +126,6 @@ export const toMatrixCustomHTML = ( opts: OutputOptions ): string => { let markdownLines = ''; - let insideCodeFence = false; const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => { if (opts.allowBlockMarkdown && 'type' in n && n.type === BlockType.Paragraph) { let line = toMatrixCustomHTML(n, { @@ -136,15 +135,11 @@ export const toMatrixCustomHTML = ( }); const rawText = line.replace(/$/, ''); - const isCodeFenceLine = /^`{3}/.test(rawText); - if (isCodeFenceLine) { - insideCodeFence = !insideCodeFence; - } - // Use \n inside code fences to prevent extra blank lines from - // accumulating on each edit cycle. Normal paragraphs use \n\n. + // Use \n for all paragraphs to prevent extra blank lines from + // accumulating on each edit cycle. line = line - .replace(/$/, insideCodeFence || isCodeFenceLine ? '\n' : '\n\n') + .replace(/$/, '\n') .replace(/^(\\*)>/, '$1>'); // strip nicknames if needed diff --git a/src/app/plugins/markdown/htmlToMarkdown.ts b/src/app/plugins/markdown/htmlToMarkdown.ts index 2412e015a..fac19c52e 100644 --- a/src/app/plugins/markdown/htmlToMarkdown.ts +++ b/src/app/plugins/markdown/htmlToMarkdown.ts @@ -17,8 +17,44 @@ export function htmlToMarkdown(html: string): string { return processNodes(domNodes).trim(); } +function isBlockTag(node: ChildNode | undefined): boolean { + if (!node || !isTag(node)) return false; + const blocks = [ + 'p', + 'div', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'ul', + 'ol', + 'li', + 'blockquote', + 'pre', + 'hr', + 'table', + 'details', + 'summary', + ]; + return blocks.includes(node.name.toLowerCase()); +} + function processNodes(nodes: ChildNode[]): string { - return nodes.map((n) => processNode(n)).join(''); + return nodes + .filter((n, i) => { + if (isText(n) && /^\s*$/.test(n.data)) { + const prev = nodes[i - 1]; + const next = nodes[i + 1]; + // Ignore whitespace between block tags or at the edges + const isBetweenBlocks = (!prev || isBlockTag(prev)) && (!next || isBlockTag(next)); + if (isBetweenBlocks) return false; + } + return true; + }) + .map((n) => processNode(n)) + .join(''); } function processNode(node: ChildNode, listDepth: number = 0): string {