import { tr } from "../i18n/index.ts"; import MarkdownIt from "markdown-it"; import type { Token } from "markdown-it"; import { inlineMathEnd } from "./inlineMath.ts"; import { activeTableFormulas } from "../formulas/index.ts"; import { hasTableDelimiter } from "../editor/markdownTable.ts"; import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts"; const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false }); markdown.use(footnotes); export const escapeHtml = markdown.utils.escapeHtml; // Require a row delimiter so deleting a blank line cannot turn prose into cells. // Markdown-it checks blockquote terminators while it reads a table body. markdown.block.ruler.before("table", "table_prose_boundary", (state, line, _end, silent) => { return silent && state.parentType === "table" && !hasTableDelimiter(state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line])); }, { alt: ["blockquote"] }); // Inline note formats also round-trip through the table cell editor. markdown.inline.ruler.before("emphasis", "note_formats", (state, silent) => { const marker = ["==", "%%", "$"].find(value => state.src.startsWith(value, state.pos)); if (!marker) return false; let end = state.pos + marker.length; if (marker === "$") { end = inlineMathEnd(state.src, state.pos, state.posMax); if (end < 0) return false; } else { for (; end < state.posMax; end++) { if (state.src[end] === "\\") { end++; continue; } if (state.src.startsWith(marker, end)) break; } } if (end >= state.posMax || end === state.pos + marker.length) return false; if (!silent) { const kind = marker === "==" ? "highlight" : marker === "$" ? "math" : "comment"; const token = state.push(`note_${kind}`, "", 0); token.content = state.src.slice(state.pos + marker.length, end); } state.pos = end + marker.length; return true; }); for (const kind of ["highlight", "math", "comment"]) { markdown.renderer.rules[`note_${kind}`] = (tokens, index, _options, env) => { const content = tokens[index].content; return kind === "highlight" ? `${markdown.renderInline(content, env)}` : `${escapeHtml(content)}`; }; } export function plainInlineMarkdown(source: string): string { const literal = (text: string) => text.replace(/&/g, "&").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`); function plain(tokens: Token[]): string { return tokens.map(token => { if (token.type === "note_highlight") return plain(markdown.parseInline(token.content, {})); if (token.type === "hardbreak" || token.type === "softbreak") return "
"; if (token.type === "image") { const target = String(token.attrGet("src") || ""); const label = plain(token.children || []); return token.attrGet("data-md-kind") === "wiki" ? `![[${literal(target)}\\|${label}]]` : `![${label}](<${target.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`; } if (token.children) return plain(token.children); return token.nesting === 0 ? literal(token.content) : ""; }).join(""); } return plain(markdown.parseInline(source, {})); } // Obsidian-style table cells use
for line breaks. Recognize only this // attribute-free tag; arbitrary HTML remains escaped, including inside cells. markdown.inline.ruler.before("html_inline", "note_line_break", (state, silent) => { const match = /^/i.exec(state.src.slice(state.pos)); if (!match) return false; if (!silent) state.push("hardbreak", "br", 0); state.pos += match[0].length; return true; }); const copyIcon = ''; // Parse wiki links as inline tokens, so code spans and fenced code stay literal. markdown.inline.ruler.before("link", "wiki_link", (state, silent) => { const match = /^(!?)\[\[([^\]\n]+)\]\]/.exec(state.src.slice(state.pos)); if (!match) return false; const [target, ...alias] = match[2].split("|"); const label = alias.join("|") || target; if (!target.trim() || !markdown.validateLink(target)) return false; if (!silent) { if (match[1]) { const image = state.push("image", "img", 0); image.attrs = [["src", target.trim()], ["alt", label], ["data-md-kind", "wiki"]]; image.content = label; const text = new MarkdownIt.Token("text", "", 0); text.content = label; image.children = [text]; } else { const open = state.push("link_open", "a", 1); open.attrs = [["href", target.trim()], ["data-kind", "wiki"], ["class", "wiki"]]; state.push("text", "", 0).content = label; state.push("link_close", "a", -1); } } state.pos += match[0].length; return true; }); markdown.core.ruler.after("inline", "note_blocks", state => { for (let i = 0; i < state.tokens.length; i++) { const token = state.tokens[i]; if (token.type !== "inline" || !token.children?.length) continue; const first = token.children[0]; if (first.type !== "text") continue; const item = state.tokens[i - 2]; const task = /^\[([ xX])\]\s+/.exec(first.content); if (task && item?.type === "list_item_open") { const checked = task[1].toLowerCase() === "x"; item.attrJoin("class", `task-list-item${checked ? " is-checked" : ""}`); first.content = first.content.slice(task[0].length); const checkbox = new MarkdownIt.Token("html_inline", "", 0); checkbox.content = ` `; token.children.unshift(checkbox); for (let parent = i - 3; parent >= 0; parent--) { const ancestor = state.tokens[parent]; if ((ancestor.type === "bullet_list_open" || ancestor.type === "ordered_list_open") && ancestor.level < item.level) { ancestor.attrJoin("class", "contains-task-list"); break; } } } const callout = /^\[!(note|tip|info|warning|danger|important|success|question)\][+-]?(?:[ \t]+([^\n]*))?(?:\n|$)/i.exec(first.content); if (callout && item?.type === "blockquote_open") { item.attrJoin("class", "md-callout"); item.attrSet("data-callout", callout[1].toLowerCase()); const title = callout[2] || callout[1].charAt(0).toUpperCase() + callout[1].slice(1).toLowerCase(); first.content = first.content.slice(callout[0].length); if (!first.content && token.children[1]?.type === "softbreak") token.children.splice(1, 1); const heading = new MarkdownIt.Token("html_inline", "", 0); heading.content = `${escapeHtml(title)}`; token.children.unshift(heading); } } }); markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => { if (!tokens[index].attrGet("data-kind")) tokens[index].attrSet("data-kind", "md"); return renderer.renderToken(tokens, index, options); }; markdown.renderer.rules.fence = (tokens, index) => { const token = tokens[index]; const language = token.info.trim().split(/\s+/)[0]; const code = `
${escapeHtml(token.content)}
\n`; return language.toLowerCase() === "mermaid" ? `
${tr("Diagram source")}${code}
\n` : code; }; markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => { const token = tokens[index]; const original = String(token.attrGet("src") || ""); const urls = env?.urls as Map | undefined; const resolved = urls?.get(original) || (/^https?:\/\//i.test(original) ? original : ""); const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env); // Only app-resolved image data or HTTP(S) URLs become image sources. if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `Image unavailable: ${escapeHtml(alt || original)}`; return `${escapeHtml(alt)}`; }; markdown.renderer.rules.table_open = () => '
\n'; markdown.renderer.rules.table_close = () => '
\n'; markdown.core.ruler.after("inline", "table_formulas", state => { activeTableFormulas()?.renderTableFormulas(state.tokens); }); function documentParts(contents: string) { const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(contents); return match ? { body: contents.slice(match[0].length), properties: match[1] } : { body: contents, properties: "" }; } export function documentBodyStart(contents: string): number { return contents.length - documentParts(contents).body.length; } export function markdownImages(contents: string): string[] { const paths = new Set(); function visit(tokens: Token[]) { for (const token of tokens) { if (token.type === "image") paths.add(String(token.attrGet("src") || "")); if (token.children) visit(token.children); } } const env: FootnoteEnvironment = {}; visit(markdown.parse(documentParts(contents).body, env)); for (const note of env.noteFootnotes?.values() ?? []) visit(note.tokens); return [...paths]; } export function renderMarkdownHtml(contents: string, urls: Map): string { const { body, properties } = documentParts(contents); const metadata = properties ? `
Properties
${escapeHtml(properties)}
\n` : ""; const env = { urls }; return metadata + markdown.render(body, env) + renderFootnotes(markdown, env); } export type MarkdownSection = { start: number; end: number; html: string }; // Render with the entire document's reference environment, retaining exact source // offsets so editing one block never serializes the rest of the document. export function renderMarkdownSections(contents: string, urls: Map): MarkdownSection[] { const { body, properties } = documentParts(contents); const offset = contents.length - body.length; const lines = [offset]; for (const match of body.matchAll(/\n/g)) lines.push(offset + match.index + 1); const env = { urls }; const tokens = markdown.parse(body, env); const sections: MarkdownSection[] = []; if (offset) sections.push({ start: 0, end: offset, html: `
Properties
${escapeHtml(properties)}
` }); for (let i = 0; i < tokens.length;) { const token = tokens[i]; const start = token.map ? (lines[token.map[0]] ?? contents.length) : offset; let end = i + 1; if (token.nesting === 1) { let depth = 1; while (end < tokens.length && depth) depth += tokens[end++].nesting; } sections.push({ start, end: contents.length, html: markdown.renderer.render(tokens.slice(i, end), markdown.options, env) }); i = end; } if (!sections.length) sections.push({ start: 0, end: contents.length, html: "" }); sections[0].start = 0; for (let i = 0; i < sections.length - 1; i++) sections[i].end = sections[i + 1].start; return sections; }