Open History to see the last commit
1import type { Root, RootContent } from "mdast";
2import { unified } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5
6const parser = unified().use(remarkParse).use(remarkGfm);
7export type MarkdownNode = Root | RootContent;
8
9function decodeCodePoint(codePoint: number, entity: string): string {
10 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
11 return entity;
12 }
13 return String.fromCodePoint(codePoint);
14}
15
16function decodeHtmlEntities(value: string): string {
17 return value.replace(
18 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
19 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
20 if (decimal) {
21 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
22 }
23 if (hexadecimal) {
24 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
25 }
26 switch (entity.toLowerCase()) {
27 case "&":
28 return "&";
29 case "'":
30 return "'";
31 case ">":
32 return ">";
33 case "<":
34 return "<";
35 case " ":
36 return "\u00a0";
37 case """:
38 return '"';
39 default:
40 return entity;
41 }
42 },
43 );
44}
45
46const HTML_TAG = /<!--[\s\S]*?-->|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi;
47
48function attribute(tag: string, name: string): string | null {
49 const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
50 for (const match of tag.matchAll(attributes)) {
51 if (match[1]?.toLowerCase() === name) {
52 return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? "");
53 }
54 }
55 return null;
56}
57
58function markdownDestination(url: string): string {
59 return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
60}
61
62const ANCHOR_TAG = /^<\/?a[\s/>]/i;
63
64/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
65type AnchorState = { readonly pending: string[]; open: number };
66
67// Code spans keep their text; an odd trailing backslash would escape the closing "]".
68function escapeLinkLabel(text: string): string {
69 return text
70 .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
71 match.startsWith("`") || match.length % 2 === 0
72 ? match
73 : `${match.slice(0, -1)}\\${match.slice(-1)}`,
74 )
75 .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
76}
77
78// An unescaped "!" before the inserted "[" would turn the link into an image.
79function bangBefore(text: string, index: number): boolean {
80 if (text[index - 1] !== "!") return false;
81 let backslashes = 0;
82 while (text[index - 2 - backslashes] === "\\") backslashes += 1;
83 return backslashes % 2 === 0;
84}
85
86/**
87 * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
88 * Markdown link; any other anchor keeps its text unlinked.
89 */
90function anchorMarkdown(tags: readonly string[]): AnchorState {
91 const replacements = tags.map(() => "");
92 const open: Array<{ index: number; href: string | undefined }> = [];
93 tags.forEach((tag, index) => {
94 if (tag[1] !== "/") {
95 const href = attribute(tag, "href")?.trim();
96 open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
97 return;
98 }
99 const opening = open.pop();
100 if (!opening?.href) return;
101 replacements[opening.index] = "[";
102 replacements[index] = `](${markdownDestination(opening.href)})`;
103 });
104 return { pending: replacements, open: 0 };
105}
106
107function markdownHtmlTags(content: string): RegExpExecArray[] {
108 // An HTML block such as <details> can also contain Markdown fences and code spans.
109 const codeRanges: Array<{ start: number; end: number }> = [];
110 const tags = [...content.matchAll(HTML_TAG)];
111 let tagIndex = 0;
112 const delimiters = [...content.matchAll(/`+|~{3,}/g)].filter((delimiter) => {
113 while (tags[tagIndex] && tags[tagIndex]!.index + tags[tagIndex]![0].length <= delimiter.index)
114 tagIndex += 1;
115 const tag = tags[tagIndex];
116 return !tag || delimiter.index < tag.index;
117 });
118 for (let index = 0; index < delimiters.length; index += 1) {
119 const opening = delimiters[index]!;
120 const lineStart = content.lastIndexOf("\n", opening.index - 1) + 1;
121 const fenced =
122 opening[0].length >= 3 && /^ {0,3}$/.test(content.slice(lineStart, opening.index));
123 if (opening[0][0] === "~" && !fenced) continue;
124 let closingIndex = -1;
125 for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) {
126 const closing = delimiters[candidate]!;
127 if (!fenced && closing[0] === opening[0]) {
128 closingIndex = candidate;
129 break;
130 }
131 if (!fenced || closing[0][0] !== opening[0][0] || closing[0].length < opening[0].length)
132 continue;
133 const start = content.lastIndexOf("\n", closing.index - 1) + 1;
134 const nextLine = content.indexOf("\n", closing.index);
135 const end = nextLine === -1 ? content.length : nextLine;
136 if (
137 /^ {0,3}$/.test(content.slice(start, closing.index)) &&
138 /^\s*$/.test(content.slice(closing.index + closing[0].length, end))
139 ) {
140 closingIndex = candidate;
141 break;
142 }
143 }
144 if (closingIndex === -1) {
145 if (fenced) codeRanges.push({ start: opening.index, end: content.length });
146 continue;
147 }
148 const closing = delimiters[closingIndex]!;
149 codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
150 index = closingIndex;
151 }
152 return tags.filter(
153 (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
154 );
155}
156
157/**
158 * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
159 * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
160 */
161export function markdownHtmlContent(
162 content: string,
163 options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
164): string {
165 const tags = markdownHtmlTags(content);
166 const anchors =
167 options.anchors ??
168 anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
169 let result = "";
170 let end = 0;
171 for (const match of tags) {
172 const text = content.slice(end, match.index);
173 result += anchors.open > 0 ? escapeLinkLabel(text) : text;
174 const replacement = htmlTagMarkdown(match[0], anchors, options);
175 if (replacement === "[" && bangBefore(result, result.length))
176 result = `${result.slice(0, -1)}\\!`;
177 result +=
178 anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
179 ? replacement.replace(/^ /, "")
180 : replacement;
181 end = match.index + match[0].length;
182 }
183 const text = content.slice(end);
184 return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
185}
186
187function htmlTagMarkdown(
188 tag: string,
189 anchors: AnchorState,
190 options: { readonly inTableCell?: boolean },
191): string {
192 if (tag.startsWith("<!--")) return "";
193 if (ANCHOR_TAG.test(tag)) {
194 const replacement = anchors.pending.shift() ?? "";
195 if (replacement === "[") anchors.open += 1;
196 else if (replacement) anchors.open -= 1;
197 return replacement;
198 }
199 if (/^<img\b/i.test(tag)) {
200 const src = attribute(tag, "src");
201 if (!src) return "";
202 const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
203 return `})`;
204 }
205 // A blank line inside an open link label would end the paragraph before its "]".
206 const blockBreak = anchors.open === 0 ? "\n\n" : " ";
207 if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
208 if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
209 // A line break would end the table row, so a cell keeps its content on one line.
210 if (/^<br\b/i.test(tag)) return options.inTableCell ? " " : " \n";
211 if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
212 return "";
213}
214
215export function markdownWithHtml(markdown: string): string {
216 if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
217 const edits: Array<{ start: number; end: number; content: string }> = [];
218 const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
219 if (!("children" in node)) return;
220 inTableCell ||= node.type === "tableCell";
221 const children: readonly MarkdownNode[] = node.children;
222 // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
223 const anchors =
224 node.type === "root" || node.type === "blockquote" || node.type === "listItem"
225 ? undefined
226 : anchorMarkdown(
227 children.flatMap((child) =>
228 child.type === "html"
229 ? markdownHtmlTags(child.value)
230 .map((tag) => tag[0])
231 .filter((tag) => ANCHOR_TAG.test(tag))
232 : [],
233 ),
234 );
235 for (const child of children) {
236 const start = child.position?.start.offset;
237 const end = child.position?.end.offset;
238 const linkLabel = inLink || (anchors?.open ?? 0) > 0;
239 if (child.type === "text") {
240 if (linkLabel && start !== undefined && end !== undefined) {
241 const content = escapeLinkLabel(markdown.slice(start, end));
242 if (content !== markdown.slice(start, end)) edits.push({ start, end, content });
243 }
244 continue;
245 }
246 if (child.type !== "html") {
247 visit(child, inTableCell, linkLabel);
248 continue;
249 }
250 const content = markdownHtmlContent(child.value, { anchors, inTableCell });
251 if (start === undefined || end === undefined) continue;
252 // Text before an outermost link is never edited, so this edit cannot overlap another.
253 if (content.startsWith("[") && !linkLabel && bangBefore(markdown, start))
254 edits.push({ start: start - 1, end: start, content: "\\!" });
255 edits.push({ start, end, content });
256 }
257 };
258 visit(parser.parse(markdown), false, false);
259 for (const edit of edits.reverse())
260 markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
261 return markdown;
262}
263
264const INLINE_CODE_SPAN = /`+([^`\r\n]+)`+/g;
265
266export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
267 if (![...markdown.matchAll(INLINE_CODE_SPAN)].some(([, code]) => fileLink.test(code!.trim())))
268 return markdown;
269 const edits: Array<{ start: number; end: number; content: string }> = [];
270 const visit = (node: MarkdownNode) => {
271 if (node.type === "inlineCode") {
272 const start = node.position?.start.offset;
273 const end = node.position?.end.offset;
274 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
275 if (
276 start !== undefined &&
277 end !== undefined &&
278 fileLink.test(node.value) &&
279 !/[<>]/.test(node.value)
280 )
281 edits.push({
282 start,
283 end,
284 content: `[${escaped}](<${escaped}>)`,
285 });
286 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
287 node.children.forEach(visit);
288 };
289 visit(parser.parse(markdown));
290 for (const edit of edits.reverse())
291 markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
292 return markdown;
293}
294
295// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
296function isTableDelimiterRow(line: string): boolean {
297 if (!line.includes("-")) return false;
298 const row = line.replace(/^[ \t>]+/, "").trim();
299 return row
300 .replace(/^\||\|$/g, "")
301 .split("|")
302 .every((cell) => /^:?-+:?$/.test(cell.trim()));
303}
304
305function mayHaveTableUnderText(markdown: string): boolean {
306 if (!markdown.includes("|")) return false;
307 const lines = markdown.split(/\r\n|\r|\n/);
308 for (let index = 2; index < lines.length; index += 1) {
309 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
310 }
311 return false;
312}
313
314/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
315export function markdownWithTableBreaks(markdown: string): string {
316 if (!mayHaveTableUnderText(markdown)) return markdown;
317 const lineStarts: number[] = [];
318 const visit = (node: MarkdownNode) => {
319 if (!("children" in node)) return;
320 node.children.forEach((child, index) => {
321 const previous = node.children[index - 1];
322 const start = child.position?.start;
323 if (
324 child.type === "table" &&
325 previous?.type === "paragraph" &&
326 start?.offset !== undefined &&
327 previous.position?.end.line === start.line - 1
328 )
329 lineStarts.push(
330 Math.max(
331 markdown.lastIndexOf("\n", start.offset - 1),
332 markdown.lastIndexOf("\r", start.offset - 1),
333 ) + 1,
334 );
335 visit(child);
336 });
337 };
338 visit(parser.parse(markdown));
339 for (const lineStart of lineStarts.reverse()) {
340 // Lazy headers can lack container markers; copy the delimiter's markers to the header and blank line.
341 const [, header = "", cells = "", ending = "\n", markers = ""] =
342 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
343 markdown =
344 markdown.slice(0, lineStart) +
345 `${markers.trimEnd()}${ending}${markers}${cells}` +
346 markdown.slice(lineStart + header.length + cells.length);
347 }
348 return markdown;
349}
350
351export function parseMarkdownDocument(markdown: string): Root {
352 return parser.parse(markdownWithHtml(markdown));
353}