/* Page to Markdown by Pablo Murad · https://pablomurad.com Turns the article on the current page (or just the text you selected) into clean Markdown, right in the browser. Nothing is sent anywhere. Edit the result in the panel, then copy it or download it as a .md file. Esc closes. Run it again to toggle. */ (() => { const ID = "page-to-md-root"; const old = document.getElementById(ID); if (old) { old.__close(); return; } const abs = url => { if (!url) return ""; try { const u = new URL(url.trim(), document.baseURI); return /^(https?|mailto|ftp|data):$/.test(u.protocol) ? u.href : ""; } catch (e) { return ""; } }; /* Elements that never carry article text. */ const DROP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "IFRAME", "SVG", "CANVAS", "FORM", "INPUT", "BUTTON", "SELECT", "TEXTAREA", "OBJECT", "EMBED", "DIALOG", "LINK", "META"]); /* Page furniture, skipped when converting a whole page (kept inside a selection). */ const CLUTTER = /(^|[\s_-])(share|sharing|social|comments?|related|reactions|likes|webmentions?|syndication|advert|ads?|promo|newsletter|subscribe|cookie|breadcrumbs?|sidebar|popup|modal|banner)([\s_-]|$)/i; /* Footnote lists. Some sites hide them and show the notes in the margin instead, so they are kept even when hidden. */ const NOTES = "section.footnotes, div.footnotes, .footnotes > ol, [role=doc-endnotes], ol.references"; const selection = getSelection(); const fromSelection = !!(selection && selection.rangeCount && selection.toString().trim()); const skip = el => { if (DROP.has(el.tagName.toUpperCase())) return true; if (el.matches(NOTES)) return false; if (el.hidden || el.getAttribute("aria-hidden") === "true") return true; if (fromSelection) return false; const tag = el.tagName; if (tag === "NAV" || tag === "ASIDE") return true; const role = el.getAttribute("role"); if (role && /^(navigation|complementary|banner|contentinfo|search)$/.test(role)) return true; if ((tag === "HEADER" || tag === "FOOTER") && !el.closest("article")) return true; const hook = `${el.id} ${typeof el.className === "string" ? el.className : ""}`; if (CLUTTER.test(hook) && !el.querySelector("h1")) return true; if (el.isConnected) { const cs = getComputedStyle(el); if (cs.display === "none" || cs.visibility === "hidden") return true; } return false; }; /* Find the element that holds the article. Every block of real prose counts toward its containers; reader modes use a fancier version of the same idea. */ const findRoot = () => { const prose = [...document.body.querySelectorAll("p, pre, blockquote, dd, li")] .filter(el => el.textContent.trim().length >= 25 && !el.closest("nav, aside, footer, [role=navigation]")); const total = el => prose.reduce((n, p) => n + (el.contains(p) ? p.textContent.length : 0), 0); const known = [...document.querySelectorAll( "article, main, [role=main], [itemprop=articleBody], .post-content, .entry-content, .article-body, #content")]; const sized = known.map(el => [el, total(el)]).filter(([, n]) => n >= 400); if (sized.length) { const most = Math.max(...sized.map(([, n]) => n)); /* The innermost container that still holds nearly all of the text. */ const fits = sized.filter(([, n]) => n >= most * 0.85).map(([el]) => el); return fits.find(el => !fits.some(o => o !== el && el.contains(o))) || fits[0]; } const score = new Map(); for (const p of prose) { const el = p.parentElement; if (el) score.set(el, (score.get(el) || 0) + p.textContent.length); } let best = null, bestScore = 0; for (const [el, n] of score) if (n > bestScore) { best = el; bestScore = n; } if (!best || bestScore < 200) return document.body; /* Climb while the parent holds clearly more prose (several sections, not one). */ let current = best, size = total(best); while (current.parentElement && current.parentElement !== document.body) { const up = total(current.parentElement); if (up < size * 1.25) break; current = current.parentElement; size = up; } return current; }; const escText = s => s .replace(/\\/g, "\\\\") .replace(/([*`\[\]<])/g, "\\$1") .replace(/(^|\s)_/g, "$1\\_") .replace(/_(\s|$)/g, "\\_$1"); const fence = (text, min) => { const runs = text.match(/`+/g) || []; const longest = runs.reduce((m, r) => Math.max(m, r.length), 0); return "`".repeat(Math.max(min, longest + 1)); }; const inlineCode = text => { const f = fence(text, 1); const pad = /^`|`$/.test(text) ? " " : ""; return `${f}${pad}${text}${pad}${f}`; }; const wrap = (mark, inner) => { if (/\n\s*\n/.test(inner)) return inner; /* bold or italic around whole blocks: leave it plain */ const m = inner.match(/^(\s*)([\s\S]*?)(\s*)$/); return m[2] ? `${m[1]}${mark}${m[2]}${mark}${m[3]}` : inner; }; const block = s => `\n\n${s.trim()}\n\n`; const imageSrc = img => abs(img.currentSrc || img.getAttribute("src") || img.getAttribute("data-src") || img.getAttribute("data-original") || (img.getAttribute("srcset") || "").split(/\s+/)[0]); const children = (node, ctx) => [...node.childNodes].map(n => conv(n, ctx)).join(""); const list = (el, ctx) => { const ordered = el.tagName === "OL"; let n = parseInt(el.getAttribute("start") || "1", 10) || 1; const tight = [...el.children].every(li => !li.querySelector("p, pre, blockquote, table")); const items = []; for (const li of el.children) { if (li.tagName !== "LI") continue; const marker = ordered ? `${n++}. ` : "- "; const box = li.querySelector(":scope > input[type=checkbox]"); const task = box ? (box.checked ? "[x] " : "[ ] ") : ""; let body = children(li, ctx).trim().replace(/\n{3,}/g, "\n\n"); if (tight) body = body.replace(/\n\n+/g, "\n"); const indent = " ".repeat(marker.length); items.push(marker + task + body.split("\n").map((l, i) => i && l ? indent + l : l).join("\n")); } return block(items.join(tight ? "\n" : "\n\n")); }; const table = (el, ctx) => { const rows = [...el.rows].map(r => [...r.cells].map(c => children(c, ctx).trim().replace(/\s*\n+\s*/g, " ").replace(/\|/g, "\\|") || " ")); if (!rows.length) return ""; const width = Math.max(...rows.map(r => r.length)); rows.forEach(r => { while (r.length < width) r.push(" "); }); const line = r => `| ${r.join(" | ")} |`; const [head, ...body] = rows; return block([line(head), line(head.map(() => "---")), ...body.map(line)].join("\n")); }; /* Footnotes become Markdown footnotes: [^1] in the text, [^1]: at the end. */ const label = (text, id) => { const t = text.replace(/[\[\]\s]/g, ""); return /^\w{1,12}$/.test(t) ? t : ((id || "").match(/(\d+)$/) || [])[1] || ""; }; const noteRef = el => { const a = el.tagName === "A" ? el : el.tagName === "SUP" && el.children.length === 1 ? el.querySelector(":scope > a") : null; if (!a || !/^#/.test(a.getAttribute("href") || "")) return ""; const isRef = a.getAttribute("role") === "doc-noteref" || /footnote|fn-?ref|noteref/i.test(a.className) || el.tagName === "SUP"; return isRef && a.textContent.trim().length <= 6 ? label(a.textContent, a.getAttribute("href")) : ""; }; const isBacklink = a => a.getAttribute("role") === "doc-backlink" || /back/i.test(a.className) || /^[↩↑^⤴\s]+$/.test(a.textContent) || /^#(fnref|cite_ref)/.test(a.getAttribute("href") || ""); const notes = (el, ctx) => { const items = [...el.querySelectorAll("li")].filter(li => li.id); if (!items.length) return ""; return block(items.map((li, i) => { const text = children(li, ctx).trim().replace(/\n{2,}/g, "\n\n ").replace(/\s*\\$/, ""); return `[^${label("", li.id) || i + 1}]: ${text}`; }).join("\n\n")); }; const conv = (node, ctx = {}) => { if (node.nodeType === 3) { if (ctx.pre) return node.nodeValue; return escText(node.nodeValue.replace(/\s+/g, " ")); } if (node.nodeType === 11) return children(node, ctx); if (node.nodeType !== 1 || skip(node)) return ""; const el = node, tag = el.tagName.toUpperCase(); if (el.matches(NOTES)) return notes(el, ctx); const ref = noteRef(el); if (ref) return `[^${ref}]`; switch (tag) { case "H1": case "H2": case "H3": case "H4": case "H5": case "H6": { const text = children(el, ctx).replace(/\s+/g, " ").trim(); return text ? block("#".repeat(+tag[1]) + " " + text) : ""; } case "P": return block(children(el, ctx)); case "BR": return ctx.pre ? "\n" : "\\\n"; case "HR": return block("---"); case "STRONG": case "B": return wrap("**", children(el, ctx)); case "EM": case "I": case "CITE": return wrap("*", children(el, ctx)); case "DEL": case "S": case "STRIKE": return wrap("~~", children(el, ctx)); case "MARK": return wrap("==", children(el, ctx)); case "CODE": case "KBD": case "SAMP": return ctx.pre ? el.textContent : inlineCode(el.textContent); case "PRE": { const code = el.querySelector("code") || el; const hint = `${code.className} ${el.className}`; const lang = (hint.match(/(?:language|lang)-([\w+#-]+)/) || [])[1] || el.getAttribute("data-lang") || code.getAttribute("data-lang") || ""; const text = el.textContent.replace(/\n$/, ""); const f = fence(text, 3); return block(`${f}${lang}\n${text}\n${f}`); } case "BLOCKQUOTE": { const inner = children(el, ctx).trim().replace(/\n{3,}/g, "\n\n"); return inner ? block(inner.split("\n").map(l => l ? "> " + l : ">").join("\n")) : ""; } case "UL": case "OL": return list(el, ctx); case "LI": return block("- " + children(el, ctx).trim()); /* a list item without its list */ case "TABLE": return table(el, ctx); case "A": { const text = children(el, ctx).replace(/\s+/g, " ").trim(); const raw = el.getAttribute("href") || ""; if (isBacklink(el) || /#/.test(raw) && /^[#¶§🔗\s]*$/.test(el.textContent)) return ""; /* anchors and "back to text" */ const href = abs(raw); if (!href || /^#/.test(raw)) return text; if (!text) return ""; const title = el.getAttribute("title"); return `[${text}](${href.replace(/\)/g, encodeURIComponent(")"))}${title ? ` "${title.replace(/"/g, "'")}"` : ""})`; } case "IMG": { const src = imageSrc(el); if (!src || /^data:/.test(src) && src.length > 2000) return ""; const alt = (el.getAttribute("alt") || "").replace(/[\[\]]/g, "").trim(); return `![${alt}](${src.replace(/\)/g, encodeURIComponent(")"))})`; } case "PICTURE": { const img = el.querySelector("img"); return img ? conv(img, ctx) : ""; } case "FIGURE": { const cap = el.querySelector("figcaption"); const body = [...el.childNodes].filter(n => n !== cap).map(n => conv(n, ctx)).join("").trim(); const caption = cap ? escText(cap.textContent.replace(/\s+/g, " ").trim()) : ""; return block(caption ? `${body}\n*${caption}*` : body); } case "VIDEO": case "AUDIO": { const src = abs(el.getAttribute("src") || (el.querySelector("source") || { getAttribute: () => "" }).getAttribute("src")); return src ? block(`[${tag === "VIDEO" ? "Video" : "Audio"}](${src})`) : ""; } case "DL": { const out = []; for (const item of el.children) { const text = children(item, ctx).replace(/\s+/g, " ").trim(); if (!text) continue; out.push(item.tagName === "DT" ? `**${text}**` : `: ${text}`); } return block(out.join("\n")); } case "DETAILS": { const sum = el.querySelector("summary"); const rest = [...el.childNodes].filter(n => n !== sum).map(n => conv(n, ctx)).join(""); return (sum ? block(`**${children(sum, ctx).trim()}**`) : "") + rest; } case "SUP": case "SUB": case "SPAN": case "SMALL": case "ABBR": case "TIME": case "LABEL": case "U": case "Q": return children(el, ctx); default: { const inner = children(el, ctx); const display = el.isConnected ? getComputedStyle(el).display : ""; return /^(inline|contents)/.test(display) ? inner : block(inner); } } }; /* Tidy the result: no runs of blank lines, no trailing spaces, code untouched. */ const tidy = md => { const out = []; let inFence = null; for (const line of md.split("\n")) { const f = line.match(/^\s*(`{3,})/); if (f && (!inFence || f[1].length >= inFence.length)) inFence = inFence ? null : f[1]; out.push(inFence || f ? line : line.replace(/[ \t]+$/, "").replace(/^ +(?![-\d>*]|\s)/, "")); } return out.join("\n").replace(/\n{3,}/g, "\n\n").replace(/(\\\n)\s*\n/g, "\n\n").trim() + "\n"; }; const meta = name => { const el = document.querySelector(`meta[property="${name}"], meta[name="${name}"]`); return el ? el.getAttribute("content").trim() : ""; }; const canonical = (document.querySelector("link[rel=canonical]") || {}).href; const info = { title: (meta("og:title") || document.title || "Untitled").trim(), source: canonical || location.href, author: meta("author") || meta("article:author"), published: (meta("article:published_time") || (document.querySelector("time[datetime]") || { getAttribute: () => "" }).getAttribute("datetime") || "").slice(0, 10), saved: new Date().toISOString().slice(0, 10) }; let body; if (fromSelection) { /* A selection inside a table, list or code block loses its container when cloned, so rebuild the missing parents around it. */ const holder = document.createElement("div"); for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); let part = range.cloneContents(); let el = range.commonAncestorContainer; if (el.nodeType !== 1) el = el.parentElement; if (el && el.closest("table, ul, ol, pre")) { while (el) { const shell = el.cloneNode(false); shell.appendChild(part); part = shell; if (/^(TABLE|UL|OL|PRE)$/.test(el.tagName)) break; el = el.parentElement; } } holder.appendChild(part); } body = tidy(conv(holder)); } else { const root = findRoot(); body = tidy(conv(root)); if (!/^# /m.test(body)) body = `# ${info.title}\n\n${body}`; } const yaml = v => /[:#"'\[\]{}]|^\s|\s$/.test(v) ? `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : v; const frontMatter = () => ["---", ...Object.entries(info).filter(([, v]) => v).map(([k, v]) => `${k}: ${yaml(v)}`), "---", ""].join("\n"); /* Interface in a shadow root, so the page's CSS can't reach it. */ const host = document.createElement("div"); host.id = ID; Object.assign(host.style, { position: "fixed", inset: "0", zIndex: "2147483647" }); const root = host.attachShadow({ mode: "open" }); const css = ` :host { all: initial; } * { box-sizing: border-box; } .shade { position: fixed; inset: 0; background: rgba(15,17,20,.45); } .panel { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(860px, calc(100vw - 32px)); height: min(80vh, 760px); display: flex; flex-direction: column; border-radius: 12px; border: 1px solid #dee2e6; background: #fff; color: #212529; font: 13px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; box-shadow: 0 20px 50px rgba(0,0,0,.25); } @media (prefers-color-scheme: dark) { .panel { background: #1b1e22; color: #e9ecef; border-color: #343a40; } } .head { display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-bottom: 1px solid rgba(128,128,128,.25); } .title { font-weight: 700; font-size: 14px; } .hint { opacity: .65; font-size: 12px; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } textarea { flex: 1; width: 100%; resize: none; border: 0; outline: 0; padding: 14px 16px; background: transparent; color: inherit; font: 12.5px/1.55 ui-monospace, Menlo, Consolas, monospace; tab-size: 4; } .foot { display: flex; align-items: center; gap: 8px; padding: 10px 16px; border-top: 1px solid rgba(128,128,128,.25); } .grow { flex: 1; } button { font: inherit; font-size: 12px; padding: 5px 12px; border-radius: 6px; border: 1px solid #ced4da; background: transparent; color: inherit; cursor: pointer; } button:hover { border-color: #4dabf7; } button.primary { background: #1c7ed6; border-color: #1c7ed6; color: #fff; } .by { font-size: 11px; opacity: .55; margin-left: 8px; } .by a { color: inherit; } label { display: flex; align-items: center; gap: 6px; font-size: 12px; cursor: pointer; } `; try { const sheet = new CSSStyleSheet(); sheet.replaceSync(css); /* works on pages whose CSP blocks inline