@toolpal/markdown-to-doc
publicv2.0published 1 download this weekMIT
Converts Markdown (inline or .md/.txt file) or structured JSON/sheets locally into a formatted Word (.docx), PDF (.pdf), or Excel (.xlsx) file. Supports headings, bold/italic/code, links, lists, code blocks, blockquotes, and tables. Offline, no API key needed.
// Markdown block & inline parser supporting headings, lists, pipe tables, fenced code blocks,
// blockquotes, horizontal rules, and inline bold/italic/code/links.
export type Inline =
| { type: "text"; text: string }
| { type: "bold"; text: string }
| { type: "italic"; text: string }
| { type: "code"; text: string }
| { type: "link"; text: string; url: string };
export type MdBlock =
| { type: "heading"; level: 1 | 2 | 3 | 4; text: string; runs: Inline[] }
| { type: "paragraph"; text: string; runs: Inline[] }
| { type: "bullets"; items: Array<{ text: string; runs: Inline[] }> }
| { type: "numbered"; items: Array<{ text: string; runs: Inline[] }> }
| { type: "code"; language: string; code: string }
| { type: "quote"; text: string; runs: Inline[] }
| { type: "hr" }
| { type: "table"; heading?: string; header: string[]; rows: string[][] };
function isSafeLink(url: string): boolean {
try {
const u = new URL(url.trim());
return u.protocol === "http:" || u.protocol === "https:" || u.protocol === "mailto:";
} catch {
return false;
}
}
export function parseInlines(input: string): Inline[] {
const runs: Inline[] = [];
const re = /(`[^`\n]+`)|(\[([^\]\n]+)\]\(([^)\s]+)\))|(\*\*([^*\n]+)\*\*|__([^_\n]+)__)|(\*([^*\n]+)\*)/g;
let last = 0;
for (const m of input.matchAll(re)) {
const idx = m.index ?? 0;
if (idx > last) runs.push({ type: "text", text: input.slice(last, idx) });
if (m[1]) {
runs.push({ type: "code", text: m[1].slice(1, -1) });
} else if (m[2]) {
const label = m[3];
const url = m[4];
if (isSafeLink(url)) runs.push({ type: "link", text: label, url });
else runs.push({ type: "text", text: `${label} (${url})` });
} else if (m[5]) {
runs.push({ type: "bold", text: m[6] ?? m[7] ?? "" });
} else if (m[8]) {
runs.push({ type: "italic", text: m[9] ?? "" });
}
last = idx + m[0].length;
}
if (last < input.length) runs.push({ type: "text", text: input.slice(last) });
return runs.length > 0 ? runs : [{ type: "text", text: input }];
}
export function plainText(runs: Inline[]): string {
return runs.map((r) => r.text).join("");
}
function splitTableRow(line: string): string[] {
const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
const cells: string[] = [];
let cur = "";
for (let i = 0; i < trimmed.length; i++) {
if (trimmed[i] === "\\" && trimmed[i + 1] === "|") {
cur += "|";
i++;
} else if (trimmed[i] === "|") {
cells.push(cur.trim());
cur = "";
} else {
cur += trimmed[i];
}
}
cells.push(cur.trim());
return cells;
}
function isTableSeparator(line: string): boolean {
const trimmed = line.trim();
if (!trimmed.includes("|") && !trimmed.includes("-")) return false;
const cells = splitTableRow(trimmed);
return cells.length >= 1 && cells.every((c) => /^:?-{3,}:?$/.test(c));
}
export function parseMarkdown(md: string): MdBlock[] {
const lines = md.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n");
const blocks: MdBlock[] = [];
let i = 0;
let lastHeading = "";
while (i < lines.length) {
const raw = lines[i];
const trimmed = raw.trim();
if (!trimmed) {
i++;
continue;
}
// Fenced code block
const fence = trimmed.match(/^(```+|~~~+)\s*([A-Za-z0-9_+-]*)/);
if (fence) {
const marker = fence[1][0];
const len = fence[1].length;
const language = fence[2] ?? "";
const codeLines: string[] = [];
i++;
while (i < lines.length) {
const close = lines[i].trim();
if (close.startsWith(marker.repeat(len)) && close.replaceAll(marker, "").trim() === "") {
i++;
break;
}
codeLines.push(lines[i]);
i++;
}
blocks.push({ type: "code", language, code: codeLines.join("\n") });
continue;
}
// Horizontal rule
if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
blocks.push({ type: "hr" });
i++;
continue;
}
// Heading
const heading = trimmed.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
const level = Math.min(heading[1].length, 4) as 1 | 2 | 3 | 4;
const runs = parseInlines(heading[2].replace(/\s+#+\s*$/, "").trim());
const text = plainText(runs);
lastHeading = text;
blocks.push({ type: "heading", level, text, runs });
i++;
continue;
}
// Pipe table (header row + separator row)
if (trimmed.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
const header = splitTableRow(trimmed).map((c) => plainText(parseInlines(c)));
i += 2;
const rows: string[][] = [];
while (i < lines.length && lines[i].trim().includes("|") && lines[i].trim() !== "") {
const cells = splitTableRow(lines[i]).map((c) => plainText(parseInlines(c)));
while (cells.length < header.length) cells.push("");
rows.push(cells.slice(0, header.length));
i++;
}
blocks.push({
type: "table",
...(lastHeading ? { heading: lastHeading } : {}),
header,
rows,
});
continue;
}
// Blockquote
if (trimmed.startsWith(">")) {
const qLines: string[] = [];
while (i < lines.length && lines[i].trim().startsWith(">")) {
qLines.push(lines[i].trim().replace(/^>\s?/, ""));
i++;
}
const joined = qLines.join(" ").trim();
const runs = parseInlines(joined);
blocks.push({ type: "quote", text: plainText(runs), runs });
continue;
}
// Bullet list
if (/^\s*[-*+•]\s+/.test(raw)) {
const items: Array<{ text: string; runs: Inline[] }> = [];
while (i < lines.length && /^\s*[-*+•]\s+/.test(lines[i])) {
const itemText = lines[i].replace(/^\s*[-*+•]\s+/, "").trim();
const runs = parseInlines(itemText);
items.push({ text: plainText(runs), runs });
i++;
}
blocks.push({ type: "bullets", items });
continue;
}
// Numbered list
if (/^\s*\d+[.)]\s+/.test(raw)) {
const items: Array<{ text: string; runs: Inline[] }> = [];
while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) {
const itemText = lines[i].replace(/^\s*\d+[.)]\s+/, "").trim();
const runs = parseInlines(itemText);
items.push({ text: plainText(runs), runs });
i++;
}
blocks.push({ type: "numbered", items });
continue;
}
// Paragraph
const pLines: string[] = [];
while (i < lines.length) {
const cur = lines[i].trim();
if (
!cur ||
/^(#{1,6}\s+|```|~~~|>|(-{3,}|\*{3,}|_{3,})$)/.test(cur) ||
/^\s*([-*+•]|\d+[.)])\s+/.test(lines[i]) ||
(cur.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1]))
) {
break;
}
pLines.push(cur);
i++;
}
const joined = pLines.join(" ").trim();
const runs = parseInlines(joined);
blocks.push({ type: "paragraph", text: plainText(runs), runs });
}
return blocks;
}