HTML to Markdown Converter — C 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 C implementation — the same logic the interactive tool runs, in a shareable, citable form.
/*
* html-to-markdown — supported HTML subset → Markdown converter.
*
* Language: C (C11, standard library only).
* CosmoDev polyglot showcase port of the `html-to-markdown` tool.
* Ported from src/lib/html-to-markdown.ts (the canonical TypeScript lib);
* the Go CLI twin lives at cli/html-to-markdown/html-to-markdown.go.
*
* 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.
*
* Entity decode: C has no WHATWG table, so this port hand-rolls the
* fallback — numeric (&#NN; / &#xHH;) plus the six named entities (amp lt gt
* quot apos nbsp), single pass, no double-decode ("x &lt; y" stays
* "x < y"). Text is UTF-8; code points above U+007F (NBSP, etc.) are
* matched by their byte sequences in the whitespace-collapse pass, mirroring
* the TS twin's /\s+/g (JS \s matches U+00A0, U+2028, ...).
*
* Never fails loudly: html_to_markdown returns the output or NULL with a
* malloc'd error string ("Unclosed tag").
*
* display source — part of CosmoDev's polyglot tool pages.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ---------- growable string buffer ---------- */
typedef struct {
char *data;
size_t len, cap;
} Buf;
static void buf_init(Buf *b) {
b->cap = 64;
b->len = 0;
b->data = malloc(b->cap);
b->data[0] = 0;
}
static void buf_reserve(Buf *b, size_t extra) {
if (b->len + extra + 1 > b->cap) {
size_t ncap = b->cap;
while (b->len + extra + 1 > ncap) ncap *= 2;
char *nd = realloc(b->data, ncap);
if (!nd) exit(1);
b->data = nd;
b->cap = ncap;
}
}
static void buf_push(Buf *b, char c) {
buf_reserve(b, 1);
b->data[b->len++] = c;
b->data[b->len] = 0;
}
static void buf_str_n(Buf *b, const char *s, size_t n) {
buf_reserve(b, n);
memcpy(b->data + b->len, s, n);
b->len += n;
b->data[b->len] = 0;
}
static void buf_str(Buf *b, const char *s) { buf_str_n(b, s, strlen(s)); }
static char *dup_range(const char *s, size_t from, size_t to) {
char *out = malloc(to - from + 1);
memcpy(out, s + from, to - from);
out[to - from] = 0;
return out;
}
/* ---------- forest node ---------- */
typedef struct Node Node;
typedef struct {
char *name, *value; /* value stays RAW; decoded at use */
} Attr;
typedef struct {
Node **items;
size_t len, cap;
} NodeList;
struct Node {
int is_elem;
char *text; /* text nodes */
char *tag; /* element tag, lowercase */
Attr *attrs;
size_t nattrs;
NodeList children;
};
static Node *node_text(const char *s, size_t n) {
Node *nd = calloc(1, sizeof(Node));
nd->is_elem = 0;
nd->text = dup_range(s, 0, n);
return nd;
}
static Node *node_elem(const char *tag) {
Node *nd = calloc(1, sizeof(Node));
nd->is_elem = 1;
nd->tag = strdup(tag);
return nd;
}
static void list_push(NodeList *l, Node *n) {
if (l->len == l->cap) {
l->cap = l->cap ? l->cap * 2 : 8;
l->items = realloc(l->items, l->cap * sizeof(Node *));
}
l->items[l->len++] = n;
}
static const char *attr_get(const Node *nd, const char *name) {
for (size_t k = 0; k < nd->nattrs; k++) {
if (strcmp(nd->attrs[k].name, name) == 0) return nd->attrs[k].value;
}
return "";
}
/* ---------- character helpers ---------- */
static int is_ascii_letter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
static int is_ascii_digit(char c) { return c >= '0' && c <= '9'; }
static int hex_val(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return c - 'A' + 10;
}
/* 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). */
static int js_space_at(const char *s, size_t len, size_t i) {
unsigned char c = (unsigned char)s[i];
if (c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r') return 1;
if (c == 0xC2 && i + 1 < len && (unsigned char)s[i + 1] == 0xA0) return 2; /* U+00A0 */
if (i + 3 > len) return 0;
unsigned char m = (unsigned char)s[i + 1], z = (unsigned char)s[i + 2];
if (c == 0xE1 && m == 0x9A && z == 0x80) return 3; /* U+1680 */
if (c == 0xE2 && m == 0x80 && z >= 0x80 && z <= 0x8A) return 3; /* U+2000-200A */
if (c == 0xE2 && m == 0x80 && (z == 0xA8 || z == 0xA9 || z == 0xAF)) return 3;
if (c == 0xE2 && m == 0x81 && z == 0x9F) return 3; /* U+205F */
if (c == 0xE3 && m == 0x80 && z == 0x80) return 3; /* U+3000 */
if (c == 0xEF && m == 0xBB && z == 0xBF) return 3; /* U+FEFF */
return 0;
}
/* Byte length of the JS-\s code point ending at s[e], or 0. */
static int js_space_end(const char *s, size_t e) {
unsigned char c = (unsigned char)s[e - 1];
if (c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r') return 1;
if (e >= 2 && (unsigned char)s[e - 2] == 0xC2 && c == 0xA0) return 2;
if (e < 3) return 0;
unsigned char a = (unsigned char)s[e - 3], m = (unsigned char)s[e - 2];
if (a == 0xE1 && m == 0x9A && c == 0x80) return 3;
if (a == 0xE2 && m == 0x80 && c >= 0x80 && c <= 0x8A) return 3;
if (a == 0xE2 && m == 0x80 && (c == 0xA8 || c == 0xA9 || c == 0xAF)) return 3;
if (a == 0xE2 && m == 0x81 && c == 0x9F) return 3;
if (a == 0xE3 && m == 0x80 && c == 0x80) return 3;
if (a == 0xEF && m == 0xBB && c == 0xBF) return 3;
return 0;
}
/* JS String.prototype.trim over the JS-\s class; malloc'd copy. */
static char *trim_js(const char *s) {
size_t len = strlen(s), b = 0, e = len;
while (b < len) {
int l = js_space_at(s, len, b);
if (!l) break;
b += (size_t)l;
}
while (e > b) {
int l = js_space_end(s, e);
if (!l) break;
e -= (size_t)l;
}
return dup_range(s, b, e);
}
/* ---------- entity decode (single pass, never fails) ---------- */
/* The six named entities; the TS lib uses the full WHATWG shared table. */
static const char *NAMED_ENT[6][2] = {
{"amp", "&"}, {"lt", "<"}, {"gt", ">"},
{"quot", "\""}, {"apos", "'"}, {"nbsp", "\xc2\xa0"},
};
static void buf_utf8(Buf *b, unsigned long cp) {
if (cp < 0x80) {
buf_push(b, (char)cp);
} else if (cp < 0x800) {
buf_push(b, (char)(0xC0 | (cp >> 6)));
buf_push(b, (char)(0x80 | (cp & 0x3F)));
} else if (cp < 0x10000) {
buf_push(b, (char)(0xE0 | (cp >> 12)));
buf_push(b, (char)(0x80 | ((cp >> 6) & 0x3F)));
buf_push(b, (char)(0x80 | (cp & 0x3F)));
} else {
buf_push(b, (char)(0xF0 | (cp >> 18)));
buf_push(b, (char)(0x80 | ((cp >> 12) & 0x3F)));
buf_push(b, (char)(0x80 | ((cp >> 6) & 0x3F)));
buf_push(b, (char)(0x80 | (cp & 0x3F)));
}
}
/* Decode every recognized reference in s into out. Unknown refs and stray
* '&' pass through untouched; "x &lt; y" stays "x < y". */
static void decode_entities(const char *s, Buf *out) {
size_t i = 0, len = strlen(s);
while (i < len) {
char c = s[i];
if (c != '&') {
buf_push(out, c);
i++;
continue;
}
size_t p = i + 1;
int matched = 0;
if (p < len && s[p] == '#') { /* &#NN; / &#xHH; */
int hex = p + 1 < len && (s[p + 1] == 'x' || s[p + 1] == 'X');
size_t d = hex ? p + 2 : p + 1, start = d;
while (d < len && (hex ? isxdigit((unsigned char)s[d]) : is_ascii_digit(s[d]))) d++;
if (d > start && d < len && s[d] == ';' && d - start <= 7) {
unsigned long cp = 0;
for (size_t k = start; k < d; k++) cp = cp * (hex ? 16 : 10) + (unsigned long)hex_val(s[k]);
/* Lone surrogates are not valid standalone scalars. */
if (!((cp >= 0xD800 && cp <= 0xDFFF) || cp > 0x10FFFF)) {
buf_utf8(out, cp);
i = d + 1;
matched = 1;
}
}
} else if (p < len && is_ascii_letter(s[p])) { /* &name; */
size_t d = p + 1;
while (d < len && (is_ascii_letter(s[d]) || is_ascii_digit(s[d]))) d++;
if (d < len && s[d] == ';') {
for (int k = 0; k < 6; k++) {
size_t nl = strlen(NAMED_ENT[k][0]);
if (d - p == nl && strncmp(s + p, NAMED_ENT[k][0], nl) == 0) {
buf_str(out, NAMED_ENT[k][1]);
i = d + 1;
matched = 1;
break;
}
}
}
}
if (!matched) {
buf_push(out, '&');
i++;
}
}
}
/* malloc'd decode convenience. */
static char *decode_dup(const char *s) {
Buf b;
buf_init(&b);
decode_entities(s, &b);
return b.data;
}
/* ---------- markdown helpers ---------- */
static int is_md_escape(unsigned char c) {
return c == '\\' || c == '`' || c == '*' || c == '_' || c == '[' || c == ']';
}
/* Backslash-escape the Markdown-significant \ ` * _ [ ]. */
static void escape_markdown(const char *s, Buf *out) {
for (size_t i = 0; s[i]; i++) {
if (is_md_escape((unsigned char)s[i])) buf_push(out, '\\');
buf_push(out, s[i]);
}
}
/* Collapse any run of JS whitespace to a single space — /\s+/g, ' '. */
static void collapse_whitespace(const char *s, Buf *out) {
size_t i = 0, len = strlen(s);
while (i < len) {
int l = js_space_at(s, len, i);
if (l) {
buf_push(out, ' ');
i += (size_t)l;
while ((l = js_space_at(s, len, i))) i += (size_t)l;
} else {
buf_push(out, s[i]);
i++;
}
}
}
/* Text-node normalization, TS order: escape(decode(v)) then \s+ collapse. */
static void normalize_text(const char *s, Buf *out) {
Buf d, e;
buf_init(&d);
buf_init(&e);
decode_entities(s, &d);
escape_markdown(d.data, &e);
collapse_whitespace(e.data, out);
free(d.data);
free(e.data);
}
/* ---------- parser ---------- */
static const char *VOID_TAGS[7] = {"br", "hr", "img", "meta", "link", "input", "source"};
static const char *BLOCK_TAGS[13] = {"p", "div", "blockquote", "pre", "ul", "ol", "hr",
"h1", "h2", "h3", "h4", "h5", "h6"};
static int in_table(const char **tab, int n, const char *s) {
for (int k = 0; k < n; k++) {
if (strcmp(tab[k], s) == 0) return 1;
}
return 0;
}
/* Parse into a node forest. Attribute values may be double-quoted,
* single-quoted or bare; a quoted value may contain '>'. Returns 0 on the
* one error (a '<' with no closing '>'). */
static int parse_html(const char *raw, NodeList *roots) {
NodeList stack = {0};
size_t i = 0, len = strlen(raw);
while (i < len) {
const char *lt_p = strchr(raw + i, '<');
if (!lt_p) {
list_push(stack.len ? &stack.items[stack.len - 1]->children : roots,
node_text(raw + i, strlen(raw + i)));
break;
}
size_t lt = (size_t)(lt_p - raw);
if (lt > i) {
list_push(stack.len ? &stack.items[stack.len - 1]->children : roots,
node_text(raw + i, lt - i));
}
/* Find the tag's '>', skipping quoted attribute values. */
size_t j = lt + 1;
char quote = 0;
while (j < len && (raw[j] != '>' || quote != 0)) {
char c = raw[j];
if (!quote && (c == '"' || c == '\'')) quote = c;
else if (quote && c == quote) quote = 0;
j++;
}
if (j >= len) return 0; /* Unclosed tag */
char *inner = dup_range(raw, lt + 1, j);
{
char *t = trim_js(inner);
free(inner);
inner = t;
}
i = j + 1;
if (strncmp(inner, "!--", 3) == 0) { free(inner); continue; } /* comment */
if (inner[0] == '!') { free(inner); continue; } /* doctype */
int closing = inner[0] == '/';
const char *body_s = closing ? inner + 1 : inner;
size_t body_len = strlen(body_s);
if (!closing && body_len && body_s[body_len - 1] == '/') body_len--; /* one trailing slash */
/* Tag name: ^[a-zA-Z][a-zA-Z0-9-]* — else drop (browsers would show
* it as text; we drop it). */
if (!body_len || !is_ascii_letter(body_s[0])) { free(inner); continue; }
size_t name_end = 1;
while (name_end < body_len &&
(is_ascii_letter(body_s[name_end]) || is_ascii_digit(body_s[name_end]) ||
body_s[name_end] == '-')) {
name_end++;
}
char tag[64];
size_t tl = name_end < sizeof(tag) ? name_end : sizeof(tag) - 1;
for (size_t k = 0; k < tl; k++) tag[k] = (char)((body_s[k] >= 'A' && body_s[k] <= 'Z') ? body_s[k] + 32 : body_s[k]);
tag[tl] = 0;
if (closing) {
for (size_t k = stack.len; k-- > 0;) {
if (strcmp(stack.items[k]->tag, tag) == 0) {
stack.len = k;
break;
}
}
free(inner);
continue;
}
Node *elem = node_elem(tag);
/* Attributes: ([a-zA-Z-]+)( = (double | single | bare))? with the
* same left-to-right resumption as the TS /g regex: the scan
* continues after the VALUE when one matched, else after the name.
* Values stay RAW; href/src/alt are entity-decoded at use, titles
* stay verbatim. The strip mirrors TS am[2].slice(1, -1): quoted
* values lose their quotes, bare values lose their first and last
* characters (same quirk the Go twin keeps for lock-step). */
size_t p = name_end;
while (p < body_len) {
char c = body_s[p];
if (is_ascii_letter(c) || c == '-') {
size_t q = p + 1;
while (q < body_len && (is_ascii_letter(body_s[q]) || body_s[q] == '-')) q++;
size_t r = q;
while (r < body_len && js_space_at(body_s, body_len, r)) r++;
char *value = NULL;
size_t vend = q;
if (r < body_len && body_s[r] == '=') {
r++;
while (r < body_len && js_space_at(body_s, body_len, r)) r++;
if (r < body_len) {
char vc = body_s[r];
if (vc == '"' || vc == '\'') {
size_t e = r + 1;
while (e < body_len && body_s[e] != vc) e++;
if (e < body_len) { /* closing quote — value includes quotes */
vend = e + 1;
value = dup_range(body_s, r, vend);
}
}
if (!value) { /* bare [^\s>]+ — '>' already consumed */
size_t e = r;
while (e < body_len && !js_space_at(body_s, body_len, e)) e++;
vend = e;
value = dup_range(body_s, r, e);
}
}
}
char name[64];
size_t nl = q - p < sizeof(name) ? q - p : sizeof(name) - 1;
for (size_t k = 0; k < nl; k++) name[k] = (char)((body_s[p + k] >= 'A' && body_s[p + k] <= 'Z') ? body_s[p + k] + 32 : body_s[p + k]);
name[nl] = 0;
char *stripped = value
? (strlen(value) >= 2 ? dup_range(value, 1, strlen(value) - 1) : strdup(""))
: strdup("");
free(value);
elem->attrs = realloc(elem->attrs, (elem->nattrs + 1) * sizeof(Attr));
elem->attrs[elem->nattrs].name = strdup(name);
elem->attrs[elem->nattrs].value = stripped;
elem->nattrs++;
p = vend;
} else {
p++;
}
}
list_push(stack.len ? &stack.items[stack.len - 1]->children : roots, elem);
if (!in_table(VOID_TAGS, 7, tag) && !(body_len && body_s[body_len - 1] == '/')) {
list_push(&stack, elem);
}
free(inner);
}
free(stack.items);
return 1;
}
/* ---------- renderer ---------- */
static int is_block(const Node *n) {
return n->is_elem && in_table(BLOCK_TAGS, 13, n->tag);
}
/* Inline content of one block: marks, links, images, escaped text. */
static void render_inline(const NodeList *nodes, Buf *out) {
for (size_t k = 0; k < nodes->len; k++) {
const Node *n = nodes->items[k];
if (!n->is_elem) {
normalize_text(n->text, out);
} else if (strcmp(n->tag, "br") == 0) {
buf_str(out, " \n");
} else if (strcmp(n->tag, "strong") == 0 || strcmp(n->tag, "b") == 0 ||
strcmp(n->tag, "em") == 0 || strcmp(n->tag, "i") == 0 ||
strcmp(n->tag, "del") == 0 || strcmp(n->tag, "s") == 0 ||
strcmp(n->tag, "code") == 0) {
Buf b;
buf_init(&b);
render_inline(&n->children, &b);
char *t = trim_js(b.data);
free(b.data);
if (t[0]) { /* empty emphasis renders as nothing */
const char *a = "", *z = "";
if (strcmp(n->tag, "strong") == 0 || strcmp(n->tag, "b") == 0) { a = "**"; z = "**"; }
else if (strcmp(n->tag, "em") == 0 || strcmp(n->tag, "i") == 0) { a = "*"; z = "*"; }
else if (strcmp(n->tag, "del") == 0 || strcmp(n->tag, "s") == 0) { a = "~~"; z = "~~"; }
else { a = "`"; z = "`"; }
buf_str(out, a);
buf_str(out, t);
buf_str(out, z);
}
free(t);
} else if (strcmp(n->tag, "a") == 0) {
char *href = decode_dup(attr_get(n, "href"));
const char *title = attr_get(n, "title");
Buf b;
buf_init(&b);
render_inline(&n->children, &b);
char *label = trim_js(b.data);
free(b.data);
buf_push(out, '[');
buf_str(out, label[0] ? label : href);
buf_push(out, ']');
buf_push(out, '(');
buf_str(out, href);
if (title[0]) {
buf_str(out, " \"");
buf_str(out, title); /* verbatim — decode would let a '"' break the link */
buf_push(out, '"');
}
buf_push(out, ')');
free(href);
free(label);
} else if (strcmp(n->tag, "img") == 0) {
Buf d;
buf_init(&d);
decode_entities(attr_get(n, "alt"), &d);
escape_markdown(d.data, &d); /* safe: escaping never shrinks the buffer */
char *alt = trim_js(d.data);
free(d.data);
char *src = decode_dup(attr_get(n, "src"));
buf_str(out, ";
buf_str(out, src);
buf_push(out, ')');
free(alt);
free(src);
} else {
render_inline(&n->children, out); /* span and unknown tags are transparent */
}
}
}
/* Concatenate the entity-decoded text under nodes (pre content only). */
static void text_of(const NodeList *nodes, Buf *out) {
for (size_t k = 0; k < nodes->len; k++) {
const Node *c = nodes->items[k];
if (c->is_elem) text_of(&c->children, out);
else decode_entities(c->text, out);
}
}
/* The language token from a class="language-*" attribute ([\w-]+ run). */
static void lang_from_class(const Node *code, Buf *out) {
const char *cls = attr_get(code, "class");
const char *hit = strstr(cls, "language-");
if (!hit) return;
const char *p = hit + strlen("language-");
while (*p && (is_ascii_letter(*p) || is_ascii_digit(*p) || *p == '_' || *p == '-')) {
buf_push(out, *p);
p++;
}
}
/* Append a block with "\n\n" separators between blocks. */
static void push_block(Buf *out, int *first, const char *block) {
if (!*first) buf_str(out, "\n\n");
*first = 0;
buf_str(out, block);
}
/* Render a sequence of nodes as Markdown blocks joined with "\n\n". */
static void render_blocks(const NodeList *nodes, Buf *out, int *first) {
NodeList para = {0};
for (size_t k = 0; k < nodes->len; k++) {
const Node *n = nodes->items[k];
if (!is_block(n)) {
list_push(¶, (Node *)n);
continue;
}
if (para.len) { /* flush */
Buf b;
buf_init(&b);
render_inline(¶, &b);
char *t = trim_js(b.data);
free(b.data);
if (t[0]) push_block(out, first, t);
free(t);
para.len = 0;
}
if (strcmp(n->tag, "hr") == 0) {
push_block(out, first, "---");
} else if (strcmp(n->tag, "p") == 0) {
Buf b;
buf_init(&b);
render_inline(&n->children, &b);
char *t = trim_js(b.data);
free(b.data);
if (t[0]) push_block(out, first, t);
free(t);
} else if (strcmp(n->tag, "div") == 0) {
render_blocks(&n->children, out, first);
} else if (strcmp(n->tag, "blockquote") == 0) {
Buf ib;
buf_init(&ib);
int ifirst = 1;
render_blocks(&n->children, &ib, &ifirst);
Buf pb;
buf_init(&pb);
const char *s = ib.data;
while (1) {
const char *nl = strchr(s, '\n');
size_t ll = nl ? (size_t)(nl - s) : strlen(s);
if (ll) {
buf_str(&pb, "> ");
buf_str_n(&pb, s, ll);
} else {
buf_push(&pb, '>');
}
if (!nl) break;
buf_push(&pb, '\n');
s = nl + 1;
}
push_block(out, first, pb.data);
free(ib.data);
free(pb.data);
} else if (strcmp(n->tag, "pre") == 0) {
const Node *code = NULL;
for (size_t c = 0; c < n->children.len; c++) {
if (n->children.items[c]->is_elem && strcmp(n->children.items[c]->tag, "code") == 0) {
code = n->children.items[c];
break;
}
}
Buf lang;
buf_init(&lang);
if (code) lang_from_class(code, &lang);
Buf tb;
buf_init(&tb);
text_of(code ? &code->children : (NodeList *)&n->children, &tb);
while (tb.len && tb.data[tb.len - 1] == '\n') buf_reserve(&tb, 0), tb.len--, tb.data[tb.len] = 0;
Buf fence;
buf_init(&fence);
buf_str(&fence, "```");
buf_str(&fence, lang.data);
buf_push(&fence, '\n');
buf_str(&fence, tb.data);
buf_str(&fence, "\n```");
push_block(out, first, fence.data);
free(lang.data);
free(tb.data);
free(fence.data);
} else if (strcmp(n->tag, "ul") == 0 || strcmp(n->tag, "ol") == 0) {
Buf lb;
buf_init(&lb);
render_list(n, 0, &lb);
push_block(out, first, lb.data);
free(lb.data);
} else { /* h1-h6 */
int level = strlen(n->tag) >= 2 && n->tag[1] >= '1' && n->tag[1] <= '6' ? n->tag[1] - '0' : 0;
Buf b;
buf_init(&b);
render_inline(&n->children, &b);
char *t = trim_js(b.data);
free(b.data);
Buf hb;
buf_init(&hb);
for (int k = 0; k < level; k++) buf_push(&hb, '#');
buf_push(&hb, ' ');
buf_str(&hb, t);
push_block(out, first, hb.data);
free(t);
free(hb.data);
}
}
if (para.len) {
Buf b;
buf_init(&b);
render_inline(¶, &b);
char *t = trim_js(b.data);
free(b.data);
if (t[0]) push_block(out, first, t);
free(t);
}
free(para.items);
}
/* ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
* numbering restarted per list. */
static void render_list(const Node *list, int depth, Buf *out) {
int ordered = strcmp(list->tag, "ol") == 0;
int lfirst = 1;
int idx = 0;
for (size_t k = 0; k < list->children.len; k++) {
const Node *li = list->children.items[k];
if (!li->is_elem || strcmp(li->tag, "li") != 0) continue;
char marker[16];
if (ordered) snprintf(marker, sizeof(marker), "%d.", ++idx);
else strcpy(marker, "-");
int indent = depth == 0 ? 0 : ordered ? 4 : 2;
/* Split li children into inline content + nested lists. */
NodeList inline_nodes = {0};
Buf nested = {0};
buf_init(&nested);
int nfirst = 1;
for (size_t c = 0; c < li->children.len; c++) {
const Node *ch = li->children.items[c];
if (ch->is_elem && (strcmp(ch->tag, "ul") == 0 || strcmp(ch->tag, "ol") == 0)) {
render_list(ch, depth + 1, &nested); /* nested uses \n internally */
nfirst = 0;
} else {
list_push(&inline_nodes, (Node *)ch);
}
}
Buf b;
buf_init(&b);
render_inline(&inline_nodes, &b);
char *t = trim_js(b.data);
free(b.data);
if (!lfirst) buf_push(out, '\n');
lfirst = 0;
for (int sp = 0; sp < indent; sp++) buf_push(out, ' ');
buf_str(out, marker);
if (t[0]) {
buf_push(out, ' ');
buf_str(out, t);
}
if (nested.len) {
buf_push(out, '\n');
buf_str(out, nested.data);
}
free(t);
free(nested.data);
free(inline_nodes.items);
}
}
/* ---------- public API ---------- */
/* Convert the supported HTML subset to Markdown. Returns a malloc'd string;
* on the one error returns NULL and sets *error to a malloc'd message.
* Empty or whitespace-only input is NOT an error — the tool shows nothing. */
char *html_to_markdown(const char *raw, char **error) {
*error = NULL;
char *t = trim_js(raw);
int empty = t[0] == 0;
free(t);
if (empty) return strdup("");
NodeList roots = {0};
if (!parse_html(raw, &roots)) {
*error = strdup("Unclosed tag");
return strdup("");
}
Buf out;
buf_init(&out);
int first = 1;
render_blocks(&roots, &out, &first);
return out.data;
}
static void free_nodes(NodeList *l) {
for (size_t k = 0; k < l->len; k++) {
Node *n = l->items[k];
if (n->is_elem) {
for (size_t a = 0; a < n->nattrs; a++) {
free(n->attrs[a].name);
free(n->attrs[a].value);
}
free(n->attrs);
free_nodes(&n->children);
} else {
free(n->text);
}
free(n);
}
free(l->items);
l->items = NULL;
l->len = l->cap = 0;
}
/* Example:
* char *err = NULL;
* char *md = html_to_markdown("<h1>Title</h1><p>a & <b>b</b></p>", &err);
* puts(md); // "# Title\n\na & **b**"
*/
int main(int argc, char **argv) {
const char *sample = argc > 1 ? argv[1]
: "<h1>Title</h1><p>a & <b>b</b></p><ul><li>x<ul><li>y</li></ul></li></ul>";
char *err = NULL;
char *md = html_to_markdown(sample, &err);
if (err) {
printf("error: %s\n", err);
free(err);
} else {
printf("%s\n", md);
}
free(md);
return 0;
}
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 →