Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/core/src/api/exporters/markdown/formatLinkDestination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function formatLinkDestination(
destination: string,
forceAngle = false,
): string {
// Even angle-bracket destinations cannot contain line endings. Encode
// control whitespace so the destination works in other Markdown readers.
const url = destination
.replace(/[\t\n\r]/g, encodeURIComponent)
.replace(/[\\()<>]/g, "\\$&");
return forceAngle || /[ <>]/.test(url) || url !== url.trim()
? `<${url}>`
: url;
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import { describe, expect, vi } from "vite-plus/test";

import { markdownToHtml } from "../../parsers/markdown/markdownToHtml.js";
import { htmlToMarkdown } from "./htmlToMarkdown.js";

describe("htmlToMarkdown", () => {
it.each([
String.raw`foo\ bar.png`,
String.raw`\\server\share\my photo.png`,
"my file).png",
"my file&gt;v.png",
])("round-trips an image pointing to %s", (src) => {
const image = `<p><img src="${src}" alt="Photo"></p>`;
expect(markdownToHtml(htmlToMarkdown(image))).toBe(image);
});

// In the active document, an element of the HTML can load a resource and
// run an event handler: each video of an export starts a second request.
it("keeps the HTML out of the active document", ({ onTestFinished }) => {
Expand Down
28 changes: 18 additions & 10 deletions packages/core/src/api/exporters/markdown/htmlToMarkdown.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { parseLinkFigure } from "../../../blocks/File/helpers/parse/parseLinkFigure.js";
import { detachedDoc } from "../../../util/detachedDoc.js";
import { parseAutolinkLiteral } from "../../parsers/markdown/autolink.js";
import { formatLinkDestination } from "./formatLinkDestination.js";
import { wrapWithDelimiter } from "./wrapWithDelimiter.js";

/**
Expand Down Expand Up @@ -561,7 +562,7 @@ function serializeImage(el: HTMLElement, ctx: SerializeContext): string {
if (!src) {
return "\n\n";
}
return ctx.indent + `![${alt}](${src})\n\n`;
return ctx.indent + formatImageLink(alt, src) + "\n\n";
}

function serializeVideo(el: HTMLElement, ctx: SerializeContext): string {
Expand All @@ -570,7 +571,7 @@ function serializeVideo(el: HTMLElement, ctx: SerializeContext): string {
if (!src) {
return "\n\n";
}
return ctx.indent + `![${name}](${src})\n\n`;
return ctx.indent + formatImageLink(name, src) + "\n\n";
}

function serializeAudio(el: HTMLElement, ctx: SerializeContext): string {
Expand All @@ -591,7 +592,7 @@ function serializeEmbed(el: HTMLElement, ctx: SerializeContext): string {
if (!src) {
return "\n\n";
}
return ctx.indent + `[](${src})\n\n`;
return ctx.indent + `[](${formatLinkDestination(src)})\n\n`;
}

function serializeFigure(el: HTMLElement, ctx: SerializeContext): string {
Expand Down Expand Up @@ -657,7 +658,7 @@ function serializeMediaFigure(

// No caption + has a markdown shorthand → use it.
if (!captionText && (kind === "img" || kind === "video")) {
return ctx.indent + `![${descriptor}](${src})\n\n`;
return ctx.indent + formatImageLink(descriptor, src) + "\n\n";
}

// The descriptor (alt / data-name) is dropped when it duplicates the
Expand Down Expand Up @@ -733,11 +734,12 @@ function formatLink(text: string, href: string): string {
return href;
}
}
return `[${text}](${escapeLinkDestination(href)})`;
return `[${text}](${formatLinkDestination(href)})`;
}

function escapeLinkDestination(url: string): string {
return url.replace(/[\\()]/g, "\\$&");
function formatImageLink(label: string, src: string): string {
// Distinguish escaped destinations from legacy bare Windows paths.
return `![${label}](${formatLinkDestination(src, /^(?:[a-z]:\\|\\)/i.test(src))})`;
}

function serializeDetails(el: HTMLElement, ctx: SerializeContext): string {
Expand Down Expand Up @@ -796,7 +798,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;
}
Expand Down Expand Up @@ -830,7 +838,7 @@ function serializeInlineContent(el: Element): string {
case "img": {
const src = childEl.getAttribute("src") || "";
const alt = childEl.getAttribute("alt") || "";
result += `![${alt}](${src})`;
result += formatImageLink(alt, src);
break;
}
case "video": {
Expand All @@ -842,7 +850,7 @@ function serializeInlineContent(el: Element): string {
childEl.getAttribute("data-name") ||
childEl.getAttribute("title") ||
"";
result += `![${name}](${src})`;
result += formatImageLink(name, src);
break;
}
case "p":
Expand Down
90 changes: 90 additions & 0 deletions packages/core/src/api/parsers/markdown/markdownToHtml.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { describe, expect } from "vite-plus/test";
import { markdownToHtml } from "./markdownToHtml.js";

describe("markdownToHtml", () => {
it("keeps an unmatched backtick run literal", () => {
expect(markdownToHtml("``a`")).toBe("<p>``a`</p>");
});

it("unescapes ASCII punctuation in a link destination", () => {
expect(markdownToHtml(String.raw`[x](https://example.com/a\?q\=1)`)).toBe(
'<p><a href="https://example.com/a?q=1">x</a></p>',
);
});

// 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("<p>aaa<br>bbb<br>ccc</p>");
});

it.each([
["a tab", "`foo\n\tbar`", "<p><code>foo \tbar</code></p>"],
["spaces", "`foo\n bar`", "<p><code>foo bar</code></p>"],
])("stays in a code span, for %s", (_, markdown, html) => {
expect(markdownToHtml(markdown)).toBe(html);
});
});

// The info string of a backtick code fence cannot contain a backtick
// (CommonMark). Thus a line that starts with a code span of three backticks
// is text. The markdown exporter writes such a code span for code that
// contains two backticks.
describe("a line that starts with a code span of three backticks", () => {
it("is a paragraph and not the start of a code block", () => {
expect(markdownToHtml("```a``b```\n\nnext")).toBe(
"<p><code>a``b</code></p><p>next</p>",
);
});

it("continues the paragraph before it", () => {
expect(markdownToHtml("text\n```a``b```")).toMatch(
/^<p>text<br>\s*<code>a``b<\/code><\/p>$/,
);
});

it("continues the quote before it", () => {
expect(markdownToHtml("> quote\n```a``b```")).toMatch(
/^<blockquote><p>quote<br>\s*<code>a``b<\/code><\/p><\/blockquote>$/,
);
});
});
});
Loading
Loading