Markdown to HTML Converter — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
// markdown-to-html — escape-first CommonMark subset → HTML renderer. Zig port
// (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
// Language: Zig 0.17 (unmanaged ArrayList API). 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 Zig
// stdlib has no regex, so every TS regex became a byte scanner over
// []const u8: 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. Pass an arena allocator — every byte the
// Result references lives in it; deinit the arena to free.
//
// Test: zig test zig.zig
const std = @import("std");
pub const Result = struct {
/// Rendered HTML. Allocator-owned; caller frees.
output: []const u8 = "",
/// null when rendering succeeded (TS: error: null).
err: ?[]const u8 = null,
};
/// JS `\s` (the ASCII set; URLs may not contain any of these).
fn isSpace(b: u8) bool {
return b == ' ' or b == '\t' or b == '\n' or b == 0x0b or b == 0x0c or b == '\r';
}
fn startsWith(s: []const u8, p: []const u8) bool {
return std.mem.startsWith(u8, s, p);
}
/// ASCII whitespace trim.
fn trimAscii(s: []const u8) []const u8 {
var a: usize = 0;
var e = s.len;
while (a < e and isSpace(s[a])) a += 1;
while (e > a and isSpace(s[e - 1])) e -= 1;
return s[a..e];
}
/// Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
/// the entities we emit are never re-escaped.
fn appendEscaped(a: std.mem.Allocator, out: *std.ArrayList(u8), s: []const u8) std.mem.Allocator.Error!void {
for (s) |b| {
switch (b) {
'&' => try out.appendSlice(a, "&"),
'<' => try out.appendSlice(a, "<"),
'>' => try out.appendSlice(a, ">"),
'\'' => try out.appendSlice(a, "'"),
'"' => try out.appendSlice(a, """),
else => try out.append(a, b),
}
}
}
fn encodeHtml(a: std.mem.Allocator, s: []const u8) std.mem.Allocator.Error![]u8 {
var out: std.ArrayList(u8) = .empty;
try appendEscaped(a, &out, s);
return out.items;
}
/// 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.
fn extractCodeSpans(a: std.mem.Allocator, s: []const u8, codes: *std.ArrayList([]const u8)) ![]u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < s.len) {
if (s[i] == '`') {
var j = i + 1;
while (j < s.len and s[j] != '`') j += 1;
if (j < s.len and j > i + 1) {
var code: std.ArrayList(u8) = .empty;
try code.appendSlice(a, "<code>");
try appendEscaped(a, &code, s[i + 1 .. j]);
try code.appendSlice(a, "</code>");
try codes.append(a, code.items);
try out.append(a, 0);
var idx_buf: [24]u8 = undefined;
const idx = std.fmt.bufPrint(&idx_buf, "{d}", .{codes.items.len - 1}) catch unreachable;
try out.appendSlice(a, idx);
try out.append(a, 0);
i = j + 1;
continue;
}
}
try out.append(a, s[i]); // no closing backtick (or empty span): literal char
i += 1;
}
return out.items;
}
/// `!\[([^\]]*)\]\(([^)\s]+)\)` — alt may be empty and contain anything but
/// `]`; the URL must be non-empty and stop at `)` or whitespace.
fn replaceImages(a: std.mem.Allocator, s: []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < s.len) {
if (s[i] == '!' and i + 1 < s.len and s[i + 1] == '[') {
var j = i + 2;
while (j < s.len and s[j] != ']') j += 1;
if (j < s.len and j + 1 < s.len and s[j + 1] == '(') {
var k = j + 2;
while (k < s.len and s[k] != ')' and !isSpace(s[k])) k += 1;
if (k < s.len and s[k] == ')' and k > j + 2) {
try out.appendSlice(a, "<img src=\"");
try out.appendSlice(a, s[j + 2 .. k]);
try out.appendSlice(a, "\" alt=\"");
try out.appendSlice(a, s[i + 2 .. j]);
try out.appendSlice(a, "\">");
i = k + 1;
continue;
}
}
}
try out.append(a, s[i]); // on failure the engine advances one char — emit it
i += 1;
}
return out.items;
}
/// `\[([^\]]+)\]\(([^)\s]+)\)` — link text must be non-empty (images ran
/// first, so `![` is already gone).
fn replaceLinks(a: std.mem.Allocator, s: []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < s.len) {
if (s[i] == '[') {
var j = i + 1;
while (j < s.len and s[j] != ']') j += 1;
if (j < s.len and j > i + 1 and j + 1 < s.len and s[j + 1] == '(') {
var k = j + 2;
while (k < s.len and s[k] != ')' and !isSpace(s[k])) k += 1;
if (k < s.len and s[k] == ')' and k > j + 2) {
try out.appendSlice(a, "<a href=\"");
try out.appendSlice(a, s[j + 2 .. k]);
try out.appendSlice(a, "\">");
try out.appendSlice(a, s[i + 1 .. j]);
try out.appendSlice(a, "</a>");
i = k + 1;
continue;
}
}
}
try out.append(a, s[i]);
i += 1;
}
return out.items;
}
/// 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).
fn replacePairs(a: std.mem.Allocator, s: []const u8, marker: u8, width: usize, open: []const u8, close: []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < s.len) {
const opens = s[i] == marker and (width == 1 or (i + 1 < s.len and s[i + 1] == marker));
if (opens) {
const start = i + width;
var j = start;
while (j < s.len and s[j] != marker) j += 1;
const closed = j < s.len and (width == 1 or (j + 1 < s.len and s[j + 1] == marker));
if (closed and j > start) {
try out.appendSlice(a, open);
try out.appendSlice(a, s[start..j]);
try out.appendSlice(a, close);
i = j + width;
continue;
}
}
try out.append(a, s[i]);
i += 1;
}
return out.items;
}
/// `\u0000(\d+)\u0000` — placeholders resolve back to their stored spans.
fn restoreCodeSpans(a: std.mem.Allocator, s: []const u8, codes: []const []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < s.len) {
if (s[i] == 0) {
var j = i + 1;
while (j < s.len and s[j] >= '0' and s[j] <= '9') j += 1;
if (j > i + 1 and j < s.len and s[j] == 0) {
var v: usize = 0;
for (s[i + 1 .. j]) |d| v = v * 10 + d - '0';
if (v < codes.len) try out.appendSlice(a, codes[v]);
i = j + 1;
continue;
}
}
try out.append(a, s[i]);
i += 1;
}
return out.items;
}
/// Inline pass: code spans first (placeholder-protected), then images, links,
/// bold, italic, strikethrough — non-greedy pairs, in TS precedence order.
fn renderInline(a: std.mem.Allocator, s: []const u8) ![]u8 {
var codes: std.ArrayList([]const u8) = .empty;
var text = try extractCodeSpans(a, s, &codes);
text = try encodeHtml(a, text);
text = try replaceImages(a, text);
text = try replaceLinks(a, text);
text = try replacePairs(a, text, '*', 2, "<strong>", "</strong>");
text = try replacePairs(a, text, '_', 2, "<strong>", "</strong>");
text = try replacePairs(a, text, '*', 1, "<em>", "</em>");
text = try replacePairs(a, text, '_', 1, "<em>", "</em>");
text = try replacePairs(a, text, '~', 2, "<del>", "</del>");
return restoreCodeSpans(a, text, codes.items);
}
/// `^(#{1,6}) (.*)$` — returns the heading level (1-6) or null.
fn headingLevel(line: []const u8) ?usize {
var n: usize = 0;
while (n < line.len and line[n] == '#') n += 1;
if (n >= 1 and n <= 6 and n < line.len and line[n] == ' ') return n;
return null;
}
/// `^(---+|\*\*\*+|___+)\s*$` — the whole run is one marker char (3+), then
/// only whitespace.
fn isHr(line: []const u8) bool {
if (line.len < 3) return false;
const c = line[0];
if (c != '-' and c != '*' and c != '_') return false;
var k: usize = 0;
while (k < line.len and line[k] == c) k += 1;
if (k < 3) return false;
for (line[k..]) |b| if (!isSpace(b)) return false;
return true;
}
/// `^[-*+] `
fn isUl(line: []const u8) bool {
return line.len >= 2 and (line[0] == '-' or line[0] == '*' or line[0] == '+') and line[1] == ' ';
}
/// `^\d+\. ` — returns the full prefix length (digits + ". ") or null.
fn olPrefixLen(line: []const u8) ?usize {
var n: usize = 0;
while (n < line.len and line[n] >= '0' and line[n] <= '9') n += 1;
if (n >= 1 and n + 1 < line.len and line[n] == '.' and line[n + 1] == ' ') return n + 2;
return null;
}
/// True when a line STARTS a new block — the paragraph terminator. Any new
/// block type must register here and in the renderBlock dispatch below.
fn isBlockStart(line: []const u8) bool {
return headingLevel(line) != null or isHr(line) or startsWith(line, "```")
or startsWith(line, "> ") or isUl(line) or olPrefixLen(line) != null;
}
/// Render consecutive lines (one blank-line-separated chunk).
fn renderBlock(a: std.mem.Allocator, lines: []const []const u8, out: *std.ArrayList([]const u8)) !void {
var i: usize = 0;
while (i < lines.len) {
const line = lines[i];
if (headingLevel(line)) |level| {
var piece: std.ArrayList(u8) = .empty;
try piece.appendSlice(a, try std.fmt.allocPrint(a, "<h{d}>", .{level}));
try piece.appendSlice(a, try renderInline(a, trimAscii(line[level + 1 ..])));
try piece.appendSlice(a, try std.fmt.allocPrint(a, "</h{d}>", .{level}));
try out.append(a, piece.items);
i += 1;
continue;
}
if (isHr(line)) {
try out.append(a, "<hr>");
i += 1;
continue;
}
if (startsWith(line, "```")) {
const lang = trimAscii(line[3..]);
var body: std.ArrayList([]const u8) = .empty;
i += 1;
while (i < lines.len and !startsWith(lines[i], "```")) {
try body.append(a, lines[i]);
i += 1;
}
i += 1; // past the closing fence (or past the end of an unclosed fence)
var piece: std.ArrayList(u8) = .empty;
try piece.appendSlice(a, "<pre><code");
if (lang.len != 0) {
try piece.appendSlice(a, " class=\"language-");
try appendEscaped(a, &piece, lang);
try piece.append(a, '"');
}
try piece.append(a, '>');
try appendEscaped(a, &piece, try std.mem.join(a, "\n", body.items));
try piece.appendSlice(a, "</code></pre>");
try out.append(a, piece.items);
continue;
}
if (startsWith(line, "> ")) {
var quoted: std.ArrayList([]const u8) = .empty;
while (i < lines.len and startsWith(lines[i], "> ")) {
try quoted.append(a, lines[i][2..]);
i += 1;
}
var inner: std.ArrayList([]const u8) = .empty;
try renderBlock(a, quoted.items, &inner);
var piece: std.ArrayList(u8) = .empty;
try piece.appendSlice(a, "<blockquote>\n");
try piece.appendSlice(a, try std.mem.join(a, "\n", inner.items));
try piece.appendSlice(a, "\n</blockquote>");
try out.append(a, piece.items);
continue;
}
if (isUl(line)) {
var items: std.ArrayList([]const u8) = .empty;
while (i < lines.len and isUl(lines[i])) {
try items.append(a, try std.fmt.allocPrint(
a,
"<li>{s}</li>",
.{try renderInline(a, lines[i][2..])},
));
i += 1;
}
var piece: std.ArrayList(u8) = .empty;
try piece.appendSlice(a, "<ul>\n");
try piece.appendSlice(a, try std.mem.join(a, "\n", items.items));
try piece.appendSlice(a, "\n</ul>");
try out.append(a, piece.items);
continue;
}
if (olPrefixLen(line) != null) {
var items: std.ArrayList([]const u8) = .empty;
while (i < lines.len) {
const pl = olPrefixLen(lines[i]) orelse break;
try items.append(a, try std.fmt.allocPrint(
a,
"<li>{s}</li>",
.{try renderInline(a, lines[i][pl..])},
));
i += 1;
}
var piece: std.ArrayList(u8) = .empty;
try piece.appendSlice(a, "<ol>\n");
try piece.appendSlice(a, try std.mem.join(a, "\n", items.items));
try piece.appendSlice(a, "\n</ol>");
try out.append(a, piece.items);
continue;
}
var para: std.ArrayList([]const u8) = .empty;
while (i < lines.len and !isBlockStart(lines[i])) {
try para.append(a, try renderInline(a, trimAscii(lines[i])));
i += 1;
}
var piece: std.ArrayList(u8) = .empty;
try piece.appendSlice(a, "<p>");
try piece.appendSlice(a, try std.mem.join(a, "\n", para.items));
try piece.appendSlice(a, "</p>");
try out.append(a, piece.items);
}
}
/// Split on runs of 2+ newlines (JS `text.split(/\n{2,}/)`).
fn splitBlocks(a: std.mem.Allocator, text: []const u8) !std.ArrayList([]const u8) {
var blocks: std.ArrayList([]const u8) = .empty;
var start: usize = 0;
var i: usize = 0;
while (i < text.len) {
if (text[i] == '\n') {
var j = i;
while (j < text.len and text[j] == '\n') j += 1;
if (j - i >= 2) {
try blocks.append(a, text[start..i]);
start = j;
}
i = j;
} else {
i += 1;
}
}
try blocks.append(a, text[start..]);
return blocks;
}
/// `\r\n?` → `\n`
fn normalize(a: std.mem.Allocator, raw: []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
out.ensureTotalCapacity(a, raw.len) catch return error.OutOfMemory;
var i: usize = 0;
while (i < raw.len) {
if (raw[i] == '\r') {
try out.append(a, '\n');
if (i + 1 < raw.len and raw[i + 1] == '\n') i += 1;
} else {
try out.append(a, raw[i]);
}
i += 1;
}
return out.items;
}
/// Convert the supported Markdown subset to HTML. Never fails.
pub fn markdownToHtml(a: std.mem.Allocator, raw: []const u8) std.mem.Allocator.Error!Result {
var text: []const u8 = try normalize(a, raw);
text = trimAscii(text);
if (text.len == 0) {
return .{}; // empty input is NOT an error — the tool shows nothing
}
var out: std.ArrayList([]const u8) = .empty;
const blocks = try splitBlocks(a, text);
for (blocks.items) |block| {
var lines: std.ArrayList([]const u8) = .empty;
var it = std.mem.splitScalar(u8, block, '\n');
while (it.next()) |l| {
if (trimAscii(l).len != 0) try lines.append(a, l);
}
try renderBlock(a, lines.items, &out);
}
return .{ .output = try std.mem.join(a, "\n", out.items), .err = null };
}
test "markdown_to_html headings, rules, fences" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try std.testing.expectEqualStrings("<h2>Hello</h2>", (try markdownToHtml(a, "## Hello")).output);
try std.testing.expectEqualStrings("<h6>Deep</h6>", (try markdownToHtml(a, "###### Deep")).output);
try std.testing.expectEqualStrings("<hr>", (try markdownToHtml(a, "---")).output);
try std.testing.expectEqualStrings("<hr>", (try markdownToHtml(a, "***")).output);
try std.testing.expectEqualStrings("<hr>", (try markdownToHtml(a, "___")).output);
try std.testing.expectEqualStrings(
"<pre><code class=\"language-js\">const x = 1; // <b></code></pre>",
(try markdownToHtml(a, "```js\nconst x = 1; // <b>\n```")).output,
);
try std.testing.expectEqualStrings(
"<pre><code>plain *text*</code></pre>",
(try markdownToHtml(a, "```\nplain *text*\n```")).output,
);
}
test "markdown_to_html blocks, inline marks, escaping, empty input" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
try std.testing.expectEqualStrings(
"<blockquote>\n<h1>quoted</h1>\n<p>body</p>\n</blockquote>",
(try markdownToHtml(a, "> # quoted\n> body")).output,
);
try std.testing.expectEqualStrings(
"<ul>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n</ul>",
(try markdownToHtml(a, "- a\n* b\n+ c")).output,
);
try std.testing.expectEqualStrings(
"<ol>\n<li>first</li>\n<li>second</li>\n</ol>",
(try markdownToHtml(a, "1. first\n2. second")).output,
);
try std.testing.expectEqualStrings(
"<p><strong>b</strong> and <em>i</em> and <del>s</del> and <code>c</code></p>",
(try markdownToHtml(a, "**b** and *i* and ~~s~~ and `c`")).output,
);
try std.testing.expectEqualStrings(
"<p>see <a href=\"https://x.dev\">docs</a> and <img src=\"img.png\" alt=\"logo\"></p>",
(try markdownToHtml(a, "see [docs](https://x.dev) and ")).output,
);
// code spans stay inert: no inline markdown or escaping is reprocessed
try std.testing.expectEqualStrings("<p><code>a *b* <c></code></p>", (try markdownToHtml(a, "`a *b* <c>`")).output);
// raw HTML never passes through — script tags are escaped
try std.testing.expectEqualStrings("<p><script>alert(1)</script></p>", (try markdownToHtml(a, "<script>alert(1)</script>")).output);
try std.testing.expectEqualStrings("<p>just words & <signs></p>", (try markdownToHtml(a, "just words & <signs>")).output);
// soft line breaks join, CRLF normalizes
try std.testing.expectEqualStrings("<p>line one\nline two</p>", (try markdownToHtml(a, "line one\nline two")).output);
try std.testing.expectEqualStrings("<h1>title</h1>\n<p>text</p>", (try markdownToHtml(a, "# title\r\n\r\ntext")).output);
// empty or whitespace-only input is NOT an error
const empty = try markdownToHtml(a, " \n \n ");
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 →