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. C++ port
// (canonical TS: src/lib/html-to-markdown.ts; Go twin:
// cli/html-to-markdown/html-to-markdown.go).
//
// Language: C++17, standard library only (std::regex is loosely specified
// and slow, so every TS regex became a byte scanner over std::string).
// 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.
//
// Entity decode: the standard library 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"; the Go twin uses the full stdlib
// html.UnescapeString table). Text is UTF-8; code points above U+007F (NBSP,
// etc.) are matched by their byte sequences in the trim/whitespace-collapse
// passes, mirroring the TS twin's \s (JS \s matches U+00A0, U+2028, ...).
//
// display source — part of CosmoDev's polyglot tool pages.
#include <optional>
#include <string>
#include <vector>
namespace {
struct HtmlToMarkdownResult {
std::string output;
std::optional<std::string> error; // set iff a '<' found no closing '>'
};
struct Node {
bool is_elem = false;
std::string tag;
std::string text;
std::vector<std::pair<std::string, std::string>> attrs;
std::vector<size_t> children; // arena indices (stable across growth)
};
using Arena = std::vector<Node>;
const char *const kUnclosedTag = "Unclosed tag";
// VOID in the TS lib — tags that never open a scope.
const char *const kVoidTags[7] = {"br", "hr", "img", "meta", "link", "input", "source"};
// BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks.
const char *const kBlockTags[13] = {"p", "div", "blockquote", "pre", "ul", "ol", "hr",
"h1", "h2", "h3", "h4", "h5", "h6"};
// The six named entities; the TS lib uses the full WHATWG shared table.
const char *const kNamedEnt[6][2] = {
{"amp", "&"}, {"lt", "<"}, {"gt", ">"},
{"quot", "\""}, {"apos", "'"}, {"nbsp", "\xc2\xa0"},
};
bool in_table(const char *const *tab, int n, const std::string &s) {
for (int k = 0; k < n; k++) {
if (s == tab[k]) return true;
}
return false;
}
bool is_ascii_letter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
bool is_ascii_digit(char c) { return c >= '0' && c <= '9'; }
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).
size_t js_space_at(const std::string &s, 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 < s.size() && (unsigned char)s[i + 1] == 0xA0) return 2; // U+00A0
if (i + 3 > s.size()) 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.
size_t js_space_end(const std::string &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.
std::string trim_js(const std::string &s) {
size_t b = 0, e = s.size();
while (b < e) {
size_t l = js_space_at(s, b);
if (!l) break;
b += l;
}
while (e > b) {
size_t l = js_space_end(s, e);
if (!l) break;
e -= l;
}
return s.substr(b, e - b);
}
void append_utf8(std::string &out, unsigned long cp) {
if (cp < 0x80) {
out += (char)cp;
} else if (cp < 0x800) {
out += (char)(0xC0 | (cp >> 6));
out += (char)(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += (char)(0xE0 | (cp >> 12));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
} else {
out += (char)(0xF0 | (cp >> 18));
out += (char)(0x80 | ((cp >> 12) & 0x3F));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
}
}
// Decode every recognized reference in s. Unknown refs and stray '&' pass
// through untouched; "x &lt; y" stays "x < y".
std::string decode_entities(const std::string &s) {
std::string out;
size_t i = 0, len = s.size();
while (i < len) {
if (s[i] != '&') {
out += s[i];
i++;
continue;
}
size_t p = i + 1;
bool matched = false;
if (p < len && s[p] == '#') { // &#NN; / &#xHH;
bool 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 ? is_ascii_digit(s[d]) || (s[d] >= 'a' && s[d] <= 'f') ||
(s[d] >= 'A' && s[d] <= 'F')
: 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)) {
append_utf8(out, cp);
i = d + 1;
matched = true;
}
}
} 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 = std::char_traits<char>::length(kNamedEnt[k][0]);
if (d - p == nl && s.compare(p, nl, kNamedEnt[k][0]) == 0) {
out += kNamedEnt[k][1];
i = d + 1;
matched = true;
break;
}
}
}
}
if (!matched) {
out += '&';
i++;
}
}
return out;
}
// Backslash-escape the Markdown-significant \ ` * _ [ ].
std::string escape_markdown(const std::string &s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
if (c == '\\' || c == '`' || c == '*' || c == '_' || c == '[' || c == ']') out += '\\';
out += c;
}
return out;
}
// Collapse any run of JS whitespace to a single space — /\s+/g, ' '.
std::string collapse_whitespace(const std::string &s) {
std::string out;
out.reserve(s.size());
size_t i = 0, len = s.size();
while (i < len) {
size_t l = js_space_at(s, i);
if (l) {
out += ' ';
i += l;
while ((l = js_space_at(s, i))) i += l;
} else {
out += s[i];
i++;
}
}
return out;
}
// `language-([\w-]+)` — the first occurrence whose capture is non-empty.
std::string lang_from_class(const std::string &cls) {
size_t from = 0;
while (true) {
size_t off = cls.find("language-", from);
if (off == std::string::npos) return "";
size_t start = off + 9, e = start;
while (e < cls.size() &&
(is_ascii_letter(cls[e]) || is_ascii_digit(cls[e]) || cls[e] == '_' || cls[e] == '-')) {
e++;
}
if (e > start) return cls.substr(start, e - start);
from = start;
}
}
// 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).
void scan_attrs(Node &elem, const std::string &body, size_t from) {
size_t p = from;
while (p < body.size()) {
if (is_ascii_letter(body[p]) || body[p] == '-') {
size_t q = p + 1;
while (q < body.size() && (is_ascii_letter(body[q]) || body[q] == '-')) q++;
size_t r = q;
while (r < body.size() && js_space_at(body, r)) r++;
size_t vend = q;
std::string value;
bool have_value = false;
if (r < body.size() && body[r] == '=') {
size_t r2 = r + 1;
while (r2 < body.size() && js_space_at(body, r2)) r2++;
if (r2 < body.size()) {
char vc = body[r2];
if (vc == '"' || vc == '\'') {
size_t e = r2 + 1;
while (e < body.size() && body[e] != vc) e++;
if (e < body.size()) { // closing quote — value includes quotes
value = body.substr(r2, e + 1 - r2);
vend = e + 1;
have_value = true;
}
}
if (!have_value) { // bare [^\s>]+ — '>' already consumed
size_t e = r2;
while (e < body.size() && !js_space_at(body, e) && body[e] != '>') e++;
if (e > r2) {
value = body.substr(r2, e - r2);
vend = e;
have_value = true;
} else {
vend = q; // no value — the group backtracks off
}
}
} else {
vend = q;
}
}
std::string name = body.substr(p, q - p);
for (char &ch : name) {
if (ch >= 'A' && ch <= 'Z') ch += 32;
}
std::string stripped = have_value && value.size() >= 2 ? value.substr(1, value.size() - 2) : std::string();
elem.attrs.emplace_back(std::move(name), std::move(stripped));
p = vend;
} else {
p++;
}
}
}
size_t attach(Arena &arena, size_t parent, Node nd) {
size_t ix = arena.size();
arena.push_back(std::move(nd));
arena[parent].children.push_back(ix);
return ix;
}
// Parse into a node forest. arena[0] is a synthetic root holding the
// top-level nodes. Attribute values may be double-quoted, single-quoted or
// bare; a quoted value may contain '>'. Returns false on the one error
// (a '<' with no closing '>').
bool parse_html(const std::string &raw, Arena &arena) {
Node root;
root.is_elem = true;
arena.push_back(std::move(root)); // arena[0] = synthetic root
std::vector<size_t> stack(1, 0);
size_t i = 0, len = raw.size();
while (i < len) {
size_t lt = raw.find('<', i);
if (lt == std::string::npos) {
Node t;
t.text = raw.substr(i);
attach(arena, stack.back(), std::move(t));
break;
}
if (lt > i) {
Node t;
t.text = raw.substr(i, lt - i);
attach(arena, stack.back(), std::move(t));
}
// 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 false; // Unclosed tag
std::string inner = trim_js(raw.substr(lt + 1, j - lt - 1));
i = j + 1;
if (inner.size() >= 3 && inner.compare(0, 3, "!--") == 0) continue; // comment
if (!inner.empty() && inner[0] == '!') continue; // doctype
bool closing = !inner.empty() && inner[0] == '/';
std::string body = closing ? inner.substr(1) : inner;
if (!closing && !body.empty() && body.back() == '/') body.pop_back(); // one trailing slash
// ^[a-zA-Z][a-zA-Z0-9-]* — else drop (browsers would show it as text)
if (body.empty() || !is_ascii_letter(body[0])) continue;
size_t name_end = 1;
while (name_end < body.size() &&
(is_ascii_letter(body[name_end]) || is_ascii_digit(body[name_end]) || body[name_end] == '-')) {
name_end++;
}
std::string tag = body.substr(0, name_end);
for (char &ch : tag) {
if (ch >= 'A' && ch <= 'Z') ch += 32;
}
if (closing) {
for (size_t k = stack.size(); k-- > 1;) {
if (arena[stack[k]].tag == tag) {
stack.resize(k);
break;
}
}
continue;
}
Node elem;
elem.is_elem = true;
elem.tag = tag;
scan_attrs(elem, body, name_end);
size_t ix = attach(arena, stack.back(), std::move(elem));
if (!in_table(kVoidTags, 7, arena[ix].tag) && (body.empty() || body.back() != '/')) {
stack.push_back(ix);
}
}
return true;
}
const std::string &attr_get(const Node &nd, const std::string &name) {
static const std::string kEmpty;
for (const auto &kv : nd.attrs) {
if (kv.first == name) return kv.second;
}
return kEmpty;
}
bool is_block(const Node &n) { return n.is_elem && in_table(kBlockTags, 13, n.tag); }
std::string join(const std::vector<std::string> &parts, const std::string &sep) {
std::string out;
for (size_t i = 0; i < parts.size(); i++) {
if (i) out += sep;
out += parts[i];
}
return out;
}
// Inline content of one block: marks, links, images, escaped text.
std::string render_inline(const Arena &arena, const std::vector<size_t> &nodes) {
std::string out;
for (size_t ix : nodes) {
const Node &n = arena[ix];
if (!n.is_elem) {
// TS order: escape(decode(v)) then the \s+ collapse.
out += collapse_whitespace(escape_markdown(decode_entities(n.text)));
} else if (n.tag == "br") {
out += " \n";
} else if (n.tag == "strong" || n.tag == "b") {
std::string inner = trim_js(render_inline(arena, n.children));
if (!inner.empty()) out += "**" + inner + "**"; // empty emphasis renders as nothing
} else if (n.tag == "em" || n.tag == "i") {
std::string inner = trim_js(render_inline(arena, n.children));
if (!inner.empty()) out += "*" + inner + "*";
} else if (n.tag == "del" || n.tag == "s") {
std::string inner = trim_js(render_inline(arena, n.children));
if (!inner.empty()) out += "~~" + inner + "~~";
} else if (n.tag == "code") {
std::string inner = trim_js(render_inline(arena, n.children));
if (!inner.empty()) out += "`" + inner + "`";
} else if (n.tag == "a") {
std::string href = decode_entities(attr_get(n, "href"));
const std::string &title = attr_get(n, "title"); // stays verbatim
std::string label = trim_js(render_inline(arena, n.children));
if (label.empty()) label = href;
out += "[" + label + "](" + href;
if (!title.empty()) out += " \"" + title + "\"";
out += ")";
} else if (n.tag == "img") {
std::string alt = trim_js(escape_markdown(decode_entities(attr_get(n, "alt"))));
out += ") + ")";
} else {
out += render_inline(arena, n.children); // span and unknown tags are transparent
}
}
return out;
}
// Concatenate the entity-decoded text under nodes (pre content only).
std::string text_of(const Arena &arena, const std::vector<size_t> &nodes) {
std::string out;
for (size_t ix : nodes) {
const Node &n = arena[ix];
if (n.is_elem) out += text_of(arena, n.children);
else out += decode_entities(n.text);
}
return out;
}
// ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
// numbering restarted per list. (Defined below; render_blocks recurses.)
std::string render_list(const Arena &arena, size_t list_ix, size_t depth);
// Render a sequence of nodes as Markdown blocks.
std::vector<std::string> render_blocks(const Arena &arena, const std::vector<size_t> &nodes) {
std::vector<std::string> out;
std::vector<size_t> para;
auto flush = [&]() {
if (!para.empty()) {
std::string text = trim_js(render_inline(arena, para));
if (!text.empty()) out.push_back(std::move(text));
para.clear();
}
};
for (size_t ix : nodes) {
const Node &n = arena[ix];
if (!is_block(n)) {
para.push_back(ix);
continue;
}
flush();
if (n.tag == "hr") {
out.push_back("---");
} else if (n.tag == "p") {
std::string text = trim_js(render_inline(arena, n.children));
if (!text.empty()) out.push_back(std::move(text));
} else if (n.tag == "div") {
std::vector<std::string> inner = render_blocks(arena, n.children);
out.insert(out.end(), inner.begin(), inner.end());
} else if (n.tag == "blockquote") {
std::string inner = join(render_blocks(arena, n.children), "\n\n");
std::string quoted;
size_t ls = 0;
while (ls <= inner.size()) {
size_t le = inner.find('\n', ls);
std::string line = inner.substr(ls, le == std::string::npos ? std::string::npos : le - ls);
quoted += line.empty() ? ">" : "> " + line;
if (le == std::string::npos) break;
quoted += "\n";
ls = le + 1;
}
out.push_back(std::move(quoted));
} else if (n.tag == "pre") {
size_t code_ix = static_cast<size_t>(-1);
for (size_t c : n.children) {
if (arena[c].is_elem && arena[c].tag == "code") {
code_ix = c;
break;
}
}
std::string lang = code_ix != static_cast<size_t>(-1)
? lang_from_class(attr_get(arena[code_ix], "class"))
: std::string();
size_t src = code_ix != static_cast<size_t>(-1) ? code_ix : ix;
std::string body = text_of(arena, arena[src].children);
while (!body.empty() && body.back() == '\n') body.pop_back(); // TS replace(/\n+$/, '')
out.push_back("```" + lang + "\n" + body + "\n```");
} else if (n.tag == "ul" || n.tag == "ol") {
out.push_back(render_list(arena, ix, 0));
} else { // h1-h6
int level = 0;
if (n.tag.size() >= 2 && is_ascii_digit(n.tag[1])) level = n.tag[1] - '0';
out.push_back(std::string(level, '#') + " " + trim_js(render_inline(arena, n.children)));
}
}
flush();
return out;
}
// ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
// numbering restarted per list.
std::string render_list(const Arena &arena, size_t list_ix, size_t depth) {
const Node &list = arena[list_ix];
bool ordered = list.tag == "ol";
std::vector<size_t> items;
for (size_t c : list.children) {
if (arena[c].is_elem && arena[c].tag == "li") items.push_back(c);
}
std::vector<std::string> lines;
for (size_t idx = 0; idx < items.size(); idx++) {
const Node &li = arena[items[idx]];
std::string marker = ordered ? std::to_string(idx + 1) + "." : "-";
std::string indent(depth == 0 ? 0 : (ordered ? 4 : 2), ' ');
// Split li children into inline content + nested lists.
std::vector<size_t> inline_nodes;
std::vector<std::string> nested;
for (size_t c : li.children) {
if (arena[c].is_elem && (arena[c].tag == "ul" || arena[c].tag == "ol")) {
nested.push_back(render_list(arena, c, depth + 1));
} else {
inline_nodes.push_back(c);
}
}
std::string text = trim_js(render_inline(arena, inline_nodes));
lines.push_back(text.empty() ? indent + marker : indent + marker + " " + text);
lines.insert(lines.end(), nested.begin(), nested.end());
}
return join(lines, "\n");
}
} // namespace
// Convert the supported HTML subset to Markdown. The result carries
// output/error, mirroring HtmlToMarkdownResult; empty or whitespace-only
// input is NOT an error — the tool shows nothing.
HtmlToMarkdownResult html_to_markdown(const std::string &raw) {
if (trim_js(raw).empty()) {
return {}; // empty input is NOT an error — the tool shows nothing
}
Arena arena;
if (!parse_html(raw, arena)) {
return {std::string(), std::string(kUnclosedTag)};
}
return {join(render_blocks(arena, arena[0].children), "\n\n"), std::nullopt};
}
// Example:
// HtmlToMarkdownResult r = html_to_markdown("<h1>Title</h1><p>a & <b>b</b></p>");
// r.output → "# Title\n\na & **b**"
// html_to_markdown("<p x=\"").error → "Unclosed tag"
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 →