import type { Root, RootContent } from "mdast"; import { unified, type Processor } from "unified"; import remarkParse from "remark-parse"; import remarkGfm from "remark-gfm"; import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths"; import { absoluteFilePathMatches, escapeWindowsPathBackslashes, parseMarkdownFileLink, } from "@t3tools/shared/markdownLinks"; import { isWindowsAbsolutePath } from "@t3tools/shared/path"; const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths); export type MarkdownNode = Root | RootContent; interface MarkdownEdit { readonly start: number; readonly end: number; readonly content: string; } function applyMarkdownEdits(markdown: string, edits: MarkdownEdit[]): string { if (edits.length === 0) return markdown; const parts: string[] = []; let offset = 0; // AST traversal emits disjoint edits in source order. for (const edit of edits) { parts.push(markdown.slice(offset, edit.start), edit.content); offset = edit.end; } parts.push(markdown.slice(offset)); return parts.join(""); } function decodeCodePoint(codePoint: number, entity: string): string { if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) { return entity; } return String.fromCodePoint(codePoint); } export function decodeHtmlEntities(value: string): string { return value.replace( /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi, (entity, decimal: string | undefined, hexadecimal: string | undefined) => { if (decimal) { return decodeCodePoint(Number.parseInt(decimal, 10), entity); } if (hexadecimal) { return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity); } switch (entity.toLowerCase()) { case "&": return "&"; case "'": return "'"; case ">": return ">"; case "<": return "<"; case " ": return "\u00a0"; case """: return '"'; default: return entity; } }, ); } const HTML_TAG = /|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi; function attribute(tag: string, name: string): string | null { const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g; for (const match of tag.matchAll(attributes)) { if (match[1]?.toLowerCase() === name) { return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? ""); } } return null; } function markdownDestination(url: string): string { return `<${url.replace(/&/g, "&").replace(//g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`; } const ANCHOR_TAG = /^<\/?a[\s/>]/i; /** Replacements for the anchor tags still ahead, and how many emitted links are open. */ type AnchorState = { readonly pending: string[]; open: number }; // Code spans keep their text; an odd trailing backslash would escape the closing "]". function escapeLinkLabel(text: string): string { return text .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) => match.startsWith("`") || match.length % 2 === 0 ? match : `${match.slice(0, -1)}\\${match.slice(-1)}`, ) .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes)); } // An unescaped "!" before the inserted "[" would turn the link into an image. function bangBefore(text: string, index: number): boolean { if (text[index - 1] !== "!") return false; let backslashes = 0; while (text[index - 2 - backslashes] === "\\") backslashes += 1; return backslashes % 2 === 0; } /** * Pairs `` tags in order. Only a closed anchor with an http(s) or mailto href becomes a * Markdown link; any other anchor keeps its text unlinked. */ function anchorMarkdown(tags: readonly string[]): AnchorState { const replacements = tags.map(() => ""); const open: Array<{ index: number; href: string | undefined }> = []; tags.forEach((tag, index) => { if (tag[1] !== "/") { const href = attribute(tag, "href")?.trim(); open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined }); return; } const opening = open.pop(); if (!opening?.href) return; replacements[opening.index] = "["; replacements[index] = `](${markdownDestination(opening.href)})`; }); return { pending: replacements, open: 0 }; } export function markdownHtmlTags(content: string): RegExpExecArray[] { // An HTML block such as
can also contain Markdown fences and code spans. const codeRanges: Array<{ start: number; end: number }> = []; const tags = [...content.matchAll(HTML_TAG)]; let tagIndex = 0; const delimiters = [...content.matchAll(/`+|~{3,}/g)].filter((delimiter) => { while (tags[tagIndex] && tags[tagIndex]!.index + tags[tagIndex]![0].length <= delimiter.index) tagIndex += 1; const tag = tags[tagIndex]; return !tag || delimiter.index < tag.index; }); for (let index = 0; index < delimiters.length; index += 1) { const opening = delimiters[index]!; const lineStart = content.lastIndexOf("\n", opening.index - 1) + 1; const fenced = opening[0].length >= 3 && /^ {0,3}$/.test(content.slice(lineStart, opening.index)); if (opening[0][0] === "~" && !fenced) continue; let closingIndex = -1; for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) { const closing = delimiters[candidate]!; if (!fenced && closing[0] === opening[0]) { closingIndex = candidate; break; } if (!fenced || closing[0][0] !== opening[0][0] || closing[0].length < opening[0].length) continue; const start = content.lastIndexOf("\n", closing.index - 1) + 1; const nextLine = content.indexOf("\n", closing.index); const end = nextLine === -1 ? content.length : nextLine; if ( /^ {0,3}$/.test(content.slice(start, closing.index)) && /^\s*$/.test(content.slice(closing.index + closing[0].length, end)) ) { closingIndex = candidate; break; } } if (closingIndex === -1) { if (!fenced) continue; // An unclosed fence runs to the end of the content, so no later opener matters. codeRanges.push({ start: opening.index, end: content.length }); break; } const closing = delimiters[closingIndex]!; codeRanges.push({ start: opening.index, end: closing.index + closing[0].length }); index = closingIndex; } return tags.filter( (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end), ); } /** * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags. * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag. */ export function markdownHtmlContent( content: string, options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {}, ): string { const tags = markdownHtmlTags(content); const anchors = options.anchors ?? anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag))); let result = ""; let end = 0; for (const match of tags) { const text = content.slice(end, match.index); result += anchors.open > 0 ? escapeLinkLabel(text) : text; const replacement = htmlTagMarkdown(match[0], anchors, options); if (replacement === "[" && bangBefore(result, result.length)) result = `${result.slice(0, -1)}\\!`; result += anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "") ? replacement.replace(/^ /, "") : replacement; end = match.index + match[0].length; } const text = content.slice(end); return result + (anchors.open > 0 ? escapeLinkLabel(text) : text); } function htmlTagMarkdown( tag: string, anchors: AnchorState, options: { readonly inTableCell?: boolean }, ): string { if (tag.startsWith("