diff --git a/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts b/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts index f99b3d36dc..531724bb87 100644 --- a/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts +++ b/packages/core/src/api/exporters/markdown/htmlToMarkdown.ts @@ -559,7 +559,7 @@ function serializeImage(el: HTMLElement, ctx: SerializeContext): string { if (!src) { return "\n\n"; } - return ctx.indent + `\n\n`; + return ctx.indent + `})\n\n`; } function serializeVideo(el: HTMLElement, ctx: SerializeContext): string { @@ -568,7 +568,7 @@ function serializeVideo(el: HTMLElement, ctx: SerializeContext): string { if (!src) { return "\n\n"; } - return ctx.indent + `\n\n`; + return ctx.indent + `})\n\n`; } function serializeAudio(el: HTMLElement, ctx: SerializeContext): string { @@ -589,7 +589,7 @@ function serializeEmbed(el: HTMLElement, ctx: SerializeContext): string { if (!src) { return "\n\n"; } - return ctx.indent + `[](${src})\n\n`; + return ctx.indent + `[](${escapeLinkDestination(src)})\n\n`; } function serializeFigure(el: HTMLElement, ctx: SerializeContext): string { @@ -645,7 +645,7 @@ function serializeMediaFigure( // No caption + has a markdown shorthand → use it. if (!captionText && kind !== "audio") { - return ctx.indent + `\n\n`; + return ctx.indent + `})\n\n`; } // The descriptor (alt / data-name) is dropped when it duplicates the @@ -720,6 +720,10 @@ function formatLink(text: string, href: string): string { return `[${text}](${escapeLinkDestination(href)})`; } +/** + * Escapes the backslashes and the parentheses in the destination of a link or + * an image. The markdown parser removes these escapes. + */ function escapeLinkDestination(url: string): string { return url.replace(/[\\()]/g, "\\$&"); } @@ -780,7 +784,13 @@ function serializeInlineContent(el: Element): string { ...(text.match(/`+/g) ?? []).map((run) => run.length), ); const fence = "`".repeat(longestRun + 1); - const needsPadding = text.startsWith("`") || text.endsWith("`"); + // A markdown parser removes one space from each side of a code span + // that starts and ends with a space and has other characters + // (CommonMark). Add a space on each side to keep these spaces. + const needsPadding = + text.startsWith("`") || + text.endsWith("`") || + (text.startsWith(" ") && text.endsWith(" ") && /[^ ]/.test(text)); result += fence + (needsPadding ? ` ${text} ` : text) + fence; break; } @@ -814,7 +824,7 @@ function serializeInlineContent(el: Element): string { case "img": { const src = childEl.getAttribute("src") || ""; const alt = childEl.getAttribute("alt") || ""; - result += ``; + result += `})`; break; } case "video": { @@ -826,7 +836,7 @@ function serializeInlineContent(el: Element): string { childEl.getAttribute("data-name") || childEl.getAttribute("title") || ""; - result += ``; + result += `})`; break; } case "p": diff --git a/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts b/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts new file mode 100644 index 0000000000..fda0f671b8 --- /dev/null +++ b/packages/core/src/api/parsers/markdown/markdownToHtml.test.ts @@ -0,0 +1,81 @@ +// @vitest-environment node +import { describe, expect } from "vite-plus/test"; +import { markdownToHtml } from "./markdownToHtml.js"; + +describe("markdownToHtml", () => { + // CommonMark: a line ending is "\n", "\r\n" or "\r". A file from Windows + // has "\r\n". + it.each([ + ["\\r\\n", "\r\n"], + ["\\r", "\r"], + ])("reads %s as a line end", (_, lineEnd) => { + const lines = [ + "# Heading", + "", + "* Bullet", + " * Nested bullet", + "", + "1. Numbered", + "", + "- [x] Checked", + "", + "> Quote", + "", + "Line one\\", + "line two", + "", + "```js", + "const a = 1;", + "```", + "", + ]; + + expect(markdownToHtml(lines.join(lineEnd))).toBe( + markdownToHtml(lines.join("\n")), + ); + }); + + // A paragraph line after the first can have any indent, and the indent is + // not a part of the text. But a code span has its text as it is: only the + // line end becomes a space (CommonMark). + describe("the indent of a paragraph line after the first", () => { + it.each([ + ["a line end alone", "aaa\n bbb\n\tccc"], + ["a backslash", "aaa\\\n bbb\\\n\tccc"], + ["two spaces", "aaa \n bbb \n\tccc"], + ])("is removed after a line break from %s", (_, markdown) => { + expect(markdownToHtml(markdown)).toBe("
aaa
bbb
ccc
foo \tbar
foo bar
a``b
next
", + ); + }); + + it("continues the paragraph before it", () => { + expect(markdownToHtml("text\n```a``b```")).toMatch( + /^text quote
\s*a``b<\/code><\/p>$/,
+ );
+ });
+
+ it("continues the quote before it", () => {
+ expect(markdownToHtml("> quote\n```a``b```")).toMatch(
+ /^
\s*a``b<\/code><\/p><\/blockquote>$/,
+ );
+ });
+ });
+});
diff --git a/packages/core/src/api/parsers/markdown/markdownToHtml.ts b/packages/core/src/api/parsers/markdown/markdownToHtml.ts
index 961192df49..f7a7f90736 100644
--- a/packages/core/src/api/parsers/markdown/markdownToHtml.ts
+++ b/packages/core/src/api/parsers/markdown/markdownToHtml.ts
@@ -46,6 +46,22 @@ type InlineTokenizer = (
allowLinks: boolean,
) => { html: string; end: number } | null;
+/** The characters that a backslash escapes. */
+const ESCAPABLE_CHARACTERS = "\\`*_{}[]()#+-.!~|<>";
+
+/**
+ * Gives the index after the indent (spaces and tabs) of the line that starts
+ * at `i`. The line after a line break in a paragraph can have any indent,
+ * which is not a part of the text (CommonMark). The line break rules use this
+ * and a code span does not, so the indent of a line in a code span stays.
+ */
+function skipIndent(text: string, i: number): number {
+ while (text[i] === " " || text[i] === "\t") {
+ i++;
+ }
+ return i;
+}
+
function tryBackslashEscape(
text: string,
i: number,
@@ -54,12 +70,14 @@ function tryBackslashEscape(
return null;
}
const next = text[i + 1];
- // Hard line break: backslash at end of line
+ // Hard line break: backslash at end of line. No newline follows the `
`:
+ // the HTML parser reads that newline as a space at the start of the next
+ // line.
if (next === "\n") {
- return { html: "
\n", end: i + 2 };
+ return { html: "
", end: skipIndent(text, i + 2) };
}
// Escapable characters
- if ("\\`*_{}[]()#+-.!~|<>".includes(next)) {
+ if (ESCAPABLE_CHARACTERS.includes(next)) {
return { html: escapeHtml(next), end: i + 2 };
}
return null;
@@ -228,7 +246,7 @@ function trySoftBreak(
i: number,
): { html: string; end: number } | null {
if (text[i] === "\n") {
- return { html: "
\n", end: i + 1 };
+ return { html: "
", end: skipIndent(text, i + 1) };
}
return null;
}
@@ -331,8 +349,8 @@ function parseInline(text: string, allowLinks = true): string {
text[i - 2] === " "
) {
result = result.replace(/ +$/, "");
- result += "
\n";
- i++;
+ result += "
";
+ i = skipIndent(text, i + 1);
continue;
}
@@ -582,7 +600,18 @@ function parseDestinationAndTitle(raw: string): {
}
}
- return { url, title };
+ return { url: removeBackslashEscapes(url), title };
+}
+
+/**
+ * Removes the backslash of each backslash escape. As in CommonMark, a
+ * backslash escape works in a link destination as it does in text. The
+ * markdown exporter writes `\(`, `\)` and `\\` in a link destination.
+ */
+function removeBackslashEscapes(text: string): string {
+ return text.replace(/\\(.)/g, (match, char: string) =>
+ ESCAPABLE_CHARACTERS.includes(char) ? char : match,
+ );
}
function parseDelimited(
@@ -803,7 +832,9 @@ function isHtmlBlockStart(line: string): boolean {
// ─── Block-Level Tokenizer ──────────────────────────────────────────────────
function tokenize(markdown: string): Token[] {
- const lines = markdown.split("\n");
+ // A line ends with "\n", "\r\n" or "\r" (CommonMark). A file from Windows
+ // has "\r\n".
+ const lines = markdown.split(/\r\n?|\n/);
const tokens: Token[] = [];
let i = 0;
let prevLineWasBlank = true; // treat start of document as after blank
@@ -818,8 +849,11 @@ function tokenize(markdown: string): Token[] {
continue;
}
- // Fenced code block (0-3 leading spaces allowed per CommonMark)
- const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
+ // Fenced code block (0-3 leading spaces allowed per CommonMark). The info
+ // string after a backtick fence cannot contain a backtick (CommonMark).
+ // Thus a line that starts with a code span, for example ```a``b```, is
+ // not a fence.
+ const fenceMatch = line.match(/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})(.*)$/);
if (fenceMatch) {
const fence = fenceMatch[1];
const fenceChar = fence[0];
@@ -936,7 +970,7 @@ function tokenize(markdown: string): Token[] {
if (/^(#{1,6})\s/.test(cur)) {
break;
} // heading
- if (/^(`{3,}|~{3,})/.test(cur)) {
+ if (/^(`{3,}(?=[^`]*$)|~{3,})/.test(cur)) {
break;
} // code fence
if (/^(\s{0,3})([-*_])\s*(\2\s*){2,}$/.test(cur)) {
@@ -1098,7 +1132,7 @@ function tokenize(markdown: string): Token[] {
if (/^(#{1,6})\s/.test(nextLine)) {
break;
}
- if (/^(`{3,}|~{3,})/.test(nextLine)) {
+ if (/^(`{3,}(?=[^`]*$)|~{3,})/.test(nextLine)) {
break;
}
if (/^\s{0,3}>/.test(nextLine)) {
@@ -1127,14 +1161,16 @@ function tokenize(markdown: string): Token[] {
paraLines.push(nextLine);
i++;
}
- // CommonMark allows up to 3 leading spaces of indent on paragraph lines.
+ // CommonMark allows up to 3 leading spaces of indent on the first
+ // paragraph line. The lines after it can have any indent: the line break
+ // rules of `parseInline` remove it (see `skipIndent`).
// Also strip trailing whitespace from the final line so a trailing
// hard-break sequence (` \n` at end of paragraph) doesn't leak as
// literal trailing spaces in the rendered output.
tokens.push({
type: "paragraph",
content: paraLines
- .map((l) => l.replace(/^ {1,3}/, ""))
+ .map((l, index) => (index === 0 ? l.replace(/^ {1,3}/, "") : l))
.join("\n")
.replace(/[ \t]+$/, ""),
});
diff --git a/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/hardBreak.json b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/hardBreak.json
index 5626739e88..dc18073a94 100644
--- a/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/hardBreak.json
+++ b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/hardBreak.json
@@ -5,7 +5,7 @@
{
"styles": {},
"text": "Line 1
- Line 2",
+Line 2",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/inlineCodeWithSurroundingSpaces.json b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/inlineCodeWithSurroundingSpaces.json
new file mode 100644
index 0000000000..fcdc775c69
--- /dev/null
+++ b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/inlineCodeWithSurroundingSpaces.json
@@ -0,0 +1,21 @@
+[
+ {
+ "children": [],
+ "content": [
+ {
+ "styles": {
+ "code": true,
+ },
+ "text": " Code text ",
+ "type": "text",
+ },
+ ],
+ "id": "1",
+ "props": {
+ "backgroundColor": "default",
+ "textAlignment": "left",
+ "textColor": "default",
+ },
+ "type": "paragraph",
+ },
+]
\ No newline at end of file
diff --git a/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/linkWithParenthesesInUrl.json b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/linkWithParenthesesInUrl.json
new file mode 100644
index 0000000000..aeebedf45c
--- /dev/null
+++ b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/linkWithParenthesesInUrl.json
@@ -0,0 +1,25 @@
+[
+ {
+ "children": [],
+ "content": [
+ {
+ "content": [
+ {
+ "styles": {},
+ "text": "Link",
+ "type": "text",
+ },
+ ],
+ "href": "https://example.com/wiki/Page_(topic)",
+ "type": "link",
+ },
+ ],
+ "id": "1",
+ "props": {
+ "backgroundColor": "default",
+ "textAlignment": "left",
+ "textColor": "default",
+ },
+ "type": "paragraph",
+ },
+]
\ No newline at end of file
diff --git a/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/mediaWithBackslashInUrl.json b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/mediaWithBackslashInUrl.json
new file mode 100644
index 0000000000..d95315e9b7
--- /dev/null
+++ b/tests/src/unit/core/formatConversion/exportParseEquality/__snapshots__/markdown/markdown/mediaWithBackslashInUrl.json
@@ -0,0 +1,30 @@
+[
+ {
+ "children": [],
+ "content": undefined,
+ "id": "1",
+ "props": {
+ "backgroundColor": "default",
+ "caption": "",
+ "name": "Example",
+ "showPreview": true,
+ "textAlignment": "left",
+ "url": "\\server\share\image.png",
+ },
+ "type": "image",
+ },
+ {
+ "children": [],
+ "content": undefined,
+ "id": "2",
+ "props": {
+ "backgroundColor": "default",
+ "caption": "",
+ "name": "Example",
+ "showPreview": true,
+ "textAlignment": "left",
+ "url": "C:\videos\_old\video.mp4",
+ },
+ "type": "video",
+ },
+]
\ No newline at end of file
diff --git a/tests/src/unit/core/formatConversion/exportParseEquality/exportParseEqualityTestInstances.ts b/tests/src/unit/core/formatConversion/exportParseEquality/exportParseEqualityTestInstances.ts
index 28c9fb34fd..7cc07ee5ac 100644
--- a/tests/src/unit/core/formatConversion/exportParseEquality/exportParseEqualityTestInstances.ts
+++ b/tests/src/unit/core/formatConversion/exportParseEquality/exportParseEqualityTestInstances.ts
@@ -652,6 +652,24 @@ export const exportParseEqualityTestInstancesMarkdown: TestInstance<
},
executeTest: testExportParseEqualityMarkdown,
},
+ {
+ testCase: {
+ name: "markdown/inlineCodeWithSurroundingSpaces",
+ content: [
+ {
+ type: "paragraph",
+ content: [
+ {
+ type: "text",
+ text: " Code text ",
+ styles: { code: true },
+ },
+ ],
+ },
+ ],
+ },
+ executeTest: testExportParseEqualityMarkdown,
+ },
{
testCase: {
name: "markdown/boldItalic",
@@ -698,6 +716,24 @@ export const exportParseEqualityTestInstancesMarkdown: TestInstance<
},
executeTest: testExportParseEqualityMarkdown,
},
+ {
+ testCase: {
+ name: "markdown/linkWithParenthesesInUrl",
+ content: [
+ {
+ type: "paragraph",
+ content: [
+ {
+ type: "link",
+ content: "Link",
+ href: "https://example.com/wiki/Page_(topic)",
+ },
+ ],
+ },
+ ],
+ },
+ executeTest: testExportParseEqualityMarkdown,
+ },
{
testCase: {
name: "markdown/plainUrlLink",
@@ -785,6 +821,28 @@ export const exportParseEqualityTestInstancesMarkdown: TestInstance<
},
executeTest: testExportParseEqualityMarkdown,
},
+ {
+ testCase: {
+ name: "markdown/mediaWithBackslashInUrl",
+ content: [
+ {
+ type: "image",
+ props: {
+ url: "\\\\server\\share\\image.png",
+ name: "Example",
+ },
+ },
+ {
+ type: "video",
+ props: {
+ url: "C:\\videos\\_old\\video.mp4",
+ name: "Example",
+ },
+ },
+ ],
+ },
+ executeTest: testExportParseEqualityMarkdown,
+ },
{
testCase: {
name: "markdown/video",
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteLazyContinuation.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteLazyContinuation.json
index 146a54b49b..a9fb97754a 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteLazyContinuation.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteLazyContinuation.json
@@ -5,8 +5,8 @@
{
"styles": {},
"text": "This is a quote
- that continues here
- and here too",
+that continues here
+and here too",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteMultiline.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteMultiline.json
index 669e44db40..2993f08418 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteMultiline.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/blockquoteMultiline.json
@@ -5,8 +5,8 @@
{
"styles": {},
"text": "Line one
- Line two
- Line three",
+Line two
+Line three",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakBackslash.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakBackslash.json
index e4ed206bcf..c6cfdcf8f0 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakBackslash.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakBackslash.json
@@ -5,7 +5,7 @@
{
"styles": {},
"text": "Line one
- Line two",
+Line two",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakMultiple.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakMultiple.json
index 359a3b1cbc..dac5b2a4de 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakMultiple.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakMultiple.json
@@ -5,8 +5,8 @@
{
"styles": {},
"text": "Line one
- Line two
- Line three",
+Line two
+Line three",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakTwoSpaces.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakTwoSpaces.json
index e4ed206bcf..c6cfdcf8f0 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakTwoSpaces.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/hardBreakTwoSpaces.json
@@ -5,7 +5,7 @@
{
"styles": {},
"text": "Line one
- Line two",
+Line two",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/lineBreaks.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/lineBreaks.json
index 359a3b1cbc..dac5b2a4de 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/lineBreaks.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/lineBreaks.json
@@ -5,8 +5,8 @@
{
"styles": {},
"text": "Line one
- Line two
- Line three",
+Line two
+Line three",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphContinuationIndent.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphContinuationIndent.json
new file mode 100644
index 0000000000..3b8024bf98
--- /dev/null
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphContinuationIndent.json
@@ -0,0 +1,21 @@
+[
+ {
+ "children": [],
+ "content": [
+ {
+ "styles": {},
+ "text": "aaa
+bbb
+ccc",
+ "type": "text",
+ },
+ ],
+ "id": "1",
+ "props": {
+ "backgroundColor": "default",
+ "textAlignment": "left",
+ "textColor": "default",
+ },
+ "type": "paragraph",
+ },
+]
\ No newline at end of file
diff --git a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphLeadingIndent.json b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphLeadingIndent.json
index 613cf56ae2..e511c777ec 100644
--- a/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphLeadingIndent.json
+++ b/tests/src/unit/core/formatConversion/parse/__snapshots__/markdown/paragraphLeadingIndent.json
@@ -5,7 +5,7 @@
{
"styles": {},
"text": "aaa
- bbb",
+bbb",
"type": "text",
},
],
diff --git a/tests/src/unit/core/formatConversion/parse/parseTestInstances.ts b/tests/src/unit/core/formatConversion/parse/parseTestInstances.ts
index 33f4be5e4d..b74fc499cb 100644
--- a/tests/src/unit/core/formatConversion/parse/parseTestInstances.ts
+++ b/tests/src/unit/core/formatConversion/parse/parseTestInstances.ts
@@ -2238,4 +2238,13 @@ Some text after.`,
},
executeTest: testParseMarkdown,
},
+ // A paragraph line after the first can have any indent; the indent is
+ // stripped (CommonMark ex. 223)
+ {
+ testCase: {
+ name: "paragraphContinuationIndent",
+ content: `aaa\n bbb\n\tccc`,
+ },
+ executeTest: testParseMarkdown,
+ },
];