Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownDocument.ts

773 lines30.6 KB

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;
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];
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("");
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);
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 "&amp;":
65 return "&";
66 case "&apos;":
67 return "'";
68 case "&gt;":
69 return ">";
70 case "&lt;":
71 return "<";
72 case "&nbsp;":
73 return "\u00a0";
74 case "&quot;":
75 return '"';
76 default:
77 return entity;
78 }
79 },
80 );
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;
94​
95function markdownDestination(url: string): string {
96 const normalized = url.replace(/[\r\n]/g, "");
97 const escaped = normalized.replace(/&/g, isWindowsAbsolutePath(normalized) ? "&amp;" : "\\&");
98 return `<${escaped.replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C")}>`;
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));
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;
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 };
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";
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;
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);
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 );
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);
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 `![${alt}](${markdownDestination(src)})`;
269 }
270 // A raw newline would end the table row; both parsers decode this reference to one inside the cell.
271 const cellBreak = "&#10;";
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 "";
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);
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;
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}`;
364​
365// Start only at the beginning of a backtick run to avoid retrying every suffix.
366const INLINE_CODE_SPAN = /(?<!`)`+([^`]+)(?=`)/g;
367const INLINE_CODE_LINE_ENDING = /\r\n|[\r\n]/g;
368const INLINE_CODE_SOURCE_CONTINUATION = /(?:\r\n|[\r\n])(?:[ \t]*>[ \t]?)*/g;
369​
370// The native regex stops at whitespace; the shared classifier decides paths with spaces.
371function isInlineCodeFileLink(code: string, fileLink: RegExp): boolean {
372 return fileLink.test(code) || (/\s/.test(code) && inlineCodeFilePathCandidate(code) !== null);
374​
375export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
376 return transformNativeMarkdown(markdown, fileLink, false);
378​
379function transformNativeMarkdown(
380 markdown: string,
381 fileLink: RegExp | undefined,
382 tableBreaks: boolean,
383): string {
384 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
385 let linkFiles = false;
386 if (fileLink) {
387 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
388 if (
389 isInlineCodeFileLink(code!.replace(INLINE_CODE_SOURCE_CONTINUATION, " ").trim(), fileLink)
390 ) {
391 linkFiles = true;
392 break;
393 }
394 }
395 }
396 const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
397 if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
398 const [, source] = splitLeadingBom(markdown);
399 const edits: MarkdownEdit[] = [];
400 const fileEdits: MarkdownEdit[] = [];
401 let rewritesPipe = false;
402 const visit = (node: MarkdownNode) => {
403 if (linkFiles && node.type === "inlineCode") {
404 const start = node.position?.start.offset;
405 const end = node.position?.end.offset;
406 const code = node.value.replace(INLINE_CODE_LINE_ENDING, " ");
407 const escaped = code.replace(/[\\[\]&|]/g, "\\$&");
408 if (
409 start !== undefined &&
410 end !== undefined &&
411 fileLink !== undefined &&
412 isInlineCodeFileLink(code, fileLink) &&
413 parseMarkdownFileLink(code) !== null &&
414 !/[<>]/.test(code)
415 ) {
416 const edit = {
417 start,
418 end,
419 content: `[${escaped}](<${escaped}>)`,
420 };
421 edits.push(edit);
422 fileEdits.push(edit);
423 if (code.includes("|")) rewritesPipe = true;
424 }
425 } else if (
426 linkProseFiles &&
427 node.type === "text" &&
428 node.position?.start.offset !== undefined
429 ) {
430 const start = node.position.start.offset;
431 const raw = source.slice(start, node.position.end.offset);
432 for (const { index, path } of absoluteFilePathMatches(raw)) {
433 // Source offsets stay valid for paths whose own text needs no Markdown decoding.
434 if (raw !== node.value && /[\\&]/.test(path)) continue;
435 const escaped = path.replace(/[\\[\]&]/g, "\\$&");
436 const edit = {
437 start: start + index,
438 end: start + index + path.length,
439 content: `[${escaped}](<${escaped}>)`,
440 };
441 edits.push(edit);
442 fileEdits.push(edit);
443 }
444 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
445 node.children.forEach((child, index) => {
446 const previous = node.children[index - 1];
447 const start = child.position?.start;
448 if (
449 breakTables &&
450 child.type === "table" &&
451 previous?.type === "paragraph" &&
452 start?.offset !== undefined &&
453 previous.position?.end.line === start.line - 1
454 ) {
455 let lineStart = start.offset;
456 while (lineStart > 0 && !/[\r\n]/.test(source[lineStart - 1]!)) lineStart -= 1;
457 // Replace only the container prefix, leaving cell edits disjoint from the table break.
458 const [, header = "", , ending = "\n", markers = ""] =
459 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(source.slice(lineStart)) ?? [];
460 edits.push({
461 start: lineStart,
462 end: lineStart + header.length,
463 content: `${markers.trimEnd()}${ending}${markers}`,
464 });
465 }
466 visit(child);
467 });
468 };
469 visit(parser.parse(markdown));
470 // Rewritten pipes can change table structure, so preserve the original pass ordering.
471 if (breakTables && rewritesPipe)
472 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
473 return applyMarkdownEdits(markdown, edits);
475​
476// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
477function isTableDelimiterRow(line: string): boolean {
478 if (!line.includes("-")) return false;
479 const row = line.replace(/^[ \t>]+/, "").trim();
480 return row
481 .replace(/^\||\|$/g, "")
482 .split("|")
483 .every((cell) => /^:?-+:?$/.test(cell.trim()));
485​
486function mayHaveTableUnderText(markdown: string): boolean {
487 if (!markdown.includes("|")) return false;
488 const lines = markdown.split(/\r\n|\r|\n/);
489 for (let index = 2; index < lines.length; index += 1) {
490 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
491 }
492 return false;
494​
495/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
496export function markdownWithTableBreaks(markdown: string): string {
497 return transformNativeMarkdown(markdown, undefined, true);
499​
500// `>` covers a destination continued on a blockquote line.
501const WINDOWS_DESTINATION = /\](?:\(|:)[\s>]*<?(?:[A-Za-z]:[\\/]|\\\\)/;
502​
503interface DestinationToken {
504 readonly start: { readonly offset: number };
505 readonly end: { readonly offset: number };
507​
508/**
509 * Markdown reads `C:\work\.t3` as `C:\work.t3`. Web keeps authored Windows destinations
510 * literally (see `remarkKeepWindowsPaths` in shared), so escape their backslashes to give
511 * both parsers here the same path.
512 * Expects authored Markdown: already escaped output would be escaped twice.
513 */
514function markdownWithWindowsPathDestinations(markdown: string): string {
515 // Skips the extra parse for the common message that has no Windows destination.
516 if (!WINDOWS_DESTINATION.test(markdown)) return markdown;
517 const [, source] = splitLeadingBom(markdown);
518 const edits: MarkdownEdit[] = [];
519 function record(
520 this: { resume(): string; sliceSerialize(token: DestinationToken): string },
521 token: DestinationToken,
522 ) {
523 this.resume();
524 const authored = this.sliceSerialize(token);
525 if (!isWindowsAbsolutePath(authored) || !authored.includes("\\") || /[<>]/.test(authored))
526 return;
527 const start = token.start.offset;
528 const end = token.end.offset;
529 const escaped = authored.replaceAll("\\", "\\\\");
530 // A bare destination ends at an unescaped `)`, so wrap it to keep `\)` inside.
531 const angled = source[start - 1] === "<";
532 edits.push({ start, end, content: angled ? escaped : `<${escaped}>` });
533 }
534 unified()
535 .use(remarkParse)
536 .use(remarkGfm)
537 .use(function (this: Processor) {
538 (this.data().fromMarkdownExtensions ??= []).push({
539 exit: { resourceDestinationString: record, definitionDestinationString: record },
540 });
541 })
542 .parse(markdown);
543 return applyMarkdownEdits(markdown, edits);
545​
546// Only a bare image paragraph gets a native image slot; a linked one would draw full width.
547const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference";
548const isSpace = (node: MarkdownNode) =>
549 node.type === "break" || (node.type === "text" && node.value.trim() === "");
550​
551/**
552 * Native Markdown sizes an image as a block only when it starts its paragraph. These are the
553 * images web puts on their own line: one alone on its source line, and the images that end a
554 * paragraph after its text, like a screenshot after its caption. A row of those can't sit side
555 * by side natively, so each gets its own paragraph.
556 */
557function markdownWithImageParagraphs(markdown: string): string {
558 if (!markdown.includes("![")) return markdown;
559 const [, source] = splitLeadingBom(markdown);
560 const edits = new Map<number, MarkdownEdit>();
561 const split = (start: number, gap: string) => {
562 const ending = /\r\n?|\n/.exec(gap)?.[0] ?? "\n";
563 edits.set(start, { start, end: start + gap.length, content: ending.repeat(2) });
564 };
565 for (const block of parser.parse(markdown).children) {
566 const blockStart = block.position?.start.offset;
567 const blockEnd = block.position?.end.offset;
568 if (block.type !== "paragraph" || blockStart === undefined || blockEnd === undefined) continue;
569 let trailingStart: number | undefined;
570 for (let index = block.children.length - 1; index >= 0; index--) {
571 const child = block.children[index]!;
572 if (isImage(child)) trailingStart = index;
573 else if (!isSpace(child)) break;
574 }
575 block.children.forEach((child, index) => {
576 const start = child.position?.start.offset;
577 const end = child.position?.end.offset;
578 if (!isImage(child) || start === undefined || end === undefined) return;
579 const before = source.slice(blockStart, start);
580 const after = source.slice(end, blockEnd);
581 const ownsLine = /(?:^|\r|\n)[ \t]*$/.test(before) && /^[ \t]*\\?(?:\r\n?|\n|$)/.test(after);
582 if (before.trim() && (ownsLine || (trailingStart !== undefined && index >= trailingStart))) {
583 const gap = /[ \t]*(?:\\?(?:\r\n?|\n)[ \t]*)?$/.exec(before)![0];
584 split(start - gap.length, gap);
585 }
586 if (ownsLine && after.trim()) split(end, /^[ \t]*\\?(?:\r\n?|\n)[ \t]*/.exec(after)![0]);
587 });
588 }
589 return applyMarkdownEdits(
590 markdown,
591 [...edits.values()].sort((a, b) => a.start - b.start),
592 );
594​
595// HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
596function normalizedMarkdown(markdown: string): string {
597 return markdownWithWindowsPathDestinations(markdownWithHtml(markdown));
599​
600const autolinkParser = unified()
601 .use(remarkParse)
602 .use(remarkGfm)
603 .use(remarkKeepWindowsProsePaths)
604 .use(remarkEndAutolinksAtScriptPunctuation);
605​
606// md4c links a bare URL only between whitespace and ASCII punctuation; ASCII neighbors it already handles.
607const blocksNativeAutolink = (character: string | undefined) =>
608 character !== undefined && /[^\0-\x7f\s]/u.test(character);
609​
610/**
611 * Wraps bare URLs that touch CJK text or full-width punctuation as `<url>` so md4c links them,
612 * ending each where web does.
613 */
614export function markdownWithNativeAutolinks(markdown: string): string {
615 if (!/[^\0-\x7f]/u.test(markdown) || !/https?:\/\//i.test(markdown)) return markdown;
616 const [, source] = splitLeadingBom(markdown);
617 const edits: MarkdownEdit[] = [];
618 const visit = (node: MarkdownNode) => {
619 if (node.type === "link") {
620 const label = node.children.length === 1 ? node.children[0] : undefined;
621 const start = node.position?.start.offset;
622 const end = node.position?.end.offset;
623 if (
624 label?.type === "text" &&
625 label.value === node.url &&
626 /^https?:\/\/[^\s<>\\]+$/i.test(node.url) &&
627 start !== undefined &&
628 end !== undefined &&
629 isBareLink(node, source) &&
630 (blocksNativeAutolink(source[start - 1]) || blocksNativeAutolink(source[end]))
631 ) {
632 edits.push({ start, end, content: `<${node.url}>` });
633 }
634 return;
635 }
636 // md4c may read `$`, `\(` or `\[` as math when math rendering is on, and a URL inside math is not a link.
637 const inlineBlock =
638 node.type === "paragraph" || node.type === "heading" || node.type === "tableCell";
639 if (
640 inlineBlock &&
641 /\$|\\[([]/.test(source.slice(node.position?.start.offset, node.position?.end.offset))
642 )
643 return;
644 if (node.type !== "linkReference" && "children" in node) node.children.forEach(visit);
645 };
646 visit(autolinkParser.runSync(autolinkParser.parse(source), source));
647 return applyMarkdownEdits(markdown, edits);
649​
650export function markdownForNativeParsing(markdown: string): string {
651 return markdownWithImageParagraphs(markdownWithNativeAutolinks(normalizedMarkdown(markdown)));
653​
654export function parseMarkdownDocument(markdown: string): Root {
655 return parser.parse(normalizedMarkdown(markdown));
657​
658export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
659 return transformNativeMarkdown(markdownForNativeParsing(markdown), fileLink, true);
661​
662/** Native media slots only cover standalone images; nested file embeds must become links. */
663export function markdownWithFileEmbeds(
664 markdown: string,
665 label: (href: string, standalone: boolean) => string | null,
666): { markdown: string; fileHrefs: ReadonlySet<string> } {
667 const fileHrefs = new Set<string>();
668 if (!markdown.includes("![")) return { markdown, fileHrefs };
669 const root = parser.parse(markdown);
670 const topLevelBlocks = new Set<MarkdownNode>(root.children);
671 const definitions = new Map<string, string>();
672 const collect = (node: MarkdownNode) => {
673 if (node.type === "definition") {
674 const identifier = node.identifier.toUpperCase();
675 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
676 }
677 if ("children" in node) node.children.forEach(collect);
678 };
679 collect(root);
680 const edits: Array<{ start: number; end: number; content: string }> = [];
681 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
682 if (node.type === "image" || node.type === "imageReference") {
683 const href =
684 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
685 const name = href === undefined ? null : label(href, standalone);
686 const start = node.position?.start.offset;
687 const end = node.position?.end.offset;
688 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
689 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
690 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
691 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
692 fileHrefs.add(href);
693 }
694 }
695 if ("children" in node)
696 node.children.forEach((child) =>
697 visit(
698 child,
699 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
700 insideLink || node.type === "link" || node.type === "linkReference",
701 ),
702 );
703 };
704 visit(root);
705 return { markdown: applyMarkdownEdits(markdown, edits), fileHrefs };
707​
708const DIRECTION_MARK = { ltr: "‎", rtl: "‏" } as const;
709​
710function proseText(node: MarkdownNode): string {
711 if (node.type === "text") return node.value;
712 if (node.type === "inlineCode" || node.type === "code") return " ";
713 if (!("children" in node)) return "";
714 const text = node.children.map(proseText).join("");
715 return node.type === "paragraph" || node.type === "heading" || node.type === "tableCell"
716 ? ` ${text} `
717 : text;
719​
720// The native renderer scans inline code too when it picks a paragraph's direction.
721function renderedText(node: MarkdownNode): string {
722 if (node.type === "text" || node.type === "inlineCode") return node.value;
723 if (!("children" in node)) return "";
724 return node.children.map(renderedText).join("");
726​
727// A mark inside `[label]` or `<url>` would break the reference or autolink.
728function firstLeafOffset(node: MarkdownNode): number | undefined {
729 if (
730 !("children" in node) ||
731 node.children.length === 0 ||
732 node.type === "link" ||
733 node.type === "linkReference"
734 ) {
735 return node.position?.start.offset;
736 }
737 return firstLeafOffset(node.children[0]!);
739​
740/**
741 * The native renderer gives each paragraph the direction of its first letter, so an Arabic
742 * line that opens with an English name renders left to right. Like the web's
743 * `rehypeTextDirection`, each top-level block follows the majority of its words, and a
744 * paragraph whose first letter disagrees gets a direction mark that the renderer reads first.
745 */
746export function markdownWithTextDirection(markdown: string): string {
747 // The parser decodes numeric character references, which can spell right-to-left letters.
748 if (
749 !hasRightToLeftLetter(markdown) &&
750 !(markdown.includes("&#") && hasRightToLeftLetter(decodeHtmlEntities(markdown)))
751 ) {
752 return markdown;
753 }
754 const edits: MarkdownEdit[] = [];
755 for (const block of parser.parse(markdown).children) {
756 if (block.type === "code" || block.type === "html") continue;
757 const direction = textDirection(proseText(block));
758 if (!direction) continue;
759 const mark = (node: MarkdownNode) => {
760 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
761 const offset = firstLeafOffset(node);
762 const first = renderedText(node).match(/\p{L}/u)?.[0];
763 if (offset !== undefined && first && textDirection(first) !== direction) {
764 edits.push({ start: offset, end: offset, content: DIRECTION_MARK[direction] });
765 }
766 return;
767 }
768 if ("children" in node) node.children.forEach(mark);
769 };
770 mark(block);
771 }
772 return applyMarkdownEdits(markdown, edits);