Open History to see the last commit
1import type { Root, RootContent } from "mdast";
2import { unified, type Processor } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths";
6import {
7 isBareLink,
8 remarkEndAutolinksAtScriptPunctuation,
9} from "@t3tools/shared/markdownScriptPunctuationAutolinks";
10import {
11 absoluteFilePathMatches,
12 inlineCodeFilePathCandidate,
13 parseMarkdownFileLink,
14} from "@t3tools/shared/markdownLinks";
15import { isWindowsAbsolutePath } from "@t3tools/shared/path";
16import { hasRightToLeftLetter, textDirection } from "@t3tools/shared/textDirection";
17
18const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
19export type MarkdownNode = Root | RootContent;
20
21interface MarkdownEdit {
22 readonly start: number;
23 readonly end: number;
24 readonly content: string;
25}
26
27/** remark-parse omits one initial BOM from its source offsets, so they index the text after it. */
28export function splitLeadingBom(markdown: string): readonly [bom: string, source: string] {
29 return markdown.startsWith("\uFEFF") ? ["\uFEFF", markdown.slice(1)] : ["", markdown];
30}
31
32function applyMarkdownEdits(markdown: string, edits: MarkdownEdit[]): string {
33 if (edits.length === 0) return markdown;
34 const [bom, source] = splitLeadingBom(markdown);
35 const parts: string[] = [bom];
36 let offset = 0;
37 // AST traversal emits disjoint edits in source order.
38 for (const edit of edits) {
39 parts.push(source.slice(offset, edit.start), edit.content);
40 offset = edit.end;
41 }
42 parts.push(source.slice(offset));
43 return parts.join("");
44}
45
46function decodeCodePoint(codePoint: number, entity: string): string {
47 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
48 return entity;
49 }
50 return String.fromCodePoint(codePoint);
51}
52
53export function decodeHtmlEntities(value: string): string {
54 return value.replace(
55 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
56 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
57 if (decimal) {
58 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
59 }
60 if (hexadecimal) {
61 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
62 }
63 switch (entity.toLowerCase()) {
64 case "&":
65 return "&";
66 case "'":
67 return "'";
68 case ">":
69 return ">";
70 case "<":
71 return "<";
72 case " ":
73 return "\u00a0";
74 case """:
75 return '"';
76 default:
77 return entity;
78 }
79 },
80 );
81}
82
83const HTML_TAG = /<!--[\s\S]*?-->|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi;
84
85function attribute(tag: string, name: string): string | null {
86 const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
87 for (const match of tag.matchAll(attributes)) {
88 if (match[1]?.toLowerCase() === name) {
89 return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? "");
90 }
91 }
92 return null;
93}
94
95function markdownDestination(url: string): string {
96 const normalized = url.replace(/[\r\n]/g, "");
97 const escaped = normalized.replace(/&/g, isWindowsAbsolutePath(normalized) ? "&" : "\\&");
98 return `<${escaped.replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C")}>`;
99}
100
101const ANCHOR_TAG = /^<\/?a[\s/>]/i;
102
103/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
104type AnchorState = { readonly pending: string[]; open: number };
105
106// Code spans keep their text; an odd trailing backslash would escape the closing "]".
107function escapeLinkLabel(text: string): string {
108 return text
109 .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
110 match.startsWith("`") || match.length % 2 === 0
111 ? match
112 : `${match.slice(0, -1)}\\${match.slice(-1)}`,
113 )
114 .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
115}
116
117// An unescaped "!" before the inserted "[" would turn the link into an image.
118function bangBefore(text: string, index: number): boolean {
119 if (text[index - 1] !== "!") return false;
120 let backslashes = 0;
121 while (text[index - 2 - backslashes] === "\\") backslashes += 1;
122 return backslashes % 2 === 0;
123}
124
125/**
126 * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
127 * Markdown link; any other anchor keeps its text unlinked.
128 */
129function anchorMarkdown(tags: readonly string[]): AnchorState {
130 const replacements = tags.map(() => "");
131 const open: Array<{ index: number; href: string | undefined }> = [];
132 tags.forEach((tag, index) => {
133 if (tag[1] !== "/") {
134 const href = attribute(tag, "href")?.trim();
135 open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
136 return;
137 }
138 const opening = open.pop();
139 if (!opening?.href) return;
140 replacements[opening.index] = "[";
141 replacements[index] = `](${markdownDestination(opening.href)})`;
142 });
143 return { pending: replacements, open: 0 };
144}
145
146const REST_OF_LINE_BLANK = /[^\S\r\n]*(?:\r|\n|$)/y;
147const BACKTICK_FENCE_INFO = /[^`\r\n]*(?:\r|\n|$)/y;
148
149function isLineStart(content: string, index: number): boolean {
150 let pos = index;
151 while (pos > 0 && content[pos - 1] === " " && index - pos < 3) pos -= 1;
152 return pos === 0 || content[pos - 1] === "\n" || content[pos - 1] === "\r";
153}
154
155function isEscaped(content: string, index: number): boolean {
156 let backslashes = 0;
157 while (content[index - 1 - backslashes] === "\\") backslashes += 1;
158 return backslashes % 2 === 1;
159}
160
161function isFenceOpening(content: string, opening: RegExpExecArray): boolean {
162 if (opening[0].length < 3 || !isLineStart(content, opening.index)) return false;
163 if (opening[0][0] === "~") return true;
164 BACKTICK_FENCE_INFO.lastIndex = opening.index + opening[0].length;
165 return BACKTICK_FENCE_INFO.test(content);
166}
167
168export function markdownHtmlTags(content: string): RegExpExecArray[] {
169 // An HTML block such as <details> can also contain Markdown fences and code spans.
170 const codeRanges: Array<{ start: number; end: number }> = [];
171 const tags = [...content.matchAll(HTML_TAG)];
172 const delimiters = [...content.matchAll(/`+|~{3,}/g)];
173 let tagIndex = 0;
174 let lastCodeEnd = 0;
175 for (let index = 0; index < delimiters.length; index += 1) {
176 const opening = delimiters[index]!;
177 while (
178 tags[tagIndex] &&
179 (tags[tagIndex]!.index + tags[tagIndex]![0].length <= opening.index ||
180 tags[tagIndex]!.index < lastCodeEnd)
181 ) {
182 tagIndex += 1;
183 }
184 if (tags[tagIndex] && opening.index >= tags[tagIndex]!.index) continue;
185 const fenced = isFenceOpening(content, opening);
186 if (opening[0][0] === "~" && !fenced) continue;
187 const escaped = !fenced && isEscaped(content, opening.index);
188 const opener = escaped ? opening[0].slice(1) : opening[0];
189 if (!opener) continue;
190 const openerStart = opening.index + (escaped ? 1 : 0);
191 let closingIndex = -1;
192 for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) {
193 const closing = delimiters[candidate]!;
194 if (!fenced && isFenceOpening(content, closing)) break;
195 if (!fenced && closing[0] === opener) {
196 closingIndex = candidate;
197 break;
198 }
199 if (!fenced || closing[0][0] !== opener[0] || closing[0].length < opener.length) continue;
200 REST_OF_LINE_BLANK.lastIndex = closing.index + closing[0].length;
201 if (isLineStart(content, closing.index) && REST_OF_LINE_BLANK.test(content)) {
202 closingIndex = candidate;
203 break;
204 }
205 }
206 if (closingIndex === -1) {
207 if (!fenced) continue;
208 // An unclosed fence runs to the end of the content, so no later opener matters.
209 codeRanges.push({ start: opening.index, end: content.length });
210 break;
211 }
212 const closing = delimiters[closingIndex]!;
213 lastCodeEnd = closing.index + closing[0].length;
214 codeRanges.push({ start: openerStart, end: lastCodeEnd });
215 index = closingIndex;
216 }
217 return tags.filter(
218 (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
219 );
220}
221
222/**
223 * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
224 * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
225 */
226export function markdownHtmlContent(
227 content: string,
228 options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
229): string {
230 const tags = markdownHtmlTags(content);
231 const anchors =
232 options.anchors ??
233 anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
234 let result = "";
235 let end = 0;
236 for (const match of tags) {
237 const text = content.slice(end, match.index);
238 result += anchors.open > 0 ? escapeLinkLabel(text) : text;
239 const replacement = htmlTagMarkdown(match[0], anchors, options);
240 if (replacement === "[" && bangBefore(result, result.length))
241 result = `${result.slice(0, -1)}\\!`;
242 result +=
243 anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
244 ? replacement.replace(/^ /, "")
245 : replacement;
246 end = match.index + match[0].length;
247 }
248 const text = content.slice(end);
249 return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
250}
251
252function htmlTagMarkdown(
253 tag: string,
254 anchors: AnchorState,
255 options: { readonly inTableCell?: boolean },
256): string {
257 if (tag.startsWith("<!--")) return "";
258 if (ANCHOR_TAG.test(tag)) {
259 const replacement = anchors.pending.shift() ?? "";
260 if (replacement === "[") anchors.open += 1;
261 else if (replacement) anchors.open -= 1;
262 return replacement;
263 }
264 if (/^<img\b/i.test(tag)) {
265 const src = attribute(tag, "src");
266 if (!src) return "";
267 const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
268 return `})`;
269 }
270 // A raw newline would end the table row; both parsers decode this reference to one inside the cell.
271 const cellBreak = " ";
272 // A blank line inside an open link label would end the paragraph before its "]".
273 const blockBreak = anchors.open > 0 ? " " : options.inTableCell ? cellBreak : "\n\n";
274 if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
275 if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
276 if (/^<br\b/i.test(tag)) return options.inTableCell ? cellBreak : " \n";
277 if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
278 return "";
279}
280
281export function markdownWithHtml(markdown: string): string {
282 if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
283 const [, source] = splitLeadingBom(markdown);
284 const edits: Array<{ start: number; end: number; content: string }> = [];
285 const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
286 if (!("children" in node)) return;
287 inTableCell ||= node.type === "tableCell";
288 const children: readonly MarkdownNode[] = node.children;
289 // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
290 const anchors =
291 node.type === "root" || node.type === "blockquote" || node.type === "listItem"
292 ? undefined
293 : anchorMarkdown(
294 children.flatMap((child) =>
295 child.type === "html"
296 ? markdownHtmlTags(child.value)
297 .map((tag) => tag[0])
298 .filter((tag) => ANCHOR_TAG.test(tag))
299 : [],
300 ),
301 );
302 for (const child of children) {
303 const start = child.position?.start.offset;
304 const end = child.position?.end.offset;
305 const linkLabel = inLink || (anchors?.open ?? 0) > 0;
306 if (child.type === "text") {
307 if (linkLabel && start !== undefined && end !== undefined) {
308 const content = escapeLinkLabel(source.slice(start, end));
309 if (content !== source.slice(start, end)) edits.push({ start, end, content });
310 }
311 continue;
312 }
313 if (child.type !== "html") {
314 visit(child, inTableCell, linkLabel);
315 continue;
316 }
317 const content = markdownHtmlContent(child.value, { anchors, inTableCell });
318 if (start === undefined || end === undefined) continue;
319 // Text before an outermost link is never edited, so this edit cannot overlap another.
320 if (content.startsWith("[") && !linkLabel && bangBefore(source, start))
321 edits.push({ start: start - 1, end: start, content: "\\!" });
322 edits.push({ start, end, content });
323 }
324 };
325 visit(parser.parse(markdown), false, false);
326 return applyMarkdownEdits(markdown, edits);
327}
328
329/** Reference definitions as authored, one line each, so a Windows destination keeps its backslashes. */
330export function markdownReferenceDefinitions(markdown: string): string[] {
331 if (!markdown.includes("]:")) return [];
332 // Flattened as the renderer does it: a raw HTML block hides the definitions inside it.
333 const flattened = markdownWithHtml(markdown);
334 const [, source] = splitLeadingBom(flattened);
335 const definitions: string[] = [];
336 const visit = (node: MarkdownNode, quotes: number) => {
337 if (node.type === "definition") {
338 // A wrapped definition drops its indent and the enclosing quotes' markers, not a literal ">".
339 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "g");
340 definitions.push(
341 source.slice(node.position?.start.offset, node.position?.end.offset).replace(wrap, " "),
342 );
343 }
344 if (!("children" in node)) return;
345 for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
346 };
347 visit(parser.parse(flattened), 0);
348 return definitions;
349}
350
351/**
352 * A reply split into folds and cards renders each fragment as its own document, so each one
353 * carries the reply's definitions. The first definition of a label wins, so the fragment's own
354 * lead: the renderer then prefers them by its own label matching, with none reimplemented here.
355 */
356export function withReferenceDefinitions(
357 fragment: string,
358 replyDefinitions: ReadonlyArray<string>,
359): string {
360 if (replyDefinitions.length === 0 || !fragment.includes("[")) return fragment;
361 const definitions = new Set([...markdownReferenceDefinitions(fragment), ...replyDefinitions]);
362 return `${[...definitions].join("\n")}\n\n${fragment}`;
363}
364
365// Start only at the beginning of a backtick run to avoid retrying every suffix.
366const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
367
368// The native regex stops at whitespace; the shared classifier decides paths with spaces.
369function isInlineCodeFileLink(code: string, fileLink: RegExp): boolean {
370 return fileLink.test(code) || (/\s/.test(code) && inlineCodeFilePathCandidate(code) !== null);
371}
372
373export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
374 return transformNativeMarkdown(markdown, fileLink, false);
375}
376
377function transformNativeMarkdown(
378 markdown: string,
379 fileLink: RegExp | undefined,
380 tableBreaks: boolean,
381): string {
382 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
383 let linkFiles = false;
384 if (fileLink) {
385 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
386 if (isInlineCodeFileLink(code!.trim(), fileLink)) {
387 linkFiles = true;
388 break;
389 }
390 }
391 }
392 const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
393 if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
394 const [, source] = splitLeadingBom(markdown);
395 const edits: MarkdownEdit[] = [];
396 const fileEdits: MarkdownEdit[] = [];
397 let rewritesPipe = false;
398 const visit = (node: MarkdownNode) => {
399 if (linkFiles && node.type === "inlineCode") {
400 const start = node.position?.start.offset;
401 const end = node.position?.end.offset;
402 const escaped = node.value.replace(/[\\[\]&|]/g, "\\$&");
403 if (
404 start !== undefined &&
405 end !== undefined &&
406 fileLink !== undefined &&
407 isInlineCodeFileLink(node.value, fileLink) &&
408 parseMarkdownFileLink(node.value) !== null &&
409 !/[<>]/.test(node.value)
410 ) {
411 const edit = {
412 start,
413 end,
414 content: `[${escaped}](<${escaped}>)`,
415 };
416 edits.push(edit);
417 fileEdits.push(edit);
418 if (node.value.includes("|")) rewritesPipe = true;
419 }
420 } else if (
421 linkProseFiles &&
422 node.type === "text" &&
423 node.position?.start.offset !== undefined
424 ) {
425 const start = node.position.start.offset;
426 const raw = source.slice(start, node.position.end.offset);
427 for (const { index, path } of absoluteFilePathMatches(raw)) {
428 // Source offsets stay valid for paths whose own text needs no Markdown decoding.
429 if (raw !== node.value && /[\\&]/.test(path)) continue;
430 const escaped = path.replace(/[\\[\]&]/g, "\\$&");
431 const edit = {
432 start: start + index,
433 end: start + index + path.length,
434 content: `[${escaped}](<${escaped}>)`,
435 };
436 edits.push(edit);
437 fileEdits.push(edit);
438 }
439 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
440 node.children.forEach((child, index) => {
441 const previous = node.children[index - 1];
442 const start = child.position?.start;
443 if (
444 breakTables &&
445 child.type === "table" &&
446 previous?.type === "paragraph" &&
447 start?.offset !== undefined &&
448 previous.position?.end.line === start.line - 1
449 ) {
450 let lineStart = start.offset;
451 while (lineStart > 0 && !/[\r\n]/.test(source[lineStart - 1]!)) lineStart -= 1;
452 // Replace only the container prefix, leaving cell edits disjoint from the table break.
453 const [, header = "", , ending = "\n", markers = ""] =
454 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(source.slice(lineStart)) ?? [];
455 edits.push({
456 start: lineStart,
457 end: lineStart + header.length,
458 content: `${markers.trimEnd()}${ending}${markers}`,
459 });
460 }
461 visit(child);
462 });
463 };
464 visit(parser.parse(markdown));
465 // Rewritten pipes can change table structure, so preserve the original pass ordering.
466 if (breakTables && rewritesPipe)
467 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
468 return applyMarkdownEdits(markdown, edits);
469}
470
471// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
472function isTableDelimiterRow(line: string): boolean {
473 if (!line.includes("-")) return false;
474 const row = line.replace(/^[ \t>]+/, "").trim();
475 return row
476 .replace(/^\||\|$/g, "")
477 .split("|")
478 .every((cell) => /^:?-+:?$/.test(cell.trim()));
479}
480
481function mayHaveTableUnderText(markdown: string): boolean {
482 if (!markdown.includes("|")) return false;
483 const lines = markdown.split(/\r\n|\r|\n/);
484 for (let index = 2; index < lines.length; index += 1) {
485 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
486 }
487 return false;
488}
489
490/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
491export function markdownWithTableBreaks(markdown: string): string {
492 return transformNativeMarkdown(markdown, undefined, true);
493}
494
495// `>` covers a destination continued on a blockquote line.
496const WINDOWS_DESTINATION = /\](?:\(|:)[\s>]*<?(?:[A-Za-z]:[\\/]|\\\\)/;
497
498interface DestinationToken {
499 readonly start: { readonly offset: number };
500 readonly end: { readonly offset: number };
501}
502
503/**
504 * Markdown reads `C:\work\.t3` as `C:\work.t3`. Web keeps authored Windows destinations
505 * literally (see `remarkKeepWindowsPaths` in shared), so escape their backslashes to give
506 * both parsers here the same path.
507 * Expects authored Markdown: already escaped output would be escaped twice.
508 */
509function markdownWithWindowsPathDestinations(markdown: string): string {
510 // Skips the extra parse for the common message that has no Windows destination.
511 if (!WINDOWS_DESTINATION.test(markdown)) return markdown;
512 const [, source] = splitLeadingBom(markdown);
513 const edits: MarkdownEdit[] = [];
514 function record(
515 this: { resume(): string; sliceSerialize(token: DestinationToken): string },
516 token: DestinationToken,
517 ) {
518 this.resume();
519 const authored = this.sliceSerialize(token);
520 if (!isWindowsAbsolutePath(authored) || !authored.includes("\\") || /[<>]/.test(authored))
521 return;
522 const start = token.start.offset;
523 const end = token.end.offset;
524 const escaped = authored.replaceAll("\\", "\\\\");
525 // A bare destination ends at an unescaped `)`, so wrap it to keep `\)` inside.
526 const angled = source[start - 1] === "<";
527 edits.push({ start, end, content: angled ? escaped : `<${escaped}>` });
528 }
529 unified()
530 .use(remarkParse)
531 .use(remarkGfm)
532 .use(function (this: Processor) {
533 (this.data().fromMarkdownExtensions ??= []).push({
534 exit: { resourceDestinationString: record, definitionDestinationString: record },
535 });
536 })
537 .parse(markdown);
538 return applyMarkdownEdits(markdown, edits);
539}
540
541// Only a bare image paragraph gets a native image slot; a linked one would draw full width.
542const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference";
543const isSpace = (node: MarkdownNode) =>
544 node.type === "break" || (node.type === "text" && node.value.trim() === "");
545
546/**
547 * Native Markdown sizes an image as a block only when it starts its paragraph. These are the
548 * images web puts on their own line: one alone on its source line, and the images that end a
549 * paragraph after its text, like a screenshot after its caption. A row of those can't sit side
550 * by side natively, so each gets its own paragraph.
551 */
552function markdownWithImageParagraphs(markdown: string): string {
553 if (!markdown.includes("![")) return markdown;
554 const [, source] = splitLeadingBom(markdown);
555 const edits = new Map<number, MarkdownEdit>();
556 const split = (start: number, gap: string) => {
557 const ending = /\r\n?|\n/.exec(gap)?.[0] ?? "\n";
558 edits.set(start, { start, end: start + gap.length, content: ending.repeat(2) });
559 };
560 for (const block of parser.parse(markdown).children) {
561 const blockStart = block.position?.start.offset;
562 const blockEnd = block.position?.end.offset;
563 if (block.type !== "paragraph" || blockStart === undefined || blockEnd === undefined) continue;
564 let trailingStart: number | undefined;
565 for (let index = block.children.length - 1; index >= 0; index--) {
566 const child = block.children[index]!;
567 if (isImage(child)) trailingStart = index;
568 else if (!isSpace(child)) break;
569 }
570 block.children.forEach((child, index) => {
571 const start = child.position?.start.offset;
572 const end = child.position?.end.offset;
573 if (!isImage(child) || start === undefined || end === undefined) return;
574 const before = source.slice(blockStart, start);
575 const after = source.slice(end, blockEnd);
576 const ownsLine = /(?:^|\r|\n)[ \t]*$/.test(before) && /^[ \t]*\\?(?:\r\n?|\n|$)/.test(after);
577 if (before.trim() && (ownsLine || (trailingStart !== undefined && index >= trailingStart))) {
578 const gap = /[ \t]*(?:\\?(?:\r\n?|\n)[ \t]*)?$/.exec(before)![0];
579 split(start - gap.length, gap);
580 }
581 if (ownsLine && after.trim()) split(end, /^[ \t]*\\?(?:\r\n?|\n)[ \t]*/.exec(after)![0]);
582 });
583 }
584 return applyMarkdownEdits(
585 markdown,
586 [...edits.values()].sort((a, b) => a.start - b.start),
587 );
588}
589
590// HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
591function normalizedMarkdown(markdown: string): string {
592 return markdownWithWindowsPathDestinations(markdownWithHtml(markdown));
593}
594
595const autolinkParser = unified()
596 .use(remarkParse)
597 .use(remarkGfm)
598 .use(remarkKeepWindowsProsePaths)
599 .use(remarkEndAutolinksAtScriptPunctuation);
600
601// md4c links a bare URL only between whitespace and ASCII punctuation; ASCII neighbors it already handles.
602const blocksNativeAutolink = (character: string | undefined) =>
603 character !== undefined && /[^\0-\x7f\s]/u.test(character);
604
605/**
606 * Wraps bare URLs that touch CJK text or full-width punctuation as `<url>` so md4c links them,
607 * ending each where web does.
608 */
609export function markdownWithNativeAutolinks(markdown: string): string {
610 if (!/[^\0-\x7f]/u.test(markdown) || !/https?:\/\//i.test(markdown)) return markdown;
611 const [, source] = splitLeadingBom(markdown);
612 const edits: MarkdownEdit[] = [];
613 const visit = (node: MarkdownNode) => {
614 if (node.type === "link") {
615 const label = node.children.length === 1 ? node.children[0] : undefined;
616 const start = node.position?.start.offset;
617 const end = node.position?.end.offset;
618 if (
619 label?.type === "text" &&
620 label.value === node.url &&
621 /^https?:\/\/[^\s<>\\]+$/i.test(node.url) &&
622 start !== undefined &&
623 end !== undefined &&
624 isBareLink(node, source) &&
625 (blocksNativeAutolink(source[start - 1]) || blocksNativeAutolink(source[end]))
626 ) {
627 edits.push({ start, end, content: `<${node.url}>` });
628 }
629 return;
630 }
631 // md4c may read `$`, `\(` or `\[` as math when math rendering is on, and a URL inside math is not a link.
632 const inlineBlock =
633 node.type === "paragraph" || node.type === "heading" || node.type === "tableCell";
634 if (
635 inlineBlock &&
636 /\$|\\[([]/.test(source.slice(node.position?.start.offset, node.position?.end.offset))
637 )
638 return;
639 if (node.type !== "linkReference" && "children" in node) node.children.forEach(visit);
640 };
641 visit(autolinkParser.runSync(autolinkParser.parse(source), source));
642 return applyMarkdownEdits(markdown, edits);
643}
644
645export function markdownForNativeParsing(markdown: string): string {
646 return markdownWithImageParagraphs(markdownWithNativeAutolinks(normalizedMarkdown(markdown)));
647}
648
649export function parseMarkdownDocument(markdown: string): Root {
650 return parser.parse(normalizedMarkdown(markdown));
651}
652
653export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
654 return transformNativeMarkdown(markdownForNativeParsing(markdown), fileLink, true);
655}
656
657/** Native media slots only cover standalone images; nested file embeds must become links. */
658export function markdownWithFileEmbeds(
659 markdown: string,
660 label: (href: string, standalone: boolean) => string | null,
661): { markdown: string; fileHrefs: ReadonlySet<string> } {
662 const fileHrefs = new Set<string>();
663 if (!markdown.includes("![")) return { markdown, fileHrefs };
664 const root = parser.parse(markdown);
665 const topLevelBlocks = new Set<MarkdownNode>(root.children);
666 const definitions = new Map<string, string>();
667 const collect = (node: MarkdownNode) => {
668 if (node.type === "definition") {
669 const identifier = node.identifier.toUpperCase();
670 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
671 }
672 if ("children" in node) node.children.forEach(collect);
673 };
674 collect(root);
675 const edits: Array<{ start: number; end: number; content: string }> = [];
676 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
677 if (node.type === "image" || node.type === "imageReference") {
678 const href =
679 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
680 const name = href === undefined ? null : label(href, standalone);
681 const start = node.position?.start.offset;
682 const end = node.position?.end.offset;
683 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
684 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
685 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
686 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
687 fileHrefs.add(href);
688 }
689 }
690 if ("children" in node)
691 node.children.forEach((child) =>
692 visit(
693 child,
694 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
695 insideLink || node.type === "link" || node.type === "linkReference",
696 ),
697 );
698 };
699 visit(root);
700 return { markdown: applyMarkdownEdits(markdown, edits), fileHrefs };
701}
702
703const DIRECTION_MARK = { ltr: "", rtl: "" } as const;
704
705function proseText(node: MarkdownNode): string {
706 if (node.type === "text") return node.value;
707 if (node.type === "inlineCode" || node.type === "code") return " ";
708 if (!("children" in node)) return "";
709 const text = node.children.map(proseText).join("");
710 return node.type === "paragraph" || node.type === "heading" || node.type === "tableCell"
711 ? ` ${text} `
712 : text;
713}
714
715// The native renderer scans inline code too when it picks a paragraph's direction.
716function renderedText(node: MarkdownNode): string {
717 if (node.type === "text" || node.type === "inlineCode") return node.value;
718 if (!("children" in node)) return "";
719 return node.children.map(renderedText).join("");
720}
721
722// A mark inside `[label]` or `<url>` would break the reference or autolink.
723function firstLeafOffset(node: MarkdownNode): number | undefined {
724 if (
725 !("children" in node) ||
726 node.children.length === 0 ||
727 node.type === "link" ||
728 node.type === "linkReference"
729 ) {
730 return node.position?.start.offset;
731 }
732 return firstLeafOffset(node.children[0]!);
733}
734
735/**
736 * The native renderer gives each paragraph the direction of its first letter, so an Arabic
737 * line that opens with an English name renders left to right. Like the web's
738 * `rehypeTextDirection`, each top-level block follows the majority of its words, and a
739 * paragraph whose first letter disagrees gets a direction mark that the renderer reads first.
740 */
741export function markdownWithTextDirection(markdown: string): string {
742 // The parser decodes numeric character references, which can spell right-to-left letters.
743 if (
744 !hasRightToLeftLetter(markdown) &&
745 !(markdown.includes("&#") && hasRightToLeftLetter(decodeHtmlEntities(markdown)))
746 ) {
747 return markdown;
748 }
749 const edits: MarkdownEdit[] = [];
750 for (const block of parser.parse(markdown).children) {
751 if (block.type === "code" || block.type === "html") continue;
752 const direction = textDirection(proseText(block));
753 if (!direction) continue;
754 const mark = (node: MarkdownNode) => {
755 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
756 const offset = firstLeafOffset(node);
757 const first = renderedText(node).match(/\p{L}/u)?.[0];
758 if (offset !== undefined && first && textDirection(first) !== direction) {
759 edits.push({ start: offset, end: offset, content: DIRECTION_MARK[direction] });
760 }
761 return;
762 }
763 if ("children" in node) node.children.forEach(mark);
764 };
765 mark(block);
766 }
767 return applyMarkdownEdits(markdown, edits);
768}