import type { BlockNode, InlineNode, ListItem, TodoItem, HtmlAttrs, ParseOptions, ParseResult, SidenoteNode } from "./types.js"; import { parseInline, parseImageAttrs } from "./inline.js"; // ── helpers ──────────────────────────────────────────────────────────────── function parseHtmlAttrs(raw: string): HtmlAttrs { // e.g. ".red#special" or ".foo.bar#id" const attrs: HtmlAttrs = {}; const classMatch = raw.match(/(\.[a-zA-Z0-9_-]+)+/g); const idMatch = raw.match(/#([a-zA-Z0-9_-]+)/); if (classMatch) attrs.class = classMatch.map(c => c.slice(1)); if (idMatch) attrs.id = idMatch[1]!; return attrs; } function attrString(attrs: HtmlAttrs): string { let s = ""; if (attrs.id) s += ` id="${attrs.id}"`; if (attrs.class?.length) s += ` class="${attrs.class.join(" ")}"`; for (const [k, v] of Object.entries(attrs.extra ?? {})) s += ` ${k}="${v}"`; return s; } // ── list parsing ─────────────────────────────────────────────────────────── function isListItem(line: string): "ul" | "ol" | "todo" | null { if (/^- \[[ x]\] /.test(line)) return "todo"; if (/^- /.test(line)) return "ul"; if (/^\d+\. /.test(line)) return "ol"; return null; } function parseList(lines: string[], start: number, kind: "ul" | "ol" | "todo", opts: ParseOptions): { node: BlockNode; end: number } { const items: (ListItem | TodoItem)[] = []; let i = start; while (i < lines.length) { const line = lines[i]!; const todoMatch = line.match(/^- \[([ x])\] (.*)$/); const ulMatch = line.match(/^- (.*)$/); const olMatch = line.match(/^\d+\. (.*)$/); let text = ""; let checked = false; if (kind === "todo" && todoMatch) { checked = todoMatch[1] === "x"; text = todoMatch[2]!; } else if (kind === "ul" && ulMatch && !todoMatch) { text = ulMatch[1]!; } else if (kind === "ol" && olMatch) { text = olMatch[1]!; } else { break; } i++; // collect continuation lines (indented) while (i < lines.length && /^ /.test(lines[i]!)) { text += "\n" + lines[i]!.slice(2); i++; } if (kind === "todo") { (items as TodoItem[]).push({ checked, children: parseInline(text, opts) }); } else { (items as ListItem[]).push({ children: parseInline(text, opts) }); } } if (kind === "todo") { return { node: { type: "todo-list", items: items as TodoItem[] }, end: i }; } else if (kind === "ul") { return { node: { type: "ul", items: items as ListItem[] }, end: i }; } else { return { node: { type: "ol", items: items as ListItem[] }, end: i }; } } // ── [tag] / block parsing ─────────────────────────────────── // Parse a "[tag.class#id]" line, returning tag + attrs or null function parseTagLine(line: string): { tag: string; attrs: HtmlAttrs; inline: string | null } | null { // self-closing: ![...] const selfCloseMatch = line.match(/^!\[([^\]]+)\](.*)$/); if (selfCloseMatch) return null; // handled as image const m = line.match(/^\[([a-zA-Z][a-zA-Z0-9-]*)([.#][^\]]*?)?\](.*)$/); if (!m) return null; const tag = m[1]!; const attrRaw = m[2] ?? ""; const rest = m[3]!.trim(); return { tag, attrs: parseHtmlAttrs(attrRaw), inline: rest || null }; } // A lazy paragraph continuation line stops as soon as the next line looks // like the start of a different block (list, heading, tag, blockquote, etc.) // — otherwise lines like "here is:" immediately followed by "- a list item" // (no blank line between) would get swallowed into the paragraph text. function isBlockStartLine(line: string): boolean { if (/^#{1,6}\s+/.test(line)) return true; if (line.trimStart().startsWith("?? ")) return true; if (line.trim() === "$$$") return true; if (/^```/.test(line)) return true; if (/^!\[/.test(line)) return true; if (parseTagLine(line) !== null) return true; if (line.startsWith("> ") || line.startsWith("| ") || line.startsWith(">> ")) return true; if (isListItem(line) !== null) return true; return false; } // ── main block parser ────────────────────────────────────────────────────── export function parseBlocks(source: string, opts: ParseOptions = {}): ParseResult { const footnotes = new Map(); const references = new Map(); const lines = source.split("\n"); // collect [^id]: value defs — used both as footnote text and as reference-link targets const cleanLines: string[] = []; for (const line of lines) { const m = line.match(/^\[\^([^\]]+)\]:\s*(.+)$/); if (m) { const id = m[1]!; const value = m[2]!.trim(); references.set(id, value); footnotes.set(id, parseInline(value, opts)); } else { cleanLines.push(line); } } const blocks = parseBlockList(cleanLines, opts, references, footnotes); return { blocks, footnotes, references }; } function parseBlockList( lines: string[], opts: ParseOptions, refs: Map, fns: Map ): BlockNode[] { const blocks: BlockNode[] = []; let i = 0; while (i < lines.length) { const raw = lines[i]!; const line = raw.trimEnd(); // blank line — skip if (line.trim() === "") { i++; continue; } // comment if (line.trimStart().startsWith("?? ")) { i++; continue; } // heading const headingMatch = line.match(/^(#{1,6})\s+(.+)$/); if (headingMatch) { const level = headingMatch[1]!.length; let text = headingMatch[2]!; let id: string | undefined; const idMatch = text.match(/\s+\[#([^\]]+)\]$/); if (idMatch) { id = idMatch[1]!; text = text.slice(0, -idMatch[0].length); } blocks.push({ type: "heading", level, children: parseInline(text, opts), ...(id ? { id } : {}) }); i++; continue; } // math block $$$ if (line.trimStart() === "$$$") { i++; const mathLines: string[] = []; while (i < lines.length && lines[i]!.trimEnd() !== "$$$") { mathLines.push(lines[i]!); i++; } i++; // closing $$$ blocks.push({ type: "math-block", value: mathLines.join("\n") }); continue; } // fenced code block ``` const fenceMatch = line.match(/^```(\w*)$/); if (fenceMatch) { const lang = fenceMatch[1]!; i++; const codeLines: string[] = []; while (i < lines.length && !lines[i]!.trimEnd().startsWith("```")) { codeLines.push(lines[i]!); i++; } i++; // closing ``` blocks.push({ type: "code-block", lang, value: codeLines.join("\n") }); continue; } // ... multiline raw html block const rawHtmlMatch = line.match(/^<([a-zA-Z][a-zA-Z0-9]*)(\s[^>]*)?>$/); if (rawHtmlMatch && line.includes("+markup")) { const tag = rawHtmlMatch[1]!; const attrsRaw = (rawHtmlMatch[2] ?? "").replace(/\+markup/, "").trim(); i++; const bodyLines: string[] = []; while (i < lines.length && lines[i]!.trimEnd() !== "") { bodyLines.push(lines[i]!); i++; } i++; // const innerBlocks = parseBlockList(bodyLines, opts, refs, fns); // Render tag with attrs blocks.push({ type: "raw-html", value: `<${tag}${attrsRaw ? " " + attrsRaw : ""}>` }); blocks.push(...innerBlocks); blocks.push({ type: "raw-html", value: `` }); continue; } // markdown-compat image: ![alt](src) if (opts.markdownCompat) { const mdImgMatch = line.match(/^!\[([^\]]*)\]\(([^)]*)\)(.*)$/); if (mdImgMatch) { const alt = mdImgMatch[1]!; const src = mdImgMatch[2]!; const restRaw = mdImgMatch[3]!; const attrs = alt ? { alt } : {}; if (restRaw.trim()) { blocks.push({ type: "paragraph", children: [{ type: "image-inline", src, attrs }, ...parseInline(restRaw, opts)], }); } else { blocks.push({ type: "image", src, attrs }); } i++; continue; } } // self-closing image: ![tag ...] const selfImgMatch = line.match(/^!\[([^\]]+)\](.*)$/); if (selfImgMatch) { const inner = selfImgMatch[1]!; const restRaw = selfImgMatch[2]!; const rest = restRaw.trim(); const { src, attrs } = parseImageAttrs(inner); const tagName = inner.split(/\s/)[0]!; if (tagName === "img") { if (rest) { // text trails on the same line — image wraps inline within a paragraph blocks.push({ type: "paragraph", children: [{ type: "image-inline", src, attrs }, ...parseInline(restRaw, opts)], }); } else { // block image, maybe caption on next line (no blank line in between) let caption: InlineNode[] | undefined; const nextLine = lines[i + 1]; if (nextLine !== undefined && nextLine.trim() !== "" && !nextLine.match(/^[#!\[>|`\-\d]/)) { i++; caption = parseInline(nextLine.trim(), opts); } blocks.push({ type: "image", src, attrs, ...(caption ? { caption } : {}) }); } } else { // other self-closing tags (plot, etc.) — preserve src + key=value attrs const extra: Record = {}; if (src) extra.src = src; Object.assign(extra, attrs); blocks.push({ type: "html-block", tag: tagName, attrs: { extra }, children: [], selfClose: true }); } i++; continue; } // [tag...] block const tagLine = parseTagLine(line); if (tagLine) { const { tag, attrs, inline } = tagLine; if (inline !== null && inline !== "") { // inline form: [div] some content — self-closes at end of line // Check for early-close [/]: the tag only wraps part of the line, so the // whole line stays a single paragraph with the tag rendered inline. const closeIdx = inline.indexOf("[/]"); if (closeIdx !== -1) { const inside = inline.slice(0, closeIdx); const after = inline.slice(closeIdx + 3); const children: InlineNode[] = [ { type: "html", value: `<${tag}${attrString(attrs)}>` }, ...parseInline(inside, opts), { type: "html", value: `` }, ...parseInline(after, opts), ]; blocks.push({ type: "paragraph", children }); } else { const childBlocks: BlockNode[] = [{ type: "paragraph", children: parseInline(inline, opts) }]; blocks.push({ type: "html-block", tag, attrs, children: childBlocks, selfClose: false }); } i++; continue; } // block form — collect children i++; let children: BlockNode[]; const next = lines[i]; if (next !== undefined && next.startsWith(" ")) { // indented region — dedent by 2, blank lines allowed inside (multiple child blocks) const childLines: string[] = []; while (i < lines.length && (lines[i] === "" || lines[i]!.startsWith(" "))) { childLines.push(lines[i] === "" ? "" : lines[i]!.slice(2)); i++; } children = parseBlockList(childLines, opts, refs, fns); } else if (next !== undefined && next.trim() !== "") { // unindented content immediately follows — single contiguous chunk until blank line const childLines: string[] = []; while (i < lines.length && lines[i]!.trim() !== "") { childLines.push(lines[i]!); i++; } children = parseBlockList(childLines, opts, refs, fns); } else { children = []; } blocks.push({ type: "html-block", tag, attrs, children, selfClose: false }); continue; } // markdown blockquote > if (line.startsWith("> ")) { const quoteLines: string[] = []; while (i < lines.length && (lines[i]!.startsWith("> ") || lines[i]!.trim() === "")) { quoteLines.push(lines[i]!.startsWith("> ") ? lines[i]!.slice(2) : ""); i++; } const children = parseBlockList(quoteLines, opts, refs, fns); blocks.push({ type: "markdown-blockquote", children }); continue; } // | blockquote if (line.startsWith("| ")) { const quoteLines: string[] = []; while (i < lines.length && lines[i]!.startsWith("| ")) { quoteLines.push(lines[i]!.slice(2)); i++; } blocks.push({ type: "blockquote", children: parseInline(quoteLines.join("\n"), opts) }); continue; } // >> sidenote (standalone) if (line.startsWith(">> ")) { blocks.push({ type: "sidenote", children: parseInline(line.slice(3), opts) }); i++; continue; } // lists const listKind = isListItem(line); if (listKind) { const { node, end } = parseList(lines, i, listKind, opts); blocks.push(node); i = end; continue; } // paragraph — collect until blank line or the start of a new block, // handling >> sidenote suffix const paraLines: string[] = []; while (i < lines.length && lines[i]!.trim() !== "" && (paraLines.length === 0 || !isBlockStartLine(lines[i]!))) { paraLines.push(lines[i]!); i++; } // check if last line is >> sidenote let sidenote: SidenoteNode | undefined; if (paraLines.length > 0 && paraLines[paraLines.length - 1]!.startsWith(">> ")) { const sn = paraLines.pop()!; sidenote = { type: "sidenote", children: parseInline(sn.slice(3), opts) }; } const paraText = paraLines.join("\n"); if (paraText.trim()) { blocks.push({ type: "paragraph", children: parseInline(paraText, opts), ...(sidenote ? { sidenote } : {}) }); } } return blocks; }