Skip to content

HTML to Markdown Converter — Zig source

Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.

This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

// html-to-markdown — supported HTML subset → Markdown converter. Zig port
// (canonical TS: src/lib/html-to-markdown.ts; Go twin:
// cli/html-to-markdown/html-to-markdown.go).
//
// Language: Zig 0.17 (unmanaged ArrayList API, arena allocation).
// CosmoDev polyglot showcase port of the `html-to-markdown` tool.
//
// A hand-rolled single-scan tag parser (no DOM) builds a node forest, then a
// renderer emits Markdown blocks: h1-h6, p/div/blockquote, pre fences with
// the language taken from class="language-*", ul/ol with 2-space (ul) and
// 4-space (ol) nested indent, hr, br as two-spaces-newline; inline marks
// strong/b/em/i/del/s/code render empty emphasis as nothing, links keep
// verbatim titles, images decode alt/src. Unknown tags are transparent,
// stray closers are ignored, unclosed tags auto-close at EOF, and text nodes
// backslash-escape \ ` * _ [ ]. A '<' with no closing '>' is the one error.
//
// The Zig stdlib has no regex, so every TS regex became a byte scanner over
// []const u8, and no WHATWG entity table, so decode hand-rolls the fallback
// — numeric (&#NN; / &#xHH;) plus the six named entities (amp lt gt quot
// apos nbsp), single pass, no double-decode ("x &amp;lt; y" stays
// "x &lt; y"; the Go twin uses the full stdlib html.UnescapeString table).
// Text is UTF-8; code points above U+007F (NBSP, etc.) are decoded and
// matched against the JS \s set in the trim/whitespace-collapse passes,
// mirroring the TS twin's /\s+/g. Only the allocator can fail; every byte of
// the Result lives in the passed arena.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Test: zig test zig.zig

const std = @import("std");

pub const Result = struct {
    /// Rendered Markdown. Allocator-owned (pass an arena); caller frees.
    output: []const u8 = "",
    /// Set iff a '<' found no closing '>' (TS: error: string).
    err: ?[]const u8 = null,
};

/// VOID in the TS lib — tags that never open a scope.
const void_tags = [_][]const u8{ "br", "hr", "img", "meta", "link", "input", "source" };

/// BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks.
const block_tags = [_][]const u8{
    "p", "div", "blockquote", "pre", "ul", "ol", "hr",
    "h1", "h2", "h3", "h4", "h5", "h6",
};

const NamedEntity = struct { name: []const u8, value: []const u8 };

/// The six named entities; the TS lib uses the full WHATWG shared table.
const named_entities = [_]NamedEntity{
    .{ .name = "amp", .value = "&" },
    .{ .name = "lt", .value = "<" },
    .{ .name = "gt", .value = ">" },
    .{ .name = "quot", .value = "\"" },
    .{ .name = "apos", .value = "'" },
    .{ .name = "nbsp", .value = "\u{00a0}" },
};

/// One forest node: text (is_elem false) or element.
const Node = struct {
    is_elem: bool,
    tag: []const u8 = "",
    text: []const u8 = "",
    attrs: std.ArrayList(Attr) = .empty,
    children: std.ArrayList(*Node) = .empty,
};

const Attr = struct { name: []const u8, value: []const u8 };

fn inList(list: []const []const u8, s: []const u8) bool {
    for (list) |x| if (std.mem.eql(u8, x, s)) return true;
    return false;
}

fn isAsciiLetter(c: u8) bool {
    return std.ascii.isAlphabetic(c);
}

fn isAsciiDigit(c: u8) bool {
    return std.ascii.isDigit(c);
}

/// Byte length of the JS-\s code point at s[i], or 0 (UTF-8 aware: NBSP,
/// U+1680, U+2000-200A, U+2028/2029, U+202F, U+205F, U+3000, U+FEFF).
fn jsSpaceAt(s: []const u8, i: usize) usize {
    const b = s[i];
    if (b == ' ' or b == '\t' or b == '\n' or b == 0x0b or b == 0x0c or b == '\r') return 1;
    if (b < 0x80) return 0;
    const seq = std.unicode.utf8ByteSequenceLength(b) catch return 0;
    if (i + seq > s.len) return 0;
    const cp = std.unicode.utf8Decode(s[i .. i + seq]) catch return 0;
    return switch (cp) {
        0xA0, 0x1680, 0x2000...0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF => seq,
        else => 0,
    };
}

/// Byte length of the JS-\s code point ending at s[e], or 0.
fn jsSpaceEnd(s: []const u8, e: usize) usize {
    if (e == 0) return 0;
    var start = e - 1;
    while (start > 0 and (s[start] & 0xC0) == 0x80) start -= 1; // back to cp start
    const l = jsSpaceAt(s, start);
    if (l > 0 and start + l == e) return l;
    return 0;
}

/// JS String.prototype.trim over the JS-\s class.
fn trimJs(s: []const u8) []const u8 {
    var b: usize = 0;
    var e: usize = s.len;
    while (b < e) {
        const l = jsSpaceAt(s, b);
        if (l == 0) break;
        b += l;
    }
    while (e > b) {
        const l = jsSpaceEnd(s, e);
        if (l == 0) break;
        e -= l;
    }
    return s[b..e];
}

/// Collapse any run of JS whitespace to a single space — /\s+/g, ' '.
fn collapseWs(a: std.mem.Allocator, s: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    var i: usize = 0;
    while (i < s.len) {
        const l = jsSpaceAt(s, i);
        if (l > 0) {
            try out.append(a, ' ');
            while (i < s.len and jsSpaceAt(s, i) > 0) i += jsSpaceAt(s, i);
        } else {
            try out.append(a, s[i]);
            i += 1;
        }
    }
    return out.toOwnedSlice(a);
}

fn hexVal(c: u8) u32 {
    if (c >= '0' and c <= '9') return c - '0';
    if (c >= 'a' and c <= 'f') return c - 'a' + 10;
    return c - 'A' + 10;
}

fn isHexDigit(c: u8) bool {
    return (c >= '0' and c <= '9') or (c >= 'a' and c <= 'f') or (c >= 'A' and c <= 'F');
}

/// Decode every recognized reference in s. Unknown refs and stray '&' pass
/// through untouched; "x &amp;lt; y" stays "x &lt; y". Byte scanning: '&' and
/// the reference grammar are ASCII, so every other byte passes through
/// verbatim.
fn decodeEntities(a: std.mem.Allocator, s: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    var i: usize = 0;
    while (i < s.len) {
        const amp = std.mem.indexOfScalarPos(u8, s, i, '&') orelse {
            try out.appendSlice(a, s[i..]);
            break;
        };
        try out.appendSlice(a, s[i..amp]);
        const p = amp + 1;
        var matched = false;
        var next = amp + 1;
        if (p < s.len and s[p] == '#') { // &#NN; / &#xHH;
            const hex = p + 1 < s.len and (s[p + 1] == 'x' or s[p + 1] == 'X');
            var d = if (hex) p + 2 else p + 1;
            const start = d;
            while (d < s.len and (if (hex) isHexDigit(s[d]) else isAsciiDigit(s[d]))) d += 1;
            if (d > start and d < s.len and s[d] == ';' and d - start <= 7) {
                var cp: u32 = 0;
                for (s[start..d]) |c| cp = cp * (if (hex) @as(u32, 16) else 10) + hexVal(c);
                // Lone surrogates are not valid standalone scalars.
                if (!((cp >= 0xD800 and cp <= 0xDFFF) or cp > 0x10FFFF)) {
                    var buf: [4]u8 = undefined;
                    const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch 0;
                    if (n > 0) {
                        try out.appendSlice(a, buf[0..n]);
                        matched = true;
                        next = d + 1;
                    }
                }
            }
        } else if (p < s.len and isAsciiLetter(s[p])) { // &name;
            var d = p + 1;
            while (d < s.len and std.ascii.isAlphanumeric(s[d])) d += 1;
            if (d < s.len and s[d] == ';') {
                const name = s[p..d];
                for (named_entities) |ent| {
                    if (std.mem.eql(u8, ent.name, name)) {
                        try out.appendSlice(a, ent.value);
                        matched = true;
                        next = d + 1;
                        break;
                    }
                }
            }
        }
        if (!matched) {
            try out.append(a, '&');
            next = amp + 1;
        }
        i = next;
    }
    return out.toOwnedSlice(a);
}

/// Backslash-escape the Markdown-significant \ ` * _ [ ].
fn escapeMarkdown(a: std.mem.Allocator, s: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    for (s) |c| {
        if (c == '\\' or c == '`' or c == '*' or c == '_' or c == '[' or c == ']') try out.append(a, '\\');
        try out.append(a, c);
    }
    return out.toOwnedSlice(a);
}

/// `language-([\w-]+)` — the first occurrence whose capture is non-empty.
fn langFromClass(class: []const u8) []const u8 {
    var from: usize = 0;
    while (std.mem.indexOfPos(u8, class, from, "language-")) |off| {
        const start = off + "language-".len;
        var e = start;
        while (e < class.len and
            (std.ascii.isAlphanumeric(class[e]) or class[e] == '_' or class[e] == '-')) e += 1;
        if (e > start) return class[start..e];
        from = start;
    }
    return "";
}

/// The TS attr regex as a scanner, resumed left-to-right like the /g loop:
/// name [a-zA-Z-]+, optional \s*=\s*("..."|'...'|bare), resume after the
/// value when one matched, else after the name. Values stay RAW (href/src/
/// alt are entity-decoded at use; titles verbatim); the strip mirrors TS
/// am[2].slice(1, -1): quoted values lose their quotes, bare values lose
/// their first and last bytes (same quirk the Go twin keeps for lock-step).
fn scanAttrs(a: std.mem.Allocator, elem: *Node, body: []const u8, from: usize) !void {
    var p = from;
    while (p < body.len) {
        const c = body[p];
        if (isAsciiLetter(c) or c == '-') {
            var q = p + 1;
            while (q < body.len and (isAsciiLetter(body[q]) or body[q] == '-')) q += 1;
            var r = q;
            while (r < body.len and jsSpaceAt(body, r) > 0) r += 1;
            var vend = q;
            var val: ?[]const u8 = null;
            if (r < body.len and body[r] == '=') {
                var r2 = r + 1;
                while (r2 < body.len and jsSpaceAt(body, r2) > 0) r2 += 1;
                if (r2 < body.len) {
                    const vc = body[r2];
                    if (vc == '"' or vc == '\'') {
                        var e = r2 + 1;
                        while (e < body.len and body[e] != vc) e += 1;
                        if (e < body.len) { // closing quote — value includes quotes
                            val = body[r2 .. e + 1];
                            vend = e + 1;
                        }
                    }
                    if (val == null) { // bare [^\s>]+ — '>' already consumed
                        var e = r2;
                        while (e < body.len and jsSpaceAt(body, e) == 0 and body[e] != '>') e += 1;
                        if (e > r2) {
                            val = body[r2..e];
                            vend = e;
                        } else {
                            vend = q; // no value — the group backtracks off
                        }
                    }
                } else {
                    vend = q;
                }
            }
            // strip mirrors TS am[2].slice(1, -1)
            const stripped: []const u8 = if (val) |v|
                (if (v.len >= 2) v[1 .. v.len - 1] else "")
            else
                "";
            const lname = try a.dupe(u8, body[p..q]);
            for (lname) |*ch| ch.* = std.ascii.toLower(ch.*);
            try elem.attrs.append(a, .{ .name = lname, .value = stripped });
            p = vend;
        } else {
            p += 1;
        }
    }
}

fn textNode(a: std.mem.Allocator, v: []const u8) !*Node {
    const n = try a.create(Node);
    n.* = .{ .is_elem = false, .text = v };
    return n;
}

const ParseResult = struct { root: *Node, err: ?[]const u8 = null };

/// Parse into a node forest. The synthetic root holds the top-level nodes.
/// Attribute values may be double-quoted, single-quoted or bare; a quoted
/// value may contain '>'. err is set only for the one error.
fn parseHtml(a: std.mem.Allocator, raw: []const u8) !ParseResult {
    const root = try a.create(Node);
    root.* = .{ .is_elem = true };
    var stack: std.ArrayList(*Node) = .empty;
    try stack.append(a, root);
    var i: usize = 0;
    while (i < raw.len) {
        const top = stack.items[stack.items.len - 1];
        const lt = std.mem.indexOfScalarPos(u8, raw, i, '<') orelse {
            try top.children.append(a, try textNode(a, raw[i..]));
            break;
        };
        if (lt > i) try top.children.append(a, try textNode(a, raw[i..lt]));
        // Find the tag's '>', skipping quoted attribute values.
        var j = lt + 1;
        var quote: u8 = 0;
        while (j < raw.len and (raw[j] != '>' or quote != 0)) {
            const c = raw[j];
            if (quote == 0 and (c == '"' or c == '\'')) quote = c else if (quote != 0 and c == quote) quote = 0;
            j += 1;
        }
        if (j >= raw.len) return .{ .root = root, .err = "Unclosed tag" };
        const inner = trimJs(raw[lt + 1 .. j]);
        i = j + 1;

        if (std.mem.startsWith(u8, inner, "!--")) continue; // comment
        if (inner.len > 0 and inner[0] == '!') continue; // doctype
        const closing = inner.len > 0 and inner[0] == '/';
        var body = if (closing) inner[1..] else inner;
        // TS inner.replace(/\/$/, '') — one trailing slash
        if (!closing and body.len > 0 and body[body.len - 1] == '/') body = body[0 .. body.len - 1];

        // ^[a-zA-Z][a-zA-Z0-9-]* — else drop (browsers would show it as text)
        if (body.len == 0 or !isAsciiLetter(body[0])) continue;
        var name_end: usize = 1;
        while (name_end < body.len and
            (std.ascii.isAlphanumeric(body[name_end]) or body[name_end] == '-')) name_end += 1;
        const lname = try a.dupe(u8, body[0..name_end]);
        for (lname) |*ch| ch.* = std.ascii.toLower(ch.*);

        if (closing) {
            var k = stack.items.len;
            while (k > 1) {
                k -= 1;
                if (std.mem.eql(u8, stack.items[k].tag, lname)) {
                    stack.shrinkRetainingCapacity(k);
                    break;
                }
            }
            continue;
        }

        const elem = try a.create(Node);
        elem.* = .{ .is_elem = true, .tag = lname };
        try scanAttrs(a, elem, body, name_end);
        try stack.items[stack.items.len - 1].children.append(a, elem);
        if (!inList(&void_tags, elem.tag) and !std.mem.endsWith(u8, body, "/")) {
            try stack.append(a, elem);
        }
    }
    return .{ .root = root };
}

/// Attribute value by (lowercased) name; "" when absent — TS attrs.href ?? ''.
fn attrOf(nd: *const Node, name: []const u8) []const u8 {
    for (nd.attrs.items) |at| {
        if (std.mem.eql(u8, at.name, name)) return at.value;
    }
    return "";
}

fn isBlock(nd: *const Node) bool {
    return nd.is_elem and inList(&block_tags, nd.tag);
}

/// Inline content of one block: marks, links, images, escaped text.
fn renderInline(a: std.mem.Allocator, nodes: []const *Node) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    for (nodes) |nd| {
        if (!nd.is_elem) {
            // TS order: escape(decode(v)) then the \s+ collapse.
            try out.appendSlice(a, try collapseWs(a, try escapeMarkdown(a, try decodeEntities(a, nd.text))));
        } else if (std.mem.eql(u8, nd.tag, "br")) {
            try out.appendSlice(a, "  \n");
        } else if (std.mem.eql(u8, nd.tag, "strong") or std.mem.eql(u8, nd.tag, "b")) {
            const inner = trimJs(try renderInline(a, nd.children.items));
            if (inner.len > 0) { // empty emphasis renders as nothing
                try out.appendSlice(a, "**");
                try out.appendSlice(a, inner);
                try out.appendSlice(a, "**");
            }
        } else if (std.mem.eql(u8, nd.tag, "em") or std.mem.eql(u8, nd.tag, "i")) {
            const inner = trimJs(try renderInline(a, nd.children.items));
            if (inner.len > 0) {
                try out.append(a, '*');
                try out.appendSlice(a, inner);
                try out.append(a, '*');
            }
        } else if (std.mem.eql(u8, nd.tag, "del") or std.mem.eql(u8, nd.tag, "s")) {
            const inner = trimJs(try renderInline(a, nd.children.items));
            if (inner.len > 0) {
                try out.appendSlice(a, "~~");
                try out.appendSlice(a, inner);
                try out.appendSlice(a, "~~");
            }
        } else if (std.mem.eql(u8, nd.tag, "code")) {
            const inner = trimJs(try renderInline(a, nd.children.items));
            if (inner.len > 0) {
                try out.append(a, '`');
                try out.appendSlice(a, inner);
                try out.append(a, '`');
            }
        } else if (std.mem.eql(u8, nd.tag, "a")) {
            const href = try decodeEntities(a, attrOf(nd, "href"));
            const title = attrOf(nd, "title"); // stays verbatim
            const label = trimJs(try renderInline(a, nd.children.items));
            try out.append(a, '[');
            try out.appendSlice(a, if (label.len > 0) label else href);
            try out.appendSlice(a, "](");
            try out.appendSlice(a, href);
            if (title.len > 0) {
                try out.appendSlice(a, " \"");
                try out.appendSlice(a, title);
                try out.append(a, '"');
            }
            try out.append(a, ')');
        } else if (std.mem.eql(u8, nd.tag, "img")) {
            const alt = trimJs(try escapeMarkdown(a, try decodeEntities(a, attrOf(nd, "alt"))));
            try out.appendSlice(a, "![");
            try out.appendSlice(a, alt);
            try out.appendSlice(a, "](");
            try out.appendSlice(a, try decodeEntities(a, attrOf(nd, "src")));
            try out.append(a, ')');
        } else {
            // span and unknown tags are transparent
            try out.appendSlice(a, try renderInline(a, nd.children.items));
        }
    }
    return out.toOwnedSlice(a);
}

/// Concatenate the entity-decoded text under nodes (pre content only).
fn textOf(a: std.mem.Allocator, nodes: []const *Node) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    for (nodes) |nd| {
        if (nd.is_elem) {
            try out.appendSlice(a, try textOf(a, nd.children.items));
        } else {
            try out.appendSlice(a, try decodeEntities(a, nd.text));
        }
    }
    return out.toOwnedSlice(a);
}

/// Render a sequence of nodes as Markdown blocks.
fn renderBlocks(a: std.mem.Allocator, nodes: []const *Node) !std.ArrayList([]const u8) {
    var out: std.ArrayList([]const u8) = .empty;
    var para: std.ArrayList(*Node) = .empty;
    for (nodes) |nd| {
        if (!isBlock(nd)) {
            try para.append(a, nd);
            continue;
        }
        // flush
        if (para.items.len > 0) {
            const text = trimJs(try renderInline(a, para.items));
            if (text.len > 0) try out.append(a, text);
            para.clearRetainingCapacity();
        }
        if (std.mem.eql(u8, nd.tag, "hr")) {
            try out.append(a, "---");
        } else if (std.mem.eql(u8, nd.tag, "p")) {
            const text = trimJs(try renderInline(a, nd.children.items));
            if (text.len > 0) try out.append(a, text);
        } else if (std.mem.eql(u8, nd.tag, "div")) {
            const inner = try renderBlocks(a, nd.children.items);
            try out.appendSlice(a, inner.items);
        } else if (std.mem.eql(u8, nd.tag, "blockquote")) {
            const inner = try std.mem.join(a, "\n\n", (try renderBlocks(a, nd.children.items)).items);
            var quoted: std.ArrayList(u8) = .empty;
            var it = std.mem.splitScalar(u8, inner, '\n');
            var first = true;
            while (it.next()) |line| {
                if (!first) try quoted.append(a, '\n');
                first = false;
                if (line.len == 0) {
                    try quoted.append(a, '>');
                } else {
                    try quoted.appendSlice(a, "> ");
                    try quoted.appendSlice(a, line);
                }
            }
            try out.append(a, try quoted.toOwnedSlice(a));
        } else if (std.mem.eql(u8, nd.tag, "pre")) {
            var code_elem: ?*Node = null;
            for (nd.children.items) |c| {
                if (c.is_elem and std.mem.eql(u8, c.tag, "code")) {
                    code_elem = c;
                    break;
                }
            }
            var lang: []const u8 = "";
            if (code_elem) |ce| lang = langFromClass(attrOf(ce, "class"));
            const src = code_elem orelse nd;
            var body = try textOf(a, src.children.items);
            while (body.len > 0 and body[body.len - 1] == '\n') body = body[0 .. body.len - 1];
            var piece: std.ArrayList(u8) = .empty;
            try piece.appendSlice(a, "```");
            try piece.appendSlice(a, lang);
            try piece.append(a, '\n');
            try piece.appendSlice(a, body);
            try piece.append(a, '\n');
            try piece.appendSlice(a, "```");
            try out.append(a, try piece.toOwnedSlice(a));
        } else if (std.mem.eql(u8, nd.tag, "ul") or std.mem.eql(u8, nd.tag, "ol")) {
            try out.append(a, try renderList(a, nd, 0));
        } else { // h1-h6
            const level: usize = if (nd.tag.len >= 2 and isAsciiDigit(nd.tag[1])) nd.tag[1] - '0' else 0;
            var piece: std.ArrayList(u8) = .empty;
            try piece.appendNTimes(a, '#', level);
            try piece.append(a, ' ');
            try piece.appendSlice(a, trimJs(try renderInline(a, nd.children.items)));
            try out.append(a, try piece.toOwnedSlice(a));
        }
    }
    if (para.items.len > 0) {
        const text = trimJs(try renderInline(a, para.items));
        if (text.len > 0) try out.append(a, text);
    }
    return out;
}

/// ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
/// numbering restarted per list.
fn renderList(a: std.mem.Allocator, list: *Node, depth: usize) ![]u8 {
    var items: std.ArrayList(*Node) = .empty;
    for (list.children.items) |c| {
        if (c.is_elem and std.mem.eql(u8, c.tag, "li")) try items.append(a, c);
    }
    const ordered = std.mem.eql(u8, list.tag, "ol");
    var lines: std.ArrayList(u8) = .empty;
    var first = true;
    for (items.items, 0..) |li, idx| {
        const indent: usize = if (depth == 0) 0 else if (ordered) 4 else 2;
        // Split li children into inline content + nested lists.
        var inline_nodes: std.ArrayList(*Node) = .empty;
        var nested: std.ArrayList([]const u8) = .empty;
        for (li.children.items) |c| {
            if (c.is_elem and (std.mem.eql(u8, c.tag, "ul") or std.mem.eql(u8, c.tag, "ol"))) {
                try nested.append(a, try renderList(a, c, depth + 1));
            } else {
                try inline_nodes.append(a, c);
            }
        }
        const text = trimJs(try renderInline(a, inline_nodes.items));
        if (!first) try lines.append(a, '\n');
        first = false;
        try lines.appendNTimes(a, ' ', indent);
        if (ordered) {
            const marker = try std.fmt.allocPrint(a, "{d}.", .{idx + 1});
            try lines.appendSlice(a, marker);
        } else {
            try lines.append(a, '-');
        }
        if (text.len > 0) {
            try lines.append(a, ' ');
            try lines.appendSlice(a, text);
        }
        for (nested.items) |nc| {
            try lines.append(a, '\n');
            try lines.appendSlice(a, nc);
        }
    }
    return lines.toOwnedSlice(a);
}

/// Convert the supported HTML subset to Markdown. Only the allocator can
/// fail — the result carries output/error, mirroring HtmlToMarkdownResult.
pub fn htmlToMarkdown(a: std.mem.Allocator, raw: []const u8) std.mem.Allocator.Error!Result {
    if (trimJs(raw).len == 0) return .{ .output = "", .err = null }; // NOT an error
    const parsed = try parseHtml(a, raw);
    if (parsed.err) |e| return .{ .output = "", .err = e };
    const blocks = try renderBlocks(a, parsed.root.children.items);
    return .{ .output = try std.mem.join(a, "\n\n", blocks.items), .err = null };
}

test "html_to_markdown headings, marks, entities" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    try std.testing.expectEqualStrings("# Title\n\na & **b**", (try htmlToMarkdown(a, "<h1>Title</h1><p>a &amp; <b>b</b></p>")).output);
    try std.testing.expectEqualStrings("###### Deep\n\n*it* ~~no~~ `c`", (try htmlToMarkdown(a, "<h6>Deep</h6><p><i>it</i> <del>no</del> <code>c</code></p>")).output);
    try std.testing.expectEqualStrings("a \\* b \\[c\\]", (try htmlToMarkdown(a, "<p>a * b [c]</p>")).output);
    try std.testing.expectEqualStrings("just plain text", (try htmlToMarkdown(a, "just <span>plain</span> text")).output);
    // single pass, no double-decode: "x &amp;lt; y" stays "x &lt; y"
    try std.testing.expectEqualStrings("x &lt; y", (try htmlToMarkdown(a, "<p>x &amp;lt; y</p>")).output);
    // numeric refs, incl. hex; lone surrogates pass through
    try std.testing.expectEqualStrings("\u{39}", (try htmlToMarkdown(a, "&#x39;")).output);
    try std.testing.expectEqualStrings("&#xD800;", (try htmlToMarkdown(a, "&#xD800;")).output);
}

test "html_to_markdown blocks: pre, quotes, lists, links" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    try std.testing.expectEqualStrings(
        "```js\nconst x = 1;\n```",
        (try htmlToMarkdown(a, "<pre><code class=\"language-js\">const x = 1;\n</code></pre>")).output,
    );
    try std.testing.expectEqualStrings(
        "> quote\n>\n> more",
        (try htmlToMarkdown(a, "<blockquote>quote<p>more</p></blockquote>")).output,
    );
    try std.testing.expectEqualStrings(
        "- one\n- two\n  - nested\n\n1. first\n2. second",
        (try htmlToMarkdown(a, "<ul><li>one</li><li>two<ul><li>nested</li></ul></li></ul><ol><li>first</li><li>second</li></ol>")).output,
    );
    try std.testing.expectEqualStrings(
        "[docs](https://x.dev \"T\")![logo](i.png)",
        (try htmlToMarkdown(a, "<a href=\"https://x.dev\" title=\"T\">docs</a><img src=\"i.png\" alt=\"logo\">")).output,
    );
    // trailing-only inline content ("  \n" from <br>) trims away — hr survives
    try std.testing.expectEqualStrings("---", (try htmlToMarkdown(a, "<hr><br>")).output);
}

test "html_to_markdown error and empty input" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();

    // a '<' with no closing '>' is the one error
    const bad = try htmlToMarkdown(a, "<p x=\"");
    try std.testing.expectEqualStrings("", bad.output);
    try std.testing.expectEqualStrings("Unclosed tag", bad.err.?);
    // empty or whitespace-only input is NOT an error — the tool shows nothing
    const empty = try htmlToMarkdown(a, "  \n \u{00a0} ");
    try std.testing.expectEqualStrings("", empty.output);
    try std.testing.expect(empty.err == null);
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →