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