Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// @vitest-environment node
import { describe, expect, it } from "vite-plus/test";
import { formatLinkDestination } from "./formatLinkDestination.js";

describe("formatLinkDestination", () => {
it.each([
"https://example.com/my file.pdf",
"https://example.com/my\tfile.pdf",
"https://example.com/my\nfile.pdf",
" https://example.com/file.pdf",
"https://example.com/file.pdf ",
])("puts %j in angle brackets", (destination) => {
expect(formatLinkDestination(destination)).toBe(`<${destination}>`);
});

it.each(["", "https://example.com/file.pdf", "my%20file.pdf"])(
"leaves %j, which has no white space, unchanged",
(destination) => {
expect(formatLinkDestination(destination)).toBe(destination);
},
);

it("leaves a destination with a no-break space unchanged", () => {
// The markdown parser reads a no-break space as a part of the URL.
const destination = "https://example.com/my file.pdf";
expect(formatLinkDestination(destination)).toBe(destination);
});
});
12 changes: 12 additions & 0 deletions packages/core/src/api/exporters/markdown/formatLinkDestination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* A space, a tab or a newline ends the destination of a link or an image.
* Thus, a destination with one of these characters goes in angle brackets
* (`<my file.png>`), as in CommonMark. Without the brackets, the markdown
* parser cuts the URL at that character.
*/
export function formatLinkDestination(destination: string): string {
// The characters at which `parseDestinationAndTitle` of the markdown parser
// ends a destination. Other white space, such as a no-break space, is a
// part of the URL there.
return /[ \t\n]/.test(destination) ? `<${destination}>` : destination;
}
110 changes: 87 additions & 23 deletions packages/core/src/api/exporters/markdown/htmlToMarkdown.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { parseAutolinkLiteral } from "../../parsers/markdown/autolink.js";
import { formatLinkDestination } from "./formatLinkDestination.js";
import { wrapWithDelimiter } from "./wrapWithDelimiter.js";

/**
Expand All @@ -25,6 +26,9 @@ export function htmlToMarkdown(html: string): string {
return result.trim() + "\n";
}

/** A serialized hard break: a backslash at the end of the line. */
const HARD_BREAK = "\\\n";

interface SerializeContext {
indent: string; // current indentation prefix for list nesting
// True when the current node is being serialized as continuation content
Expand Down Expand Up @@ -111,9 +115,7 @@ function serializeNode(node: Node, ctx: SerializeContext): string {
// ─── Block Serializers ───────────────────────────────────────────────────────

function serializeParagraph(el: HTMLElement, ctx: SerializeContext): string {
const content = serializeInlineContent(el);
// Trim leading/trailing hard breaks (matching remark behavior)
const trimmed = trimHardBreaks(content);
const trimmed = serializeBlockText(el);
if (ctx.inListItem) {
return trimmed;
}
Expand All @@ -123,7 +125,7 @@ function serializeParagraph(el: HTMLElement, ctx: SerializeContext): string {
function serializeHeading(el: HTMLElement, ctx: SerializeContext): string {
const level = parseInt(el.tagName[1], 10);
const prefix = "#".repeat(level) + " ";
const content = toSingleLine(serializeInlineContent(el));
const content = toSingleLine(serializeBlockText(el));
return ctx.indent + prefix + content + "\n\n";
}

Expand All @@ -141,7 +143,7 @@ function serializeBlockquote(el: HTMLElement, ctx: SerializeContext): string {
for (const child of blockChildren) {
const tag = child.tagName.toLowerCase();
if (tag === "p") {
parts.push(serializeInlineContent(child as HTMLElement));
parts.push(serializeBlockText(child));
} else {
const innerCtx: SerializeContext = { indent: "", inListItem: false };
parts.push(serializeNode(child, innerCtx).trim());
Expand All @@ -150,7 +152,7 @@ function serializeBlockquote(el: HTMLElement, ctx: SerializeContext): string {
content = parts.join("\n\n");
} else {
// No block-level children — treat entire content as inline
content = serializeInlineContent(el);
content = serializeBlockText(el);
}

const lines = content.split("\n");
Expand Down Expand Up @@ -325,12 +327,10 @@ function serializeListItem(
const summary = details.querySelector("summary");
const summaryP = summary?.querySelector("p");
firstContentEl = details;
inlineContent = summaryP ? serializeInlineContent(summaryP) : "";
inlineContent = summaryP ? serializeBlockText(summaryP) : "";
} else {
firstContentEl = getFirstContentElement(el, checkbox);
inlineContent = firstContentEl
? serializeInlineContent(firstContentEl)
: "";
inlineContent = firstContentEl ? serializeBlockText(firstContentEl) : "";
}

// The marker line ends with a single `\n` so that consecutive list items
Expand All @@ -352,7 +352,7 @@ function serializeListItem(
}
const childTag = child.tagName.toLowerCase();
if (childTag === "p") {
const content = serializeInlineContent(child as HTMLElement);
const content = serializeBlockText(child);
// Continuation paragraph needs a blank line to separate it from the
// previous content; CommonMark would otherwise treat it as a soft
// wrap of that content.
Expand Down Expand Up @@ -382,7 +382,7 @@ function serializeListItem(
} else if (childTag === "p") {
// Continuation paragraph within list item — requires blank line before
// so it isn't read as part of the marker line's text.
const content = serializeInlineContent(child as HTMLElement);
const content = serializeBlockText(child);
result += "\n" + childIndent + indentLines(content, childIndent) + "\n";
} else {
// Other block-level children (code blocks, blockquotes, etc.) already
Expand Down Expand Up @@ -459,8 +459,13 @@ function serializeTable(el: HTMLElement, ctx: SerializeContext): string {
hasHeader = true;
}

// A table row is one line, so the line end of a hard break would cut
// the row. Write each hard break as the HTML `<br>` tag, which the
// markdown parser reads as a hard break.
const content = escapeTableCell(
serializeInlineContent(cell as HTMLElement).trim(),
serializeInlineContent(cell as HTMLElement)
.replaceAll(HARD_BREAK, "<br>")
.trim(),
);
const colspan = parseInt(cell.getAttribute("colspan") || "1", 10);
const rowspan = parseInt(cell.getAttribute("rowspan") || "1", 10);
Expand Down Expand Up @@ -568,7 +573,10 @@ function serializeImage(el: HTMLElement, ctx: SerializeContext): string {
if (!src) {
return "\n\n";
}
return ctx.indent + `![${alt}](${escapeLinkDestination(src)})\n\n`;
return (
ctx.indent +
`![${alt}](${formatLinkDestination(escapeLinkDestination(src))})\n\n`
);
}

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

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

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

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

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

/**
Expand Down Expand Up @@ -783,6 +799,8 @@ function toSingleLine(content: string): string {
function serializeInlineContent(el: Element): string {
let result = "";

mergeAdjacentItalicElements(el);

for (const child of Array.from(el.childNodes)) {
if (child.nodeType === 3 /* Node.TEXT_NODE */) {
result += escapeHtmlLikeText(child.textContent || "");
Expand Down Expand Up @@ -831,7 +849,7 @@ function serializeInlineContent(el: Element): string {
break;
}
case "br":
result += "\\\n";
result += HARD_BREAK;
break;
case "math": {
// Inline math — emit its LaTeX source as a math span. Collapsed to
Expand All @@ -850,7 +868,7 @@ function serializeInlineContent(el: Element): string {
case "img": {
const src = childEl.getAttribute("src") || "";
const alt = childEl.getAttribute("alt") || "";
result += `![${alt}](${escapeLinkDestination(src)})`;
result += `![${alt}](${formatLinkDestination(escapeLinkDestination(src))})`;
break;
}
case "video": {
Expand All @@ -862,7 +880,7 @@ function serializeInlineContent(el: Element): string {
childEl.getAttribute("data-name") ||
childEl.getAttribute("title") ||
"";
result += `![${name}](${escapeLinkDestination(src)})`;
result += `![${name}](${formatLinkDestination(escapeLinkDestination(src))})`;
break;
}
case "p":
Expand All @@ -882,6 +900,41 @@ function serializeInlineContent(el: Element): string {
return result;
}

/**
* The external HTML exporter writes each run of text with its own elements.
* Two adjacent italic runs that are different in a second style then give
* two adjacent italic elements, for example `<em><s>a</s></em><em>b</em>`.
* If the serializer writes each element, the italic delimiter closes and
* opens at one position (`*~~a~~**b*`), and the markdown parser reads `**`
* as text. Thus, move the content of each italic element into the italic
* element directly before it (`<em><s>a</s>b</em>`). The result has one
* delimiter pair: `*~~a~~b*`. The elements are in the serializer's own copy
* of the document (see `htmlToMarkdown`), so the change has no other effect.
*/
function mergeAdjacentItalicElements(parent: Element) {
let element = parent.firstElementChild;
while (element) {
const next = element.nextElementSibling;
if (
next &&
// No text is between the two elements.
next === element.nextSibling &&
isItalicElement(element) &&
isItalicElement(next)
) {
element.append(...Array.from(next.childNodes));
next.remove();
continue;
}
element = next;
}
}

function isItalicElement(element: Element): boolean {
const tag = element.tagName.toLowerCase();
return tag === "em" || tag === "i";
}

/**
* Escape `<` where the markdown parser would read raw HTML or an autolink, so
* text like `<details>` loads back as text. A `<` before a space or digit
Expand All @@ -901,14 +954,25 @@ function escapeHtmlLikeText(text: string): string {
* if the trailing space was escaped.
*/

/**
* Serialize the inline content of a block, for use as the text of the block:
* without hard breaks at its edges. Markdown has no syntax for a hard break
* at the end of a block (the parser reads the backslash there as a literal
* character), nor for one at the start of a heading or a list item.
*/
function serializeBlockText(el: Element): string {
return trimHardBreaks(serializeInlineContent(el));
}

/**
* Trim leading/trailing hard breaks from inline content.
* Matches remark behavior where <br> at start/end of paragraph is dropped.
*/
function trimHardBreaks(content: string): string {
// Remove leading hard breaks
let result = content.replace(/^(\\\n)+/, "");
// Remove trailing hard breaks produced by `<br>`
result = result.replace(/(\\\n)+$/, "");
// Remove trailing hard breaks produced by `<br>`, also with spaces or tabs
// after them: markdown ignores those at the end of a block.
result = result.replace(/(\\\n[ \t]*)+$/, "");
return result;
}
Loading
Loading