Skip to content

Commit cc5f198

Browse files
committed
fix blank line processing with markdown
1 parent 47d7d49 commit cc5f198

File tree

4 files changed

+607
-3
lines changed

4 files changed

+607
-3
lines changed

packages/core/src/api/exporters/markdown/markdownExporter.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@ import { addSpacesToCheckboxes } from "./util/addSpacesToCheckboxesRehypePlugin.
1616

1717
// Needs to be sync because it's used in drag handler event (SideMenuPlugin)
1818
// Ideally, call `await initializeESMDependencies()` before calling this function
19-
export function cleanHTMLToMarkdown(cleanHTMLString: string) {
19+
export function cleanHTMLToMarkdown(
20+
cleanHTMLString: string,
21+
options?: {
22+
keepEmptyParagraphs: boolean;
23+
}
24+
) {
2025
const deps = esmDependencies;
2126

2227
if (!deps) {
@@ -25,6 +30,14 @@ export function cleanHTMLToMarkdown(cleanHTMLString: string) {
2530
);
2631
}
2732

33+
if (options?.keepEmptyParagraphs) {
34+
// replace empty paragraphs with [EMPTY-LINE]
35+
// otherwise the unified pipeline will get rid of these
36+
cleanHTMLString = cleanHTMLString.replace(
37+
/<p><\/p>/g,
38+
"<p>[EMPTY-LINE]</p>"
39+
);
40+
}
2841
const markdownString = deps.unified
2942
.unified()
3043
.use(deps.rehypeParse.default, { fragment: true })
@@ -37,7 +50,12 @@ export function cleanHTMLToMarkdown(cleanHTMLString: string) {
3750
})
3851
.processSync(cleanHTMLString);
3952

40-
return markdownString.value as string;
53+
let ret = markdownString.value as string;
54+
if (options?.keepEmptyParagraphs) {
55+
// remove [EMPTY-LINE] hacks we added earlier
56+
ret = ret.replace(/\n\[EMPTY-LINE\]\n/g, "\n\n");
57+
}
58+
return ret;
4159
}
4260

4361
export async function blocksToMarkdown<
@@ -54,5 +72,9 @@ export async function blocksToMarkdown<
5472
const exporter = createExternalHTMLExporter(schema, editor);
5573
const externalHTML = exporter.exportBlocks(blocks, options);
5674

57-
return cleanHTMLToMarkdown(externalHTML);
75+
const ret = cleanHTMLToMarkdown(externalHTML, {
76+
keepEmptyParagraphs: true,
77+
});
78+
79+
return ret;
5880
}

0 commit comments

Comments
 (0)