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). C has no stdlib regex, so every TS regex became a byte scanner
* (char + length windows): 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), hr rules of --- or *** or
* ___, ``` 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. Caller frees
* result.output and result.error. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ---- small growable string (NUL bytes are ordinary content) ---- */
typedef struct { char *buf; size_t len, cap; } Str;
static void str_reserve(Str *s, size_t need) {
if (need >= s->cap) {
size_t cap = s->cap ? s->cap : 64;
while (cap <= need) cap *= 2;
s->buf = (char *)realloc(s->buf, cap);
s->cap = cap;
}
}
static void str_push(Str *s, char c) {
str_reserve(s, s->len + 1);
s->buf[s->len++] = c;
}
static void str_append(Str *s, const char *t) {
size_t n = strlen(t);
str_reserve(s, s->len + n);
memcpy(s->buf + s->len, t, n);
s->len += n;
}
static void str_append_n(Str *s, const char *t, size_t n) {
if (n == 0) return;
str_reserve(s, s->len + n);
memcpy(s->buf + s->len, t, n);
s->len += n;
}
static void str_append_str(Str *s, const Str *o) { str_append_n(s, o->buf, o->len); }
static void str_free(Str *s) {
free(s->buf);
s->buf = NULL;
s->len = s->cap = 0;
}
/* Take ownership of the buffer, NUL-terminated. */
static char *str_take(Str *s) {
str_reserve(s, s->len + 1);
s->buf[s->len] = '\0';
char *r = s->buf;
s->buf = NULL;
s->len = s->cap = 0;
return r;
}
/* ---- byte helpers ---- */
static int is_space_byte(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
}
static int line_has_prefix(const char *p, size_t n, const char *pre) {
size_t m = strlen(pre);
return n >= m && memcmp(p, pre, m) == 0;
}
/* ASCII whitespace trim of a window. */
static void window_trim(const char **p, size_t *n) {
size_t a = 0, e = *n;
while (a < e && is_space_byte((*p)[a])) a++;
while (e > a && is_space_byte((*p)[e - 1])) e--;
*p += a;
*n = e - a;
}
/* ---- inline pass scanners ---- */
/* Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
* the entities we emit are never re-escaped. */
static void encode_html(Str *out, const char *p, size_t n) {
for (size_t i = 0; i < n; i++) {
switch (p[i]) {
case '&': str_append(out, "&"); break;
case '<': str_append(out, "<"); break;
case '>': str_append(out, ">"); break;
case '\'': str_append(out, "'"); break;
case '"': str_append(out, """); break;
default: str_push(out, p[i]);
}
}
}
/* `!\[([^\]]*)\]\(([^)\s]+)\)` — alt may be empty and contain anything but
* `]`; the URL must be non-empty and stop at `)` or whitespace. On failure
* the engine advances one char — emit it. */
static void replace_images(const Str *in, Str *out) {
size_t i = 0;
while (i < in->len) {
if (in->buf[i] == '!' && i + 1 < in->len && in->buf[i + 1] == '[') {
size_t j = i + 2;
while (j < in->len && in->buf[j] != ']') j++;
if (j < in->len && j + 1 < in->len && in->buf[j + 1] == '(') {
size_t k = j + 2;
while (k < in->len && in->buf[k] != ')' && !is_space_byte(in->buf[k])) k++;
if (k < in->len && in->buf[k] == ')' && k > j + 2) {
str_append(out, "<img src=\"");
str_append_n(out, in->buf + j + 2, k - j - 2);
str_append(out, "\" alt=\"");
str_append_n(out, in->buf + i + 2, j - i - 2);
str_append(out, "\">");
i = k + 1;
continue;
}
}
}
str_push(out, in->buf[i]);
i++;
}
}
/* `\[([^\]]+)\]\(([^)\s]+)\)` — link text must be non-empty (images ran
* first, so `![` is already gone). */
static void replace_links(const Str *in, Str *out) {
size_t i = 0;
while (i < in->len) {
if (in->buf[i] == '[') {
size_t j = i + 1;
while (j < in->len && in->buf[j] != ']') j++;
if (j < in->len && j > i + 1 && j + 1 < in->len && in->buf[j + 1] == '(') {
size_t k = j + 2;
while (k < in->len && in->buf[k] != ')' && !is_space_byte(in->buf[k])) k++;
if (k < in->len && in->buf[k] == ')' && k > j + 2) {
str_append(out, "<a href=\"");
str_append_n(out, in->buf + j + 2, k - j - 2);
str_append(out, "\">");
str_append_n(out, in->buf + i + 1, j - i - 1);
str_append(out, "</a>");
i = k + 1;
continue;
}
}
}
str_push(out, in->buf[i]);
i++;
}
}
/* 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). */
static void replace_pairs(const Str *in, char marker, size_t width, const char *open, const char *close, Str *out) {
size_t i = 0;
while (i < in->len) {
int opens = in->buf[i] == marker && (width == 1 || (i + 1 < in->len && in->buf[i + 1] == marker));
if (opens) {
size_t start = i + width;
size_t j = start;
while (j < in->len && in->buf[j] != marker) j++;
int closed = j < in->len && (width == 1 || (j + 1 < in->len && in->buf[j + 1] == marker));
if (closed && j > start) {
str_append(out, open);
str_append_n(out, in->buf + start, j - start);
str_append(out, close);
i = j + width;
continue;
}
}
str_push(out, in->buf[i]);
i++;
}
}
/* 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. */
static void extract_code_spans(const char *s, size_t n, Str *t, Str **codes, size_t *n_codes, size_t *cap_codes) {
size_t i = 0;
while (i < n) {
if (s[i] == '`') {
size_t j = i + 1;
while (j < n && s[j] != '`') j++;
if (j < n && j > i + 1) {
Str code = {0};
str_append(&code, "<code>");
encode_html(&code, s + i + 1, j - i - 1);
str_append(&code, "</code>");
if (*n_codes == *cap_codes) {
*cap_codes = *cap_codes ? *cap_codes * 2 : 4;
*codes = (Str *)realloc(*codes, *cap_codes * sizeof(Str));
}
(*codes)[(*n_codes)++] = code;
str_push(t, '\0');
char idx[24];
snprintf(idx, sizeof idx, "%zu", *n_codes - 1);
str_append(t, idx);
str_push(t, '\0');
i = j + 1;
continue;
}
}
str_push(t, s[i]);
i++;
}
}
/* `\u0000(\d+)\u0000` — placeholders resolve back to their stored spans. */
static void restore_codes(const Str *in, const Str *codes, size_t n_codes, Str *out) {
size_t i = 0;
while (i < in->len) {
if (in->buf[i] == '\0') {
size_t j = i + 1;
while (j < in->len && in->buf[j] >= '0' && in->buf[j] <= '9') j++;
if (j > i + 1 && j < in->len && in->buf[j] == '\0') {
size_t v = 0;
for (size_t k = i + 1; k < j; k++) v = v * 10 + (size_t)(in->buf[k] - '0');
if (v < n_codes) str_append_n(out, codes[v].buf, codes[v].len);
i = j + 1;
continue;
}
}
str_push(out, in->buf[i]);
i++;
}
}
/* Inline pass: code spans first (placeholder-protected), then images, links,
* bold, italic, strikethrough — non-greedy pairs, in TS precedence order. */
static void render_inline(const char *s, size_t n, Str *out) {
Str t = {0};
Str *codes = NULL;
size_t n_codes = 0, cap_codes = 0;
extract_code_spans(s, n, &t, &codes, &n_codes, &cap_codes);
Str x = {0}, y = {0};
encode_html(&x, t.buf, t.len); /* escape everything, placeholders survive */
str_free(&t);
replace_images(&x, &y);
str_free(&x);
replace_links(&y, &x);
str_free(&y);
replace_pairs(&x, '*', 2, "<strong>", "</strong>", &y);
str_free(&x);
replace_pairs(&y, '_', 2, "<strong>", "</strong>", &x);
str_free(&y);
replace_pairs(&x, '*', 1, "<em>", "</em>", &y);
str_free(&x);
replace_pairs(&y, '_', 1, "<em>", "</em>", &x);
str_free(&y);
replace_pairs(&x, '~', 2, "<del>", "</del>", &y);
str_free(&x);
restore_codes(&y, codes, n_codes, out);
str_free(&y);
for (size_t c = 0; c < n_codes; c++) str_free(&codes[c]);
free(codes);
}
/* ---- block scanners ---- */
/* `^(#{1,6}) (.*)$` — returns the heading level (1-6) or 0. */
static size_t heading_level(const char *p, size_t n) {
size_t k = 0;
while (k < n && p[k] == '#') k++;
if (k >= 1 && k <= 6 && k < n && p[k] == ' ') return k;
return 0;
}
/* `^(---+|\*\*\*+|___+)\s*$` — the whole run is one marker char (3+), then
* only whitespace. */
static int is_hr_line(const char *p, size_t n) {
if (n < 3) return 0;
char c = p[0];
if (c != '-' && c != '*' && c != '_') return 0;
size_t k = 0;
while (k < n && p[k] == c) k++;
if (k < 3) return 0;
for (size_t i = k; i < n; i++)
if (!is_space_byte(p[i])) return 0;
return 1;
}
/* `^[-*+] ` */
static int is_ul_line(const char *p, size_t n) {
return n >= 2 && (p[0] == '-' || p[0] == '*' || p[0] == '+') && p[1] == ' ';
}
/* `^\d+\. ` — returns the full prefix length (digits + ". ") or 0. */
static size_t ol_prefix_len(const char *p, size_t n) {
size_t k = 0;
while (k < n && p[k] >= '0' && p[k] <= '9') k++;
if (k >= 1 && k + 1 < n && p[k] == '.' && p[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. */
static int is_block_start_line(const char *p, size_t n) {
return heading_level(p, n) || is_hr_line(p, n) || line_has_prefix(p, n, "```") ||
line_has_prefix(p, n, "> ") || is_ul_line(p, n) || ol_prefix_len(p, n);
}
static int line_blank(const char *p, size_t n) {
for (size_t i = 0; i < n; i++)
if (!is_space_byte(p[i])) return 0;
return 1;
}
/* ---- growable line windows ---- */
typedef struct { const char *p; size_t len; } Line;
typedef struct { Line *items; size_t len, cap; } Lines;
static void lines_push(Lines *ls, const char *p, size_t n) {
if (ls->len == ls->cap) {
ls->cap = ls->cap ? ls->cap * 2 : 8;
ls->items = (Line *)realloc(ls->items, ls->cap * sizeof(Line));
}
ls->items[ls->len].p = p;
ls->items[ls->len].len = n;
ls->len++;
}
static void lines_free(Lines *ls) {
free(ls->items);
ls->items = NULL;
ls->len = ls->cap = 0;
}
/* Append one block piece, joining pieces with '\n' (out.join('\n') parity). */
static void emit_piece(Str *out, int *first, const Str *piece) {
if (!*first) str_push(out, '\n');
*first = 0;
str_append_str(out, piece);
}
/* Render consecutive lines (one blank-line-separated chunk). */
static void render_block(const Line *lines, size_t n, Str *out, int *first) {
size_t i = 0;
while (i < n) {
const char *lp = lines[i].p;
size_t ln = lines[i].len;
size_t level = heading_level(lp, ln);
if (level) {
char open[16], close[16];
snprintf(open, sizeof open, "<h%zu>", level);
snprintf(close, sizeof close, "</h%zu>", level);
Str piece = {0};
str_append(&piece, open);
const char *cp = lp + level + 1;
size_t cn = ln - level - 1;
window_trim(&cp, &cn);
render_inline(cp, cn, &piece);
str_append(&piece, close);
emit_piece(out, first, &piece);
str_free(&piece);
i++;
continue;
}
if (is_hr_line(lp, ln)) {
Str piece = {0};
str_append(&piece, "<hr>");
emit_piece(out, first, &piece);
str_free(&piece);
i++;
continue;
}
if (line_has_prefix(lp, ln, "```")) {
const char *langp = lp + 3;
size_t langn = ln - 3;
window_trim(&langp, &langn);
i++;
Lines body = {0};
while (i < n && !line_has_prefix(lines[i].p, lines[i].len, "```")) {
lines_push(&body, lines[i].p, lines[i].len);
i++;
}
i++; /* past the closing fence (or past the end of an unclosed fence) */
Str body_join = {0};
for (size_t k = 0; k < body.len; k++) {
if (k) str_push(&body_join, '\n');
str_append_n(&body_join, body.items[k].p, body.items[k].len);
}
Str piece = {0};
str_append(&piece, "<pre><code");
if (langn) {
str_append(&piece, " class=\"language-");
encode_html(&piece, langp, langn);
str_append(&piece, "\"");
}
str_append(&piece, ">");
encode_html(&piece, body_join.buf, body_join.len);
str_append(&piece, "</code></pre>");
emit_piece(out, first, &piece);
str_free(&piece);
str_free(&body_join);
lines_free(&body);
continue;
}
if (line_has_prefix(lp, ln, "> ")) {
Lines quoted = {0};
while (i < n && line_has_prefix(lines[i].p, lines[i].len, "> ")) {
lines_push("ed, lines[i].p + 2, lines[i].len - 2);
i++;
}
Str inner = {0};
int inner_first = 1;
render_block(quoted.items, quoted.len, &inner, &inner_first);
Str piece = {0};
str_append(&piece, "<blockquote>\n");
str_append_str(&piece, &inner);
str_append(&piece, "\n</blockquote>");
emit_piece(out, first, &piece);
str_free(&piece);
str_free(&inner);
lines_free("ed);
continue;
}
if (is_ul_line(lp, ln)) {
Str piece = {0};
str_append(&piece, "<ul>\n");
int first_item = 1;
while (i < n && is_ul_line(lines[i].p, lines[i].len)) {
if (!first_item) str_push(&piece, '\n');
first_item = 0;
str_append(&piece, "<li>");
render_inline(lines[i].p + 2, lines[i].len - 2, &piece);
str_append(&piece, "</li>");
i++;
}
str_append(&piece, "\n</ul>");
emit_piece(out, first, &piece);
str_free(&piece);
continue;
}
if (ol_prefix_len(lp, ln)) {
Str piece = {0};
str_append(&piece, "<ol>\n");
int first_item = 1;
while (i < n && ol_prefix_len(lines[i].p, lines[i].len)) {
size_t pl = ol_prefix_len(lines[i].p, lines[i].len);
if (!first_item) str_push(&piece, '\n');
first_item = 0;
str_append(&piece, "<li>");
render_inline(lines[i].p + pl, lines[i].len - pl, &piece);
str_append(&piece, "</li>");
i++;
}
str_append(&piece, "\n</ol>");
emit_piece(out, first, &piece);
str_free(&piece);
continue;
}
{
Str piece = {0};
str_append(&piece, "<p>");
int first_line = 1;
while (i < n && !is_block_start_line(lines[i].p, lines[i].len)) {
const char *pp = lines[i].p;
size_t pn = lines[i].len;
window_trim(&pp, &pn);
if (!first_line) str_push(&piece, '\n');
first_line = 0;
render_inline(pp, pn, &piece);
i++;
}
str_append(&piece, "</p>");
emit_piece(out, first, &piece);
str_free(&piece);
}
}
}
/* ---- public entry point ---- */
typedef struct { char *output; char *error; } MarkdownToHtmlResult;
/* Convert the supported Markdown subset to HTML. Never fails. */
MarkdownToHtmlResult markdown_to_html(const char *raw) {
MarkdownToHtmlResult res = { NULL, NULL };
/* normalize \r\n? -> \n, then trim */
Str text = {0};
if (raw) {
for (const char *p = raw; *p; p++) {
if (*p == '\r') {
str_push(&text, '\n');
if (p[1] == '\n') p++;
} else {
str_push(&text, *p);
}
}
}
const char *t = text.buf;
size_t n = text.len;
window_trim(&t, &n);
if (n == 0) {
str_free(&text);
res.output = strdup("");
return res; /* empty input is NOT an error — the tool shows nothing */
}
Str out = {0};
int first = 1;
size_t pos = 0;
while (pos <= n) {
/* chunk ends at the next run of 2+ newlines (or at the end) */
size_t boundary = n;
for (size_t k = pos; k + 1 < n; k++) {
if (t[k] == '\n' && t[k + 1] == '\n') {
boundary = k;
break;
}
}
if (boundary > pos) {
Lines lines = {0};
size_t lpos = pos;
while (lpos <= boundary) {
size_t lend = lpos;
while (lend < boundary && t[lend] != '\n') lend++;
if (!line_blank(t + lpos, lend - lpos)) lines_push(&lines, t + lpos, lend - lpos);
lpos = lend + 1;
}
render_block(lines.items, lines.len, &out, &first);
lines_free(&lines);
}
if (boundary == n) break;
size_t run = boundary;
while (run < n && t[run] == '\n') run++;
pos = run;
}
str_free(&text);
res.output = str_take(&out);
return res;
}
/* Example:
* MarkdownToHtmlResult r = markdown_to_html("## Hello *world*");
* puts(r.output);
* // <h2>Hello <em>world</em></h2>
* MarkdownToHtmlResult b = markdown_to_html("```js\nconst x = 1; // <b>\n```");
* puts(b.output);
* // <pre><code class="language-js">const x = 1; // <b></code></pre>
* MarkdownToHtmlResult e = markdown_to_html("<script>alert(1)</script>");
* puts(e.output);
* // <p><script>alert(1)</script></p>
* free(r.output); free(b.output); free(e.output); */
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 →