Files
gotea/third_party/bb/src/markdown.c
T
lotherk 3eae0cc954 build: vendor bb static site generator
Vendor the C99 bb sources, share directory, tests and man page under third_party/bb (MIT, upstream f5373fb) and add a make bb target. A checkout can now build project sites without an installed bb.

Assisted-by: OpenCode:DeepSeek-V4.1-Flash
2026-11-22 12:27:43 +00:00

566 lines
21 KiB
C

/* markdown.c — minimal CommonMark-subset Markdown -> HTML parser.
* Supports: ATX headings, paragraphs, unordered/ordered lists, fenced code
* blocks, indented code, blockquotes, horizontal rules, tables, and inline
* emphasis/strong/code/links/images. Pure C99, no dependencies.
*
* Memory-efficient: output streams directly to a FILE* (the content file),
* never buffered in RAM. Only one line at a time is held in memory. */
#include "bb.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
/* ---- inline parsing ---- */
/* Relative prefix ("../" * depth) prepended to root-relative links in
* Markdown content, so links work no matter where the site is deployed.
* Set per render by markdown_to_html(). */
static const char *g_md_prefix = "";
/* ---- heading anchors ---- */
/* Turn a heading's text into a URL-safe anchor id: lowercase, spaces and
* runs of non-alphanumerics become a single '-'. Empty result -> "sec". */
static void heading_slug(const char *s, size_t n, char *out, size_t outsz) {
size_t o = 0;
int dash = 0;
for (size_t i = 0; i < n && o + 1 < outsz; i++) {
unsigned char c = (unsigned char)s[i];
if (isalnum(c)) {
out[o++] = (char)tolower(c);
dash = 0;
} else if (!dash) {
out[o++] = '-';
dash = 1;
}
}
while (o > 0 && out[o - 1] == '-') o--;
if (o == 0) { out[o++] = 's'; out[o++] = 'e'; out[o++] = 'c'; }
out[o] = '\0';
}
static void inline_parse(FILE *out, const char *s, size_t n);
/* Find matching closing delimiter for emphasis/strong. Returns index or n. */
static size_t find_close(const char *s, size_t n, char c, size_t start) {
for (size_t i = start; i < n; i++) {
if (s[i] == c) return i;
}
return n;
}
/* Escape a span into a small stack buffer, then write it. */
static void emit_escaped(FILE *out, const char *s, size_t n) {
for (size_t i = 0; i < n; i++) {
switch (s[i]) {
case '&': fputs("&amp;", out); break;
case '<': fputs("&lt;", out); break;
case '>': fputs("&gt;", out); break;
case '"': fputs("&quot;", out); break;
case '\'': fputs("&#39;", out); break;
default: fputc(s[i], out); break;
}
}
}
static void inline_parse(FILE *out, const char *s, size_t n) {
size_t i = 0;
while (i < n) {
char c = s[i];
if (c == '\\' && i + 1 < n) {
fputc(s[i + 1], out);
i += 2;
continue;
}
if (c == '`') {
/* code span */
size_t j = i + 1;
while (j < n && s[j] == '`') j++;
size_t ticks = j - i;
size_t close = i + ticks;
while (close < n) {
if (s[close] == '`') {
size_t k = close;
size_t cnt = 0;
while (k < n && s[k] == '`') { cnt++; k++; }
if (cnt == ticks) break;
close = k;
} else {
close++;
}
}
if (close < n) {
fputs("<code>", out);
emit_escaped(out, s + i + ticks, close - (i + ticks));
fputs("</code>", out);
i = close + ticks;
continue;
}
fputc(c, out);
i++;
continue;
}
if (c == '*' || c == '_') {
/* emphasis or strong */
int strong = (i + 1 < n && s[i + 1] == c);
size_t delim = strong ? 2 : 1;
size_t close = find_close(s, n, c, i + delim);
if (close < n) {
if (strong) {
fputs("<strong>", out);
inline_parse(out, s + i + 2, close - (i + 2));
fputs("</strong>", out);
i = close + 2;
} else {
fputs("<em>", out);
inline_parse(out, s + i + 1, close - (i + 1));
fputs("</em>", out);
i = close + 1;
}
continue;
}
fputc(c, out);
i++;
continue;
}
if (c == '!') {
/* image: ![alt](url) -> <img src="..." alt="..."> */
if (i + 1 < n && s[i + 1] == '[') {
size_t close = find_close(s, n, ']', i + 2);
if (close < n && close + 1 < n && s[close + 1] == '(') {
size_t pend = close + 2;
while (pend < n && s[pend] != ')') pend++;
if (pend < n) {
size_t u = close + 2;
while (u < pend && isspace((unsigned char)s[u])) u++;
size_t uend = pend;
while (uend > u && isspace((unsigned char)s[uend - 1])) uend--;
fputs("<img src=\"", out);
if (uend > u && s[u] == '/') {
fputs(g_md_prefix, out);
emit_escaped(out, s + u + 1, uend - (u + 1));
} else {
emit_escaped(out, s + u, uend - u);
}
fputs("\" alt=\"", out);
emit_escaped(out, s + i + 2, close - (i + 2));
fputs("\">", out);
i = pend + 1;
continue;
}
}
}
fputc(c, out);
i++;
continue;
}
if (c == '[') {
/* link — if the text starts with ![alt](url), render the outer
* link around the image (nested image-in-link, CommonMark) */
if (i + 3 < n && s[i + 1] == '!' && s[i + 2] == '[') {
size_t iclose = find_close(s, n, ']', i + 3);
if (iclose < n && iclose + 1 < n && s[iclose + 1] == '(') {
size_t ipend = iclose + 2;
while (ipend < n && s[ipend] != ')') ipend++;
if (ipend < n) {
/* the outer link: next ]( after the inner url ) */
size_t close = find_close(s, n, ']', ipend + 1);
if (close < n && close + 1 < n && s[close + 1] == '(') {
size_t pend = close + 2;
while (pend < n && s[pend] != ')') pend++;
if (pend < n) {
size_t u = close + 2;
while (u < pend && isspace((unsigned char)s[u])) u++;
size_t uend = pend;
while (uend > u && isspace((unsigned char)s[uend - 1])) uend--;
fputs("<a href=\"", out);
if (uend > u && s[u] == '/') {
fputs(g_md_prefix, out);
emit_escaped(out, s + u + 1, uend - (u + 1));
} else {
emit_escaped(out, s + u, uend - u);
}
fputs("\">", out);
/* the image */
size_t iu = iclose + 2;
while (iu < ipend && isspace((unsigned char)s[iu])) iu++;
size_t iuend = ipend;
while (iuend > iu && isspace((unsigned char)s[iuend - 1])) iuend--;
fputs("<img src=\"", out);
if (iuend > iu && s[iu] == '/') {
fputs(g_md_prefix, out);
emit_escaped(out, s + iu + 1, iuend - (iu + 1));
} else {
emit_escaped(out, s + iu, iuend - iu);
}
fputs("\" alt=\"", out);
emit_escaped(out, s + i + 3, iclose - (i + 3));
fputs("\"></a>", out);
i = pend + 1;
continue;
}
}
}
}
}
/* link */
size_t close = find_close(s, n, ']', i + 1);
if (close < n && close + 1 < n && s[close + 1] == '(') {
size_t pend = close + 2;
while (pend < n && s[pend] != ')') pend++;
if (pend < n) {
/* extract url (trimmed) */
size_t u = close + 2;
while (u < pend && isspace((unsigned char)s[u])) u++;
size_t uend = pend;
while (uend > u && isspace((unsigned char)s[uend - 1])) uend--;
fputs("<a href=\"", out);
if (uend > u && s[u] == '/') {
/* root-relative link: make it page-relative */
fputs(g_md_prefix, out);
emit_escaped(out, s + u + 1, uend - (u + 1));
} else {
emit_escaped(out, s + u, uend - u);
}
fputs("\">", out);
inline_parse(out, s + i + 1, close - (i + 1));
fputs("</a>", out);
i = pend + 1;
continue;
}
}
fputc(c, out);
i++;
continue;
}
switch (c) {
case '&': fputs("&amp;", out); break;
case '<': fputs("&lt;", out); break;
case '>': fputs("&gt;", out); break;
case '"': fputs("&quot;", out); break;
default: fputc(c, out); break;
}
i++;
}
}
/* ---- block parsing ---- */
static int is_atx_heading(const char *line) {
int i = 0;
while (line[i] == ' ') i++;
if (line[i] != '#') return 0;
int j = i;
while (line[j] == '#') j++;
if (j - i > 6) return 0;
if (line[j] != '\0' && line[j] != ' ' && line[j] != '\t') return 0;
return j - i;
}
static int is_fence(const char *line, char *which) {
int i = 0;
while (line[i] == ' ') i++;
if (line[i] != '`' && line[i] != '~') return 0;
char c = line[i];
int j = i;
while (line[j] == c) j++;
if (j - i < 3) return 0;
*which = c;
return 1;
}
static int is_hr(const char *line) {
int i = 0;
while (line[i] == ' ') i++;
if (line[i] == '\0') return 0;
char c = line[i];
if (c != '-' && c != '*' && c != '_') return 0;
int count = 0;
while (line[i] != '\0') {
if (line[i] == c) count++;
else if (line[i] == ' ' || line[i] == '\t') { /* ok */ }
else return 0;
i++;
}
return count >= 3;
}
static int is_blockquote(const char *line) {
int i = 0;
while (line[i] == ' ') i++;
return line[i] == '>';
}
static int is_ul(const char *line) {
int i = 0;
while (line[i] == ' ') i++;
if (line[i] != '-' && line[i] != '*' && line[i] != '+') return 0;
/* require a space (or end) after the marker, else it's emphasis */
i++;
if (line[i] == '\0') return 0;
return line[i] == ' ' || line[i] == '\t';
}
static int is_ol(const char *line) {
int i = 0;
while (line[i] == ' ') i++;
if (!isdigit((unsigned char)line[i])) return 0;
while (isdigit((unsigned char)line[i])) i++;
return line[i] == '.' || line[i] == ')';
}
static int is_table_sep(const char *line) {
int i = 0;
int has_dash = 0;
while (line[i] != '\0') {
char c = line[i];
if (c == '|' || c == ' ' || c == '\t' || c == ':') { /* ok */ }
else if (c == '-') has_dash = 1;
else return 0;
i++;
}
return has_dash;
}
/* Split a table row into cells. Cells are written into a fixed array of
* pointers into a caller-provided buffer (no per-cell malloc). */
static void split_cells(const char *line, char *buf, size_t bufsz,
char **cells, int *count, int max) {
*count = 0;
const char *p = line;
size_t bi = 0;
if (*p == '|') p++;
while (*p && *count < max) {
const char *start = p;
while (*p && *p != '|') p++;
size_t len = (size_t)(p - start);
while (len > 0 && isspace((unsigned char)start[0])) { start++; len--; }
while (len > 0 && isspace((unsigned char)start[len - 1])) len--;
if (bi + len + 1 <= bufsz) {
memcpy(buf + bi, start, len);
buf[bi + len] = '\0';
cells[*count] = buf + bi;
bi += len + 1;
(*count)++;
}
if (*p == '|') p++;
}
}
void markdown_to_html(FILE *out, FILE *in, const char *prefix) {
if (!out || !in) return;
g_md_prefix = prefix ? prefix : "";
/* read lines dynamically (getline), no fixed-size limit */
char *line = NULL;
size_t line_cap = 0;
int in_para = 0;
int in_list = 0; /* 0 none, 1 ul, 2 ol */
int in_blockquote = 0;
int in_table = 0;
int first_line = 1;
while (getline(&line, &line_cap, in) != -1) {
/* strip trailing newline */
size_t li = strlen(line);
while (li > 0 && (line[li-1] == '\n' || line[li-1] == '\r')) line[--li] = '\0';
const char *l = line;
/* strip YAML frontmatter on the first line — only if a closing
* --- is found, else it's a horizontal rule */
if (first_line) {
first_line = 0;
if (strncmp(l, "---", 3) == 0) {
long pos = ftell(in);
int found = 0;
char *pl = NULL;
size_t pl_cap = 0;
while (getline(&pl, &pl_cap, in) != -1) {
size_t pll = strlen(pl);
while (pll > 0 && (pl[pll-1] == '\n' || pl[pll-1] == '\r')) pl[--pll] = '\0';
if (strncmp(pl, "---", 3) == 0) { found = 1; break; }
}
free(pl);
if (found) {
if (getline(&line, &line_cap, in) == -1) break;
li = strlen(line);
while (li > 0 && (line[li-1] == '\n' || line[li-1] == '\r')) line[--li] = '\0';
l = line;
} else {
/* not frontmatter — rewind, treat as hr below */
fseek(in, pos, SEEK_SET);
}
}
}
/* blank line */
int blank = 1;
for (size_t i = 0; i < li; i++) {
if (!isspace((unsigned char)line[i])) { blank = 0; break; }
}
if (blank) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_list) { fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out); in_list = 0; }
if (in_blockquote) { fputs("</blockquote>\n", out); in_blockquote = 0; }
if (in_table) { in_table = 0; }
continue;
}
/* fenced code */
char fence_char = 0;
if (is_fence(l, &fence_char)) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_list) { fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out); in_list = 0; }
if (in_blockquote) { fputs("</blockquote>\n", out); in_blockquote = 0; }
fputs("<pre><code>", out);
while (getline(&line, &line_cap, in) != -1) {
size_t li2 = strlen(line);
while (li2 > 0 && (line[li2-1] == '\n' || line[li2-1] == '\r')) line[--li2] = '\0';
char fc2 = 0;
if (is_fence(line, &fc2) && fc2 == fence_char) break;
emit_escaped(out, line, li2);
fputc('\n', out);
}
fputs("</code></pre>\n", out);
continue;
}
/* ATX heading */
int hlevel = is_atx_heading(l);
if (hlevel) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_list) { fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out); in_list = 0; }
if (in_blockquote) { fputs("</blockquote>\n", out); in_blockquote = 0; }
if (in_table) { in_table = 0; }
const char *h = l;
while (*h == ' ') h++;
h += hlevel;
while (*h == ' ' || *h == '\t') h++;
size_t hlen = strlen(h);
while (hlen > 0 && h[hlen - 1] == '#') hlen--;
while (hlen > 0 && isspace((unsigned char)h[hlen - 1])) hlen--;
char slug[128];
heading_slug(h, hlen, slug, sizeof slug);
fprintf(out, "<h%d id=\"%s\">", hlevel, slug);
inline_parse(out, h, hlen);
fprintf(out, "</h%d>\n", hlevel);
continue;
}
/* horizontal rule */
if (is_hr(l)) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_list) { fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out); in_list = 0; }
if (in_blockquote) { fputs("</blockquote>\n", out); in_blockquote = 0; }
if (in_table) { in_table = 0; }
fputs("<hr>\n", out);
continue;
}
/* blockquote */
if (is_blockquote(l)) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_list) { fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out); in_list = 0; }
if (!in_blockquote) { fputs("<blockquote>\n", out); in_blockquote = 1; }
const char *q = l;
while (*q == ' ') q++;
if (*q == '>') q++;
if (*q == ' ') q++;
fputs("<p>", out);
inline_parse(out, q, strlen(q));
fputs("</p>\n", out);
continue;
}
/* table separator */
if (in_table && is_table_sep(l)) {
continue;
}
/* table header start: a line with | and a following separator */
if (!in_table && strchr(l, '|')) {
/* peek next line to see if it's a separator */
long pos = ftell(in);
char *next = NULL;
size_t next_cap = 0;
if (getline(&next, &next_cap, in) != -1) {
size_t ni = strlen(next);
while (ni > 0 && (next[ni-1] == '\n' || next[ni-1] == '\r')) next[--ni] = '\0';
if (is_table_sep(next)) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_list) { fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out); in_list = 0; }
if (in_blockquote) { fputs("</blockquote>\n", out); in_blockquote = 0; }
in_table = 1;
fputs("<table>\n<thead>\n<tr>\n", out);
char cells[64][128];
char *cellp[64];
int n = 0;
split_cells(l, (char *)cells, sizeof(cells), cellp, &n, 64);
for (int i = 0; i < n; i++) {
fputs("<th>", out);
inline_parse(out, cellp[i], strlen(cellp[i]));
fputs("</th>\n", out);
}
fputs("</tr>\n</thead>\n<tbody>\n", out);
free(next);
continue;
}
/* not a table: rewind and fall through */
fseek(in, pos, SEEK_SET);
free(next);
}
}
/* table body row */
if (in_table && strchr(l, '|')) {
fputs("<tr>\n", out);
char cells[64][128];
char *cellp[64];
int n = 0;
split_cells(l, (char *)cells, sizeof(cells), cellp, &n, 64);
for (int i = 0; i < n; i++) {
fputs("<td>", out);
inline_parse(out, cellp[i], strlen(cellp[i]));
fputs("</td>\n", out);
}
fputs("</tr>\n", out);
continue;
}
/* list item */
int is_ul_item = is_ul(l);
int is_ol_item = is_ol(l);
if (is_ul_item || is_ol_item) {
if (in_para) { fputs("</p>\n", out); in_para = 0; }
if (in_blockquote) { fputs("</blockquote>\n", out); in_blockquote = 0; }
if (in_table) { in_table = 0; }
int want = is_ul_item ? 1 : 2;
if (in_list != want) {
if (in_list) fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out);
fputs(want == 1 ? "<ul>\n" : "<ol>\n", out);
in_list = want;
}
const char *item = l;
while (*item == ' ') item++;
if (is_ul_item) { item++; while (*item == ' ') item++; }
else { while (isdigit((unsigned char)*item)) item++; if (*item=='.'||*item==')') item++; while (*item==' ') item++; }
fputs("<li>", out);
inline_parse(out, item, strlen(item));
fputs("</li>\n", out);
continue;
}
/* paragraph */
if (!in_para) { fputs("<p>", out); in_para = 1; }
else fputc('\n', out);
inline_parse(out, l, li);
}
free(line);
if (in_para) fputs("</p>\n", out);
if (in_list) fputs(in_list == 1 ? "</ul>\n" : "</ol>\n", out);
if (in_blockquote) fputs("</blockquote>\n", out);
if (in_table) fputs("</tbody>\n</table>\n", out);
}