export function unescapeHtml(text: string): string { return text .replaceAll(""", '"') .replaceAll(">", ">") .replaceAll("<", "<") .replaceAll("&", "&"); } function parseAttrs(raw: string): Record { const attrs: Record = {}; const re = /([:\w-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g; let match: RegExpExecArray | null = re.exec(raw); while (match) { attrs[match[1]] = match[2] ?? match[3] ?? ""; match = re.exec(raw); } return attrs; } export function htmlToMarkdown(html: string): string { const tokens = html.match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? []; const out: string[] = []; const list: string[] = []; let inPre = false; let preLang = ""; let preBody = ""; let inline = ""; let heading = 0; let inLi = false; let liTask: boolean | null = null; let liChecked = false; let skipButton = false; let inCell = false; let tableRows: string[][] | null = null; let tableRow: string[] | null = null; let inQuote = false; let inOl = false; let olN = 1; const spanKind: string[] = []; function flushInline(): string { const text = unescapeHtml(inline.replace(/\s+/g, " ").trim()); inline = ""; return text; } for (const token of tokens) { if (token.startsWith(" ${text}`); } else if (text) { out.push(text); } continue; } if (tag === "blockquote") { inQuote = false; continue; } if (tag === "ol") { inOl = false; continue; } if (tag === "span") { const kind = spanKind.pop(); if (kind === "math") { inline += "$"; } if (kind === "comment") { inline += "%%"; } continue; } if (tag === "mark") { inline += "=="; continue; } if (tag === "em" || tag === "i") { inline += "*"; continue; } if (tag === "td" || tag === "th") { if (tableRow) { tableRow.push(flushInline()); } inCell = false; continue; } if (tag === "tr") { if (tableRows && tableRow) { tableRows.push(tableRow); } tableRow = null; continue; } if (tag === "table") { if (tableRows && tableRows.length > 0) { const width = Math.max(...tableRows.map((row) => row.length)); const pad = (row: string[]) => { const cells = [...row]; while (cells.length < width) { cells.push(""); } return `| ${cells.join(" | ")} |`; }; const sep = `| ${Array.from({ length: width }, () => "---").join(" | ")} |`; out.push(pad(tableRows[0])); out.push(sep); for (const row of tableRows.slice(1)) { out.push(pad(row)); } } tableRows = null; continue; } if (tag === "li") { const text = flushInline(); const item = text || list.pop() || ""; if (liTask !== null) { out.push(`- [${liChecked ? "x" : " "}] ${item}`); } else if (inOl) { out.push(`${olN}. ${item}`); olN += 1; } else { out.push(`- ${item}`); } inLi = false; liTask = null; continue; } if (tag === "button") { skipButton = false; continue; } if (tag === "strong" || tag === "b") { inline += "**"; continue; } if (tag === "s" || tag === "del" || tag === "strike") { inline += "~~"; continue; } if (tag === "sup") { inline += "^"; continue; } if (tag === "sub") { inline += "~"; continue; } if (tag === "code" && !inPre) { inline += "`"; continue; } continue; } if (token.startsWith("<")) { const selfClose = token.endsWith("/>"); const body = token.slice(1, token.length - (selfClose ? 2 : 1)).trim(); const space = body.indexOf(" "); const tag = (space === -1 ? body : body.slice(0, space)).toLowerCase(); const attrs = space === -1 ? {} : parseAttrs(body.slice(space + 1)); if (tag === "br") { inline += "\n"; continue; } if (tag === "img") { const src = attrs["data-md-src"] ?? ""; const alt = attrs.alt ?? ""; const kind = attrs["data-md-kind"] ?? "md"; if (kind === "wiki") { inline += alt && alt !== src ? `![[${src}|${alt}]]` : `![[${src}]]`; } else { inline += `![${alt}](${src})`; } continue; } if (tag === "input") { liTask = true; liChecked = Object.prototype.hasOwnProperty.call(attrs, "checked"); continue; } if (tag === "button") { skipButton = true; continue; } if (tag === "pre") { inPre = true; preLang = attrs["data-lang"] ?? ""; preBody = ""; continue; } if (tag === "code") { const langClass = (attrs.class ?? "").split(/\s+/).find((c) => c.startsWith("language-")); if (inPre) { if (langClass) { preLang = langClass.slice("language-".length); } continue; } inline += "`"; continue; } if (tag === "h1" || tag === "h2" || tag === "h3" || tag === "h4" || tag === "h5" || tag === "h6") { heading = Number(tag.slice(1)); continue; } if (tag === "blockquote") { inQuote = true; continue; } if (tag === "ol") { inOl = true; olN = 1; continue; } if (tag === "span") { if ("data-math" in attrs || /data-math/.test(token)) { inline += "$"; spanKind.push("math"); } else if ("data-comment" in attrs || /data-comment/.test(token)) { inline += "%%"; spanKind.push("comment"); } else { spanKind.push(""); } continue; } if (tag === "mark") { inline += "=="; continue; } if (tag === "em" || tag === "i") { inline += "*"; continue; } if (tag === "table") { tableRows = []; continue; } if (tag === "tr") { tableRow = []; continue; } if (tag === "td" || tag === "th") { inCell = true; continue; } if (tag === "li") { inLi = true; const taskItem = attrs["data-type"] === "taskItem" || attrs["data-task"] === "1" || "data-checked" in attrs; liTask = taskItem ? true : null; liChecked = attrs["data-checked"] === "true"; continue; } if (tag === "strong" || tag === "b") { inline += "**"; continue; } if (tag === "s" || tag === "del" || tag === "strike") { inline += "~~"; continue; } if (tag === "sup") { inline += "^"; continue; } if (tag === "sub") { inline += "~"; continue; } if (tag === "a") { const href = attrs.href ?? ""; const kind = /wiki/.test(token) ? "wiki" : "md"; inline += `<>`; continue; } continue; } if (skipButton) { continue; } if (inPre) { preBody += unescapeHtml(token); continue; } const linkMark = inline.match(/<]*)>>$/); if (linkMark) { const kind = linkMark[1]; const href = linkMark[2]; const label = unescapeHtml(token).trim(); inline = inline.slice(0, -linkMark[0].length); if (kind === "wiki") { inline += label && label !== href ? `[[${href}|${label}]]` : `[[${href}]]`; } else { inline += `[${label}](${href})`; } continue; } inline += token; } const trailing = flushInline(); if (trailing) { out.push(trailing); } return out.join("\n"); }