Skip to content

Markdown to HTML Converter — C++ source

Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.

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

// markdown-to-html — escape-first CommonMark subset → HTML renderer. C++ port
// (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
// Hand-rolled CommonMark SUBSET — everything is HTML-escaped before the inline
// rules run (raw HTML never passes through; security first), via the shared
// five-char escaper inlined here (`&` first so the entities we emit are never
// re-escaped). The stdlib has no regex worth trusting here, so every TS regex
// became a byte scanner over std::string: markers are ASCII and each slice
// boundary sits on an ASCII char, so multi-byte UTF-8 content passes through
// untouched and is never split. Supported blocks: #-headings (1-6), --- /***/
// ___ rules, ``` fenced code (markdown inert inside), > blockquotes
// (recursive), - * + unordered lists, N. ordered lists (source numbers
// stripped), paragraphs (soft line breaks joined with \n). Inline precedence:
// code spans first (placeholder-protected), then images, links, bold, italic,
// strikethrough — non-greedy pairs, in TS precedence order; on a failed
// attempt the engine advances one char (the scanners emit that char and retry
// — same outcomes). Not supported (by design, documented): raw HTML, tables,
// setext headings, nested lists, footnotes, autolinks. Empty or
// whitespace-only input is NOT an error — the tool shows nothing. Never fails.
#include <optional>
#include <string>
#include <vector>

namespace {

constexpr char kNul = '\0';

bool is_space_byte(char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
}

bool has_prefix(const std::string &s, const char *pre) { return s.rfind(pre, 0) == 0; }

std::string trim_ascii(const std::string &s) {
    size_t a = 0, e = s.size();
    while (a < e && is_space_byte(s[a])) a++;
    while (e > a && is_space_byte(s[e - 1])) e--;
    return s.substr(a, e - a);
}

// Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
// the entities we emit are never re-escaped.
std::string encode_html(const std::string &t) {
    std::string out;
    out.reserve(t.size());
    for (char c : t) {
        switch (c) {
        case '&': out += "&amp;"; break;
        case '<': out += "&lt;"; break;
        case '>': out += "&gt;"; break;
        case '\'': out += "&apos;"; break;
        case '"': out += "&quot;"; break;
        default: out += c;
        }
    }
    return out;
}

// Pass 1 of the inline rules: code spans (`([^`]+)`, non-empty content up to
// the next backtick) become \0<index>\0 placeholders so nothing inside them
// is ever reprocessed.
std::string extract_code_spans(const std::string &s, std::vector<std::string> &codes) {
    std::string out;
    out.reserve(s.size());
    size_t i = 0;
    while (i < s.size()) {
        if (s[i] == '`') {
            size_t j = i + 1;
            while (j < s.size() && s[j] != '`') j++;
            if (j < s.size() && j > i + 1) {
                codes.push_back("<code>" + encode_html(s.substr(i + 1, j - i - 1)) + "</code>");
                out += kNul;
                out += std::to_string(codes.size() - 1);
                out += kNul;
                i = j + 1;
                continue;
            }
        }
        out += s[i]; // no closing backtick (or empty span): literal char
        i++;
    }
    return out;
}

// `!\[([^\]]*)\]\(([^)\s]+)\)` — alt may be empty and contain anything but
// `]`; the URL must be non-empty and stop at `)` or whitespace.
std::string replace_images(const std::string &s) {
    std::string out;
    out.reserve(s.size());
    size_t i = 0;
    while (i < s.size()) {
        if (s[i] == '!' && i + 1 < s.size() && s[i + 1] == '[') {
            size_t j = i + 2;
            while (j < s.size() && s[j] != ']') j++;
            if (j < s.size() && j + 1 < s.size() && s[j + 1] == '(') {
                size_t k = j + 2;
                while (k < s.size() && s[k] != ')' && !is_space_byte(s[k])) k++;
                if (k < s.size() && s[k] == ')' && k > j + 2) {
                    out += "<img src=\"";
                    out += s.substr(j + 2, k - j - 2);
                    out += "\" alt=\"";
                    out += s.substr(i + 2, j - i - 2);
                    out += "\">";
                    i = k + 1;
                    continue;
                }
            }
        }
        out += s[i]; // on failure the engine advances one char — emit it
        i++;
    }
    return out;
}

// `\[([^\]]+)\]\(([^)\s]+)\)` — link text must be non-empty (images ran
// first, so `![` is already gone).
std::string replace_links(const std::string &s) {
    std::string out;
    out.reserve(s.size());
    size_t i = 0;
    while (i < s.size()) {
        if (s[i] == '[') {
            size_t j = i + 1;
            while (j < s.size() && s[j] != ']') j++;
            if (j < s.size() && j > i + 1 && j + 1 < s.size() && s[j + 1] == '(') {
                size_t k = j + 2;
                while (k < s.size() && s[k] != ')' && !is_space_byte(s[k])) k++;
                if (k < s.size() && s[k] == ')' && k > j + 2) {
                    out += "<a href=\"";
                    out += s.substr(j + 2, k - j - 2);
                    out += "\">";
                    out += s.substr(i + 1, j - i - 1);
                    out += "</a>";
                    i = k + 1;
                    continue;
                }
            }
        }
        out += s[i];
        i++;
    }
    return out;
}

// Emphasis pairs (`**`/`__` strong, `*`/`_` em, `~~` del): the content may
// not contain the marker char, and the closing marker must follow it
// immediately (backtracking can never help — the skipped chars are non-markers).
std::string replace_pairs(const std::string &s, char marker, size_t width, const char *open, const char *close) {
    std::string out;
    out.reserve(s.size());
    size_t i = 0;
    while (i < s.size()) {
        bool opens = s[i] == marker && (width == 1 || (i + 1 < s.size() && s[i + 1] == marker));
        if (opens) {
            size_t start = i + width;
            size_t j = start;
            while (j < s.size() && s[j] != marker) j++;
            bool closed = j < s.size() && (width == 1 || (j + 1 < s.size() && s[j + 1] == marker));
            if (closed && j > start) {
                out += open;
                out += s.substr(start, j - start);
                out += close;
                i = j + width;
                continue;
            }
        }
        out += s[i];
        i++;
    }
    return out;
}

// `\u0000(\d+)\u0000` — placeholders resolve back to their stored spans.
std::string restore_code_spans(const std::string &s, const std::vector<std::string> &codes) {
    std::string out;
    out.reserve(s.size());
    size_t i = 0;
    while (i < s.size()) {
        if (s[i] == kNul) {
            size_t j = i + 1;
            while (j < s.size() && s[j] >= '0' && s[j] <= '9') j++;
            if (j > i + 1 && j < s.size() && s[j] == kNul) {
                unsigned long v = 0;
                for (size_t k = i + 1; k < j; k++) v = v * 10 + (unsigned long)(s[k] - '0');
                if (v < codes.size()) out += codes[v];
                i = j + 1;
                continue;
            }
        }
        out += s[i];
        i++;
    }
    return out;
}

// Inline pass: code spans first (placeholder-protected), then images, links,
// bold, italic, strikethrough — non-greedy pairs, in TS precedence order.
std::string render_inline(const std::string &s) {
    std::vector<std::string> codes;
    std::string text = encode_html(extract_code_spans(s, codes));
    text = replace_images(text);
    text = replace_links(text);
    text = replace_pairs(text, '*', 2, "<strong>", "</strong>");
    text = replace_pairs(text, '_', 2, "<strong>", "</strong>");
    text = replace_pairs(text, '*', 1, "<em>", "</em>");
    text = replace_pairs(text, '_', 1, "<em>", "</em>");
    text = replace_pairs(text, '~', 2, "<del>", "</del>");
    return restore_code_spans(text, codes);
}

// `^(#{1,6}) (.*)$` — returns the heading level (1-6) or 0.
size_t heading_level(const std::string &line) {
    size_t k = 0;
    while (k < line.size() && line[k] == '#') k++;
    if (k >= 1 && k <= 6 && k < line.size() && line[k] == ' ') return k;
    return 0;
}

// `^(---+|\*\*\*+|___+)\s*$` — the whole run is one marker char (3+), then
// only whitespace.
bool is_hr_line(const std::string &line) {
    if (line.size() < 3) return false;
    char c = line[0];
    if (c != '-' && c != '*' && c != '_') return false;
    size_t k = 0;
    while (k < line.size() && line[k] == c) k++;
    if (k < 3) return false;
    for (size_t i = k; i < line.size(); i++)
        if (!is_space_byte(line[i])) return false;
    return true;
}

// `^[-*+] `
bool is_ul_line(const std::string &line) {
    return line.size() >= 2 && (line[0] == '-' || line[0] == '*' || line[0] == '+') && line[1] == ' ';
}

// `^\d+\. ` — returns the full prefix length (digits + ". ") or 0.
size_t ol_prefix_len(const std::string &line) {
    size_t k = 0;
    while (k < line.size() && line[k] >= '0' && line[k] <= '9') k++;
    if (k >= 1 && k + 1 < line.size() && line[k] == '.' && line[k + 1] == ' ') return k + 2;
    return 0;
}

// True when a line STARTS a new block — the paragraph terminator. Any new
// block type must register here and in the render_block dispatch below.
bool is_block_start(const std::string &line) {
    return heading_level(line) || is_hr_line(line) || has_prefix(line, "```") ||
           has_prefix(line, "> ") || is_ul_line(line) || ol_prefix_len(line);
}

// Append one piece with '\n' separators (out.join('\n') parity).
void emit_piece(std::vector<std::string> &out, std::string piece) { out.push_back(std::move(piece)); }

// Render consecutive lines (one blank-line-separated chunk).
void render_block(const std::vector<std::string> &lines, std::vector<std::string> &out) {
    size_t i = 0;
    while (i < lines.size()) {
        const std::string &line = lines[i];

        size_t level = heading_level(line);
        if (level) {
            emit_piece(out, "<h" + std::to_string(level) + ">" + render_inline(trim_ascii(line.substr(level + 1))) +
                                "</h" + std::to_string(level) + ">");
            i++;
            continue;
        }

        if (is_hr_line(line)) {
            emit_piece(out, "<hr>");
            i++;
            continue;
        }

        if (has_prefix(line, "```")) {
            std::string lang = trim_ascii(line.substr(3));
            std::vector<std::string> body;
            i++;
            while (i < lines.size() && !has_prefix(lines[i], "```")) {
                body.push_back(lines[i]);
                i++;
            }
            i++; // past the closing fence (or past the end of an unclosed fence)
            std::string joined;
            for (size_t k = 0; k < body.size(); k++) {
                if (k) joined += '\n';
                joined += body[k];
            }
            std::string cls = lang.empty() ? "" : " class=\"language-" + encode_html(lang) + "\"";
            emit_piece(out, "<pre><code" + cls + ">" + encode_html(joined) + "</code></pre>");
            continue;
        }

        if (has_prefix(line, "> ")) {
            std::vector<std::string> quoted;
            while (i < lines.size() && has_prefix(lines[i], "> ")) {
                quoted.push_back(lines[i].substr(2));
                i++;
            }
            std::vector<std::string> inner;
            render_block(quoted, inner);
            std::string joined;
            for (size_t k = 0; k < inner.size(); k++) {
                if (k) joined += '\n';
                joined += inner[k];
            }
            emit_piece(out, "<blockquote>\n" + joined + "\n</blockquote>");
            continue;
        }

        if (is_ul_line(line)) {
            std::string joined;
            while (i < lines.size() && is_ul_line(lines[i])) {
                if (!joined.empty()) joined += '\n';
                joined += "<li>" + render_inline(lines[i].substr(2)) + "</li>";
                i++;
            }
            emit_piece(out, "<ul>\n" + joined + "\n</ul>");
            continue;
        }

        if (ol_prefix_len(line)) {
            std::string joined;
            while (i < lines.size() && ol_prefix_len(lines[i])) {
                size_t pl = ol_prefix_len(lines[i]);
                if (!joined.empty()) joined += '\n';
                joined += "<li>" + render_inline(lines[i].substr(pl)) + "</li>";
                i++;
            }
            emit_piece(out, "<ol>\n" + joined + "\n</ol>");
            continue;
        }

        std::string joined;
        while (i < lines.size() && !is_block_start(lines[i])) {
            if (!joined.empty()) joined += '\n';
            joined += render_inline(trim_ascii(lines[i]));
            i++;
        }
        emit_piece(out, "<p>" + joined + "</p>");
    }
}

// Split on runs of 2+ newlines (JS `text.split(/\n{2,}/)`).
std::vector<std::string> split_blocks(const std::string &text) {
    std::vector<std::string> blocks;
    size_t start = 0;
    size_t i = 0;
    while (i < text.size()) {
        if (text[i] == '\n') {
            size_t j = i;
            while (j < text.size() && text[j] == '\n') j++;
            if (j - i >= 2) {
                blocks.push_back(text.substr(start, i - start));
                start = j;
            }
            i = j;
        } else {
            i++;
        }
    }
    blocks.push_back(text.substr(start));
    return blocks;
}

} // namespace

// Result union mirror: output + error (always nullopt — the renderer never fails).
struct MarkdownToHtmlResult {
    std::string output;
    std::optional<std::string> error;
};

// Convert the supported Markdown subset to HTML. Never fails.
MarkdownToHtmlResult markdown_to_html(const std::string &raw) {
    // normalize \r\n? -> \n, then trim
    std::string text;
    text.reserve(raw.size());
    for (size_t k = 0; k < raw.size(); k++) {
        if (raw[k] == '\r') {
            text += '\n';
            if (k + 1 < raw.size() && raw[k + 1] == '\n') k++;
        } else {
            text += raw[k];
        }
    }
    text = trim_ascii(text);
    MarkdownToHtmlResult res;
    if (text.empty()) return res; // empty input is NOT an error — the tool shows nothing
    std::vector<std::string> out;
    for (const std::string &block : split_blocks(text)) {
        std::vector<std::string> lines;
        size_t pos = 0;
        while (pos <= block.size()) {
            size_t end = pos;
            while (end < block.size() && block[end] != '\n') end++;
            if (!trim_ascii(block.substr(pos, end - pos)).empty()) lines.push_back(block.substr(pos, end - pos));
            pos = end + 1;
        }
        render_block(lines, out);
    }
    std::string joined;
    for (size_t k = 0; k < out.size(); k++) {
        if (k) joined += '\n';
        joined += out[k];
    }
    res.output = joined;
    return res;
}

// Example:
//   MarkdownToHtmlResult r = markdown_to_html("## Hello *world*");
//   // r.output == "<h2>Hello <em>world</em></h2>", r.error == nullopt
//   markdown_to_html("```js\nconst x = 1; // <b>\n```").output
//   // == "<pre><code class=\"language-js\">const x = 1; // &lt;b&gt;</code></pre>"
//   markdown_to_html("<script>alert(1)</script>").output
//   // == "<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>"

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 →