scorpiox-bot-plugin-fetch
←fetch_md.cc
958 lines · 35 KBHEADBlameDownload
1/*
2 * fetch_md.c - forgiving HTML tokenizer -> clean Markdown.
3 *
4 * Clean-room implementation over raw bytes. UTF-8 passes through untouched;
5 * entities are decoded. This is deliberately NOT a DOM: it is the subset a
6 * fetch tool needs to take a page down to readable Markdown:
7 *
8 * - strips comment + script/style/noscript/svg/head/nav/aside/footer/form/
9 * template/button/select/textarea/iframe subtrees
10 * - h1..h6 -> ATX headings
11 * - a -> [text](href) (absolutised against the page URL)
12 * - ul/ol/li -> "- " / "n. " with simple nesting
13 * - pre/code -> fenced block / `code span`
14 * - strong/b, em/i -> ** **, * *
15 * - blockquote -> "> " lines
16 * - table/tr/td/th -> pipe rows
17 * - img -> ![alt](src)
18 * - p/div/br/hr/section/article -> line breaks
19 * - common entities + &#NNN; + &#xHH;
20 */
21#include "fetch_md.h"
22#include "sxbuf.h"
23
24#include <ctype.h>
25#include <stdlib.h>
26#include <string.h>
27
28/* ------------------------------------------------------------------ */
29/* Tokenizer */
30/* ------------------------------------------------------------------ */
31
32typedef enum { TOK_TEXT, TOK_OPEN, TOK_CLOSE } tok_kind;
33
34typedef struct {
35 tok_kind kind;
36 char name[24]; /* lowercased tag name (close/open) */
37 char *text; /* TOK_TEXT: decoded text (heap) */
38 char *attrs; /* TOK_OPEN: raw attribute text */
39 int selfclose;
40} token;
41
42typedef struct {
43 token *v;
44 size_t n, cap;
45} toks;
46
47static void toks_push(toks *t, token *tok)
48{
49 if (t->n == t->cap) {
50 size_t cap = t->cap ? t->cap * 2 : 256;
51 token *nv = (token *)realloc(t->v, cap * sizeof *nv);
52 if (!nv) { fputs("out of memory\n", stderr); exit(1); }
53 t->v = nv;
54 t->cap = cap;
55 }
56 t->v[t->n++] = *tok;
57}
58
59static void toks_free(toks *t)
60{
61 size_t i;
62 for (i = 0; i < t->n; i++) { free(t->v[i].text); free(t->v[i].attrs); }
63 free(t->v);
64 t->v = NULL;
65 t->n = t->cap = 0;
66}
67
68/* ------------------------------------------------------------------ */
69/* Entity decoding */
70/* ------------------------------------------------------------------ */
71
72static void utf8_put(buf_t *b, unsigned cp)
73{
74 if (cp < 0x80) {
75 char c = (char)cp;
76 buf_bput(b, &c, 1);
77 } else if (cp < 0x800) {
78 char c[2] = { (char)(0xC0 | (cp >> 6)), (char)(0x80 | (cp & 0x3F)) };
79 buf_bput(b, c, 2);
80 } else if (cp < 0x10000) {
81 char c[3] = { (char)(0xE0 | (cp >> 12)), (char)(0x80 | ((cp >> 6) & 0x3F)),
82 (char)(0x80 | (cp & 0x3F)) };
83 buf_bput(b, c, 3);
84 } else {
85 char c[4] = { (char)(0xF0 | (cp >> 18)), (char)(0x80 | ((cp >> 12) & 0x3F)),
86 (char)(0x80 | ((cp >> 6) & 0x3F)), (char)(0x80 | (cp & 0x3F)) };
87 buf_bput(b, c, 4);
88 }
89}
90
91typedef struct { const char *name; const char *utf8; } ent_map;
92static const ent_map ENTITIES[] = {
93 { "amp", "&" }, { "lt", "<" }, { "gt", ">" }, { "quot", "\"" },
94 { "apos", "'" }, { "nbsp", "\xC2\xA0" },
95 { "zwnj", "" }, { "zwj", "" }, { "lrm", "" },
96 { "rdquo", "\xE2\x80\x9D" }, { "ldquo", "\xE2\x80\x9C" },
97 { "sbquo", "\xE2\x80\x9A" }, { "bdquo", "\xE2\x80\x9E" },
98 { "mdash", "\xE2\x80\x94" }, { "ndash", "\xE2\x80\x93" },
99 { "hellip", "\xE2\x80\xA6" }, { "middot", "\xC2\xB7" },
100 { "bull", "\xE2\x80\xA2" }, { "deg", "\xC2\xB0" },
101 { "copy", "\xC2\xA9" }, { "reg", "\xC2\xAE" }, { "trade", "\xE2\x84\xA2" },
102 { "laquo", "\xC2\xAB" }, { "raquo", "\xC2\xBB" },
103 { "times", "\xC3\x97" }, { "divide", "\xC3\xB7" }, { "plusmn", "\xC2\xB1" },
104 { "frac12", "\xC2\xBD" }, { "frac14", "\xC2\xBC" }, { "frac34", "\xC2\xBE" },
105 { "sect", "\xC2\xA7" }, { "para", "\xC2\xB6" }, { "dagger", "\xE2\x80\xA0" },
106 { "permil", "\xE2\x80\xB0" }, { "euro", "\xE2\x82\xAC" },
107 { "pound", "\xC2\xA3" }, { "yen", "\xC2\xA5" }, { "cent", "\xC2\xA2" },
108 { "curren", "\xC2\xA4" }, { "cldquo", "\xE2\x80\x9C" },
109 { "lsquo", "\xE2\x80\x98" }, { "rsquo", "\xE2\x80\x99" },
110 { "ne", "\xE2\x89\xA0" }, { "le", "\xE2\x89\xA4" }, { "ge", "\xE2\x89\xA5" },
111 { "larr", "\xE2\x86\x90" }, { "rarr", "\xE2\x86\x92" },
112 { "uarr", "\xE2\x86\x91" }, { "darr", "\xE2\x86\x93" },
113 { "harr", "\xE2\x86\x94" }, { "minus", "\xE2\x88\x92" },
114 { "micro", "\xC2\xB5" }, { "sup2", "\xC2\xB2" }, { "sup3", "\xC2\xB3" },
115 { "sup1", "\xC2\xB9" }, { "prime", "\xE2\x80\xB2" },
116 { "check", "\xE2\x9C\x93" }, { "star", "\xE2\x98\x85" },
117 /* The Latin-1 supplement named entities: a page that writes caf&eacute;
118 * (which plenty still do) has to read back as cafe with an accent, not
119 * as the literal source text. */
120 { "eacute", "\xC3\xA9" }, { "egrave", "\xC3\xA8" },
121 { "ecirc", "\xC3\xAA" }, { "euml", "\xC3\xAF" },
122 { "aacute", "\xC3\xA1" }, { "agrave", "\xC3\xA0" },
123 { "acirc", "\xC3\xA2" }, { "auml", "\xC3\xA4" },
124 { "ocirc", "\xC3\xB4" }, { "oacute", "\xC3\xB3" },
125 { "ouml", "\xC3\xB6" }, { "ucirc", "\xC3\xBB" },
126 { "uacute", "\xC3\xBA" }, { "uuml", "\xC3\xBC" },
127 { "icirc", "\xC3\xAE" }, { "iacute", "\xC3\xAD" },
128 { "iuml", "\xC3\xAF" }, { "ccedil", "\xC3\xA7" },
129 { "ntilde", "\xC3\xB1" }, { "szlig", "\xC3\x9F" },
130 { "Aacute", "\xC3\x81" }, { "Eacute", "\xC3\x89" },
131 { "Uuml", "\xC3\x9C" }, { "Oslash", "\xC3\x98" },
132 { "divide", "\xC3\xB7" }, { "iquest", "\xC2\xBF" },
133 { "iexcl", "\xC2\xA1" }, { "brvbar", "\xC2\xA6" },
134 { "not", "\xC2\xAC" }, { "macr", "\xC2\xAF" },
135 { "acute", "\xC2\xB4" }, { "grave", "\xC2\x60" },
136 { "cedil", "\xC2\xB8" }, { "curren", "\xC2\xA4" },
137 { "frac13", "\xE2\x85\x93" }, { "line", "|" },
138 { "verbar", "|" }, { "brvbar", "\xC2\xA6" },
139 { "ensp", "\xE2\x80\x82" }, { "emsp", "\xE2\x80\x83" },
140 { "thinsp", "\xE2\x80\x89" }, { "shy", "" },
141 { "hearts", "\xE2\x99\xA5" }, { "spades", "\xE2\x99\xA0" },
142 { "clubs", "\xE2\x99\xA3" }, { "diams", "\xE2\x99\xA6" },
143 { NULL, NULL }
144};
145
146static int entity_named(const char *name, size_t len, buf_t *out)
147{
148 int i;
149 for (i = 0; ENTITIES[i].name; i++)
150 if (strlen(ENTITIES[i].name) == len &&
151 strncmp(ENTITIES[i].name, name, len) == 0) {
152 buf_add(out, ENTITIES[i].utf8);
153 return 1;
154 }
155 return 0;
156}
157
158static void decode_entities(const char *s, size_t n, buf_t *out)
159{
160 size_t i = 0;
161 while (i < n) {
162 if (s[i] == '&') {
163 const char *semi = (const char *)memchr(s + i, ';', n - i);
164 if (semi && (size_t)(semi - (s + i)) < 12) {
165 size_t len = (size_t)(semi - (s + i)) - 1;
166 const char *nm = s + i + 1;
167 if (len > 1 && nm[0] == '#') {
168 unsigned cp = 0;
169 int ok = 1;
170 if (nm[1] == 'x' || nm[1] == 'X') {
171 size_t j;
172 for (j = 2; j < len; j++) {
173 if (!isxdigit((unsigned char)nm[j])) { ok = 0; break; }
174 cp = cp * 16 + (unsigned)(isdigit((unsigned char)nm[j])
175 ? nm[j] - '0'
176 : (tolower((unsigned char)nm[j]) - 'a' + 10));
177 }
178 } else {
179 size_t j;
180 for (j = 1; j < len; j++) {
181 if (!isdigit((unsigned char)nm[j])) { ok = 0; break; }
182 cp = cp * 10 + (unsigned)(nm[j] - '0');
183 }
184 }
185 if (ok && cp > 0 && cp <= 0x10FFFF) {
186 if (cp >= 0xD800 && cp <= 0xDFFF) cp = 0xFFFD;
187 utf8_put(out, cp);
188 i += len + 2;
189 continue;
190 }
191 } else if (len > 0) {
192 /* named entities may arrive with mixed case */
193 char lower[12];
194 size_t j;
195 for (j = 0; j < len && j < sizeof lower - 1; j++)
196 lower[j] = (char)tolower((unsigned char)nm[j]);
197 lower[j < len ? j : len] = '\0';
198 if (j <= len) {
199 if (entity_named(lower, j, out)) { i += len + 2; continue; }
200 if (entity_named(nm, len, out)) { i += len + 2; continue; }
201 }
202 }
203 }
204 }
205 buf_bput(out, s + i, 1);
206 i++;
207 }
208}
209
210#ifdef memmem
211#undef memmem
212#endif
213static const char *sx_memmem(const char *h, size_t hl, const char *n, size_t nl)
214{
215 size_t i;
216 if (nl == 0 || hl < nl) return NULL;
217 for (i = 0; i + nl <= hl; i++)
218 if (memcmp(h + i, n, nl) == 0) return h + i;
219 return NULL;
220}
221#define memmem sx_memmem
222
223/* ------------------------------------------------------------------ */
224/* Tokenizer core */
225/* ------------------------------------------------------------------ */
226
227static int tag_skip(const char *name)
228{
229 static const char *const skip[] = {
230 "script", "style", "noscript", "svg", "head", "nav", "aside",
231 "footer", "form", "template", "button", "select", "textarea",
232 "iframe", "canvas", "video", "audio", "picture", "map", "object",
233 "embed", "link", "meta", NULL
234 };
235 int i;
236 for (i = 0; skip[i]; i++) if (strcmp(skip[i], name) == 0) return 1;
237 return 0;
238}
239
240static void tokenize(const char *html, size_t len, toks *out)
241{
242 size_t i = 0;
243
244 memset(out, 0, sizeof *out); /* cap/n must start at zero: toks_push grows from them */
245 buf_t text;
246 buf_init(&text);
247
248#define FLUSH_TEXT() \
249 do { \
250 if (text.n) { \
251 token tk; \
252 memset(&tk, 0, sizeof tk); \
253 tk.kind = TOK_TEXT; \
254 tk.text = (char *)sx_malloc(text.n + 1); \
255 memcpy(tk.text, text.p, text.n); \
256 tk.text[text.n] = '\0'; \
257 toks_push(out, &tk); \
258 free(text.p); \
259 buf_init(&text); \
260 } \
261 } while (0)
262
263 while (i < len) {
264 if (html[i] == '<') {
265 /* comment / CDATA / doctype */
266 if (i + 3 < len && html[i + 1] == '!' && html[i + 2] == '-' &&
267 html[i + 3] == '-') {
268 const char *end = NULL;
269 if (i + 4 < len)
270 end = (const char *)memmem(html + i + 4, len - i - 4, "-->", 3);
271 i = end ? (size_t)(end - html) + 3 : len;
272 continue;
273 }
274 if (i + 1 < len && (html[i + 1] == '!' || html[i + 1] == '?')) {
275 const char *gt = (const char *)memchr(html + i, '>', len - i);
276 i = gt ? (size_t)(gt - html) + 1 : len;
277 continue;
278 }
279 if (i + 1 < len && (isalpha((unsigned char)html[i + 1]) ||
280 html[i + 1] == '/')) {
281 size_t j = i + 1;
282 int closing = 0;
283 char name[24];
284 size_t nl = 0;
285 const char *attr_start;
286 const char *gt;
287 token tk;
288
289 if (html[j] == '/') { closing = 1; j++; }
290 while (j < len && (isalnum((unsigned char)html[j]) || html[j] == '-')) {
291 if (nl < sizeof name - 1)
292 name[nl++] = (char)tolower((unsigned char)html[j]);
293 j++;
294 }
295 name[nl] = '\0';
296 if (nl == 0) { /* stray '<' as text */
297 buf_bput(&text, "<", 1);
298 i++;
299 continue;
300 }
301 attr_start = html + j;
302 /* skip to the closing '>' respecting quoted values */
303 gt = html + j;
304 while (gt < html + len) {
305 if (*gt == '"' || *gt == '\'') {
306 char q = *gt;
307 gt++;
308 while (gt < html + len && *gt != q) gt++;
309 if (gt < html + len) gt++;
310 } else if (*gt == '>') break;
311 else gt++;
312 }
313 if (gt >= html + len) { /* unterminated tag: swallow rest */
314 i = len;
315 continue;
316 }
317 FLUSH_TEXT();
318 memset(&tk, 0, sizeof tk);
319 snprintf(tk.name, sizeof tk.name, "%s", name);
320 if (closing) {
321 tk.kind = TOK_CLOSE;
322 } else {
323 size_t alen = (size_t)(gt - attr_start);
324 tk.kind = TOK_OPEN;
325 tk.selfclose = (alen && attr_start[alen - 1] == '/');
326 if (tk.selfclose) alen--;
327 /* trailing spaces */
328 while (alen && (unsigned char)attr_start[alen - 1] <= ' ') alen--;
329 if (alen) {
330 buf_t a;
331 buf_init(&a);
332 decode_entities(attr_start, alen, &a);
333 tk.attrs = a.p ? a.p : (char *)sx_malloc(1);
334 if (!a.p) tk.attrs[0] = '\0';
335 }
336 }
337 toks_push(out, &tk);
338 i = (size_t)(gt - html) + 1;
339 continue;
340 }
341 /* lone '<' */
342 buf_bput(&text, "<", 1);
343 i++;
344 continue;
345 }
346 {
347 const char *lt = (const char *)memchr(html + i, '<', len - i);
348 size_t n = lt ? (size_t)(lt - (html + i)) : len - i;
349 decode_entities(html + i, n, &text);
350 i += n;
351 }
352 }
353 FLUSH_TEXT();
354#undef FLUSH_TEXT
355}
356
357/* ------------------------------------------------------------------ */
358/* Attribute lookup */
359/* ------------------------------------------------------------------ */
360
361/* Find attr `key` in raw attribute text; unquotes + decodes into out. */
362static int attr_get(const char *attrs, const char *key, char *out, size_t outsz)
363{
364 const char *p = attrs;
365 size_t klen = strlen(key);
366 out[0] = '\0';
367 if (!attrs) return 0;
368 while (*p) {
369 const char *eq;
370 size_t alen;
371 while (*p && (unsigned char)*p <= ' ') p++;
372 if (!*p) break;
373 eq = p;
374 while (*eq && *eq != '=' && (unsigned char)*eq > ' ') eq++;
375 alen = (size_t)(eq - p);
376 if (alen == klen && sx_strncasecmp(p, key, klen) == 0 && *eq == '=') {
377 const char *v = eq + 1;
378 const char *ve;
379 buf_t b;
380 char raw[2048];
381 size_t rn = 0;
382 while (*v && (unsigned char)*v <= ' ') v++;
383 if (*v == '"' || *v == '\'') {
384 char q = *v++;
385 while (*v && *v != q && rn + 1 < sizeof raw) raw[rn++] = *v++;
386 ve = v;
387 } else {
388 while (*v && (unsigned char)*v > ' ' && rn + 1 < sizeof raw)
389 raw[rn++] = *v++;
390 ve = v;
391 }
392 raw[rn] = '\0';
393 (void)ve;
394 buf_init(&b);
395 decode_entities(raw, rn, &b);
396 if (b.p) {
397 snprintf(out, outsz, "%s", b.p);
398 free(b.p);
399 }
400 p = v;
401 return 1;
402 }
403 /* skip value */
404 while (*eq && *eq != '=' && (unsigned char)*eq > ' ') eq++;
405 if (*eq == '=') {
406 eq++;
407 while (*eq && (unsigned char)*eq <= ' ') eq++;
408 if (*eq == '"' || *eq == '\'') {
409 char q = *eq++;
410 while (*eq && *eq != q) eq++;
411 if (*eq) eq++;
412 } else {
413 while (*eq && (unsigned char)*eq > ' ') eq++;
414 }
415 p = eq;
416 } else {
417 p = eq;
418 }
419 }
420 return 0;
421}
422
423/* ------------------------------------------------------------------ */
424/* Link absolutisation */
425/* ------------------------------------------------------------------ */
426
427static char g_base[1024];
428
429void fx_md_set_base_url(const char *url)
430{
431 if (url && *url) snprintf(g_base, sizeof g_base, "%s", url);
432 else g_base[0] = '\0';
433}
434
435static void absolutise(const char *href, char *out, size_t outsz)
436{
437 if (!href || !*href) { out[0] = '\0'; return; }
438 if (strstr(href, "://") || strncmp(href, "mailto:", 7) == 0 ||
439 strncmp(href, "tel:", 4) == 0 || href[0] == '#') {
440 snprintf(out, outsz, "%s", href);
441 return;
442 }
443 if (!g_base[0]) { snprintf(out, outsz, "%s", href); return; }
444 {
445 char scheme[16] = "", host[300] = "";
446 const char *sc = strstr(g_base, "://");
447 const char *hs, *he;
448 if (!sc) { snprintf(out, outsz, "%s", href); return; }
449 {
450 size_t n = (size_t)(sc - g_base);
451 if (n >= sizeof scheme) n = sizeof scheme - 1;
452 memcpy(scheme, g_base, n);
453 scheme[n] = '\0';
454 }
455 hs = sc + 3;
456 he = hs;
457 while (*he && *he != '/' && *he != '?') he++;
458 {
459 size_t n = (size_t)(he - hs);
460 if (n >= sizeof host) n = sizeof host - 1;
461 memcpy(host, hs, n);
462 host[n] = '\0';
463 }
464 if (href[0] == '/')
465 snprintf(out, outsz, "%s://%s%s", scheme, host, href);
466 else {
467 char relbase[1024];
468 const char *slash;
469 snprintf(relbase, sizeof relbase, "%s", g_base);
470 slash = strrchr(relbase, '/');
471 if (slash && slash > sc + 3 - 0) {
472 /* keep everything up to and including the last '/' */
473 /* but never before the authority */
474 if (slash >= strchr(relbase, '\0') - 0) {}
475 {
476 size_t keep = (size_t)(slash - relbase) + 1;
477 /* don't cut into the scheme://authority */
478 const char *auth = strstr(relbase, "://");
479 size_t authend = auth ? (size_t)(auth - relbase) + 3 : 0;
480 const char *pa = strchr(relbase + authend, '/');
481 size_t pathstart = pa ? (size_t)(pa - relbase) : authend;
482 if (keep < pathstart) keep = pathstart;
483 if (keep >= authend) {
484 relbase[keep] = '\0';
485 snprintf(out, outsz, "%s%s", relbase, href);
486 } else
487 snprintf(out, outsz, "%s/%s", relbase, href);
488 }
489 } else
490 snprintf(out, outsz, "%s/%s", relbase, href);
491 }
492 }
493}
494
495/* ------------------------------------------------------------------ */
496/* Renderer */
497/* ------------------------------------------------------------------ */
498
499static int ends_with_blank(buf_t *b)
500{
501 if (!b->p || b->n == 0) return 1;
502 if (b->p[b->n - 1] == '\n')
503 return (b->n >= 2 && b->p[b->n - 2] == '\n');
504 return 0;
505}
506
507static void ensure_newline(buf_t *b)
508{
509 if (b->p && b->n && b->p[b->n - 1] != '\n') buf_add(b, "\n");
510}
511
512static void ensure_blank_line(buf_t *b)
513{
514 if (!b->p || b->n == 0) return;
515 ensure_newline(b);
516 if (!ends_with_blank(b)) buf_add(b, "\n");
517}
518
519static void collapse_ws_append(buf_t *out, const char *s)
520{
521 int in_ws = 0;
522 for (; *s; s++) {
523 if ((unsigned char)*s <= ' ') { in_ws = 1; continue; }
524 if (in_ws && out->n && out->p[out->n - 1] != '\n') buf_add(out, " ");
525 in_ws = 0;
526 buf_bput(out, s, 1);
527 }
528 if (in_ws && out->n && out->p[out->n - 1] != '\n') buf_add(out, " ");
529}
530
531typedef struct {
532 buf_t *out;
533 int in_pre;
534 int pre_fence;
535 int list_depth;
536 int list_ordered[12];
537 int list_count[12];
538 int in_table_row;
539 int row_cells;
540 int row_had_th;
541 int first_row;
542 int link_depth;
543 int skip_depth_guard;
544} render_state;
545
546static void render_tokens(toks *t, size_t from, size_t to, render_state *st);
547
548/* find the matching close for tokens[i] (an open), returns index+1 of the
549 * close, or `to` when unbalanced. */
550static size_t find_close(toks *t, size_t i, size_t to)
551{
552 int depth = 0;
553 size_t j;
554 for (j = i; j < to; j++) {
555 if (t->v[j].kind == TOK_OPEN && strcmp(t->v[j].name, t->v[i].name) == 0 &&
556 !t->v[j].selfclose)
557 depth++;
558 else if (t->v[j].kind == TOK_CLOSE && strcmp(t->v[j].name, t->v[i].name) == 0) {
559 depth--;
560 if (depth == 0) return j + 1;
561 }
562 }
563 return to;
564}
565
566static void render_tokens(toks *t, size_t from, size_t to, render_state *st)
567{
568 size_t i;
569 buf_t *out = st->out;
570
571 for (i = from; i < to; i++) {
572 token *tk = &t->v[i];
573 switch (tk->kind) {
574 case TOK_TEXT: {
575 if (st->in_pre) {
576 buf_add(out, tk->text);
577 } else {
578 collapse_ws_append(out, tk->text);
579 }
580 break;
581 }
582 case TOK_OPEN: {
583 const char *nm = tk->name;
584 if (tag_skip(nm)) {
585 if (!tk->selfclose) i = find_close(t, i, to) - 1;
586 break;
587 }
588 if (strcmp(nm, "br") == 0) {
589 if (st->in_pre) buf_add(out, "\n");
590 else { ensure_newline(out); }
591 break;
592 }
593 if (strcmp(nm, "hr") == 0) {
594 ensure_blank_line(out);
595 buf_add(out, "---\n");
596 break;
597 }
598 if (strcmp(nm, "img") == 0) {
599 char alt[256] = "", src[1024] = "", abs[1200];
600 attr_get(tk->attrs, "alt", alt, sizeof alt);
601 attr_get(tk->attrs, "src", src, sizeof src);
602 if (src[0]) {
603 absolutise(src, abs, sizeof abs);
604 buf_add(out, "![");
605 buf_add(out, alt);
606 buf_add(out, "](");
607 buf_add(out, abs);
608 buf_add(out, ")");
609 }
610 break;
611 }
612 if (nm[0] == 'h' && nm[1] >= '1' && nm[1] <= '6' && nm[2] == '\0') {
613 size_t end = tk->selfclose ? i + 1 : find_close(t, i, to);
614 buf_t sub;
615 render_state sub_st = *st;
616 int lvl = nm[1] - '0', k;
617 ensure_blank_line(out);
618 for (k = 0; k < lvl; k++) buf_add(out, "#");
619 buf_add(out, " ");
620 buf_init(&sub);
621 sub_st.out = &sub;
622 render_tokens(t, i + 1, end > 0 ? end - 1 : i + 1, &sub_st);
623 if (sub.p) {
624 char *p = sub.p;
625 while (*p && (unsigned char)*p <= ' ') p++; /* drop leading ws */
626 buf_add(out, p);
627 free(sub.p);
628 }
629 ensure_blank_line(out);
630 i = end - 1;
631 break;
632 }
633 if (strcmp(nm, "p") == 0 || strcmp(nm, "div") == 0 ||
634 strcmp(nm, "section") == 0 || strcmp(nm, "article") == 0 ||
635 strcmp(nm, "main") == 0 || strcmp(nm, "header") == 0 ||
636 strcmp(nm, "figure") == 0 || strcmp(nm, "figcaption") == 0 ||
637 strcmp(nm, "dl") == 0 || strcmp(nm, "dd") == 0 ||
638 strcmp(nm, "dt") == 0) {
639 ensure_blank_line(out);
640 break;
641 }
642 if (strcmp(nm, "blockquote") == 0) {
643 size_t end = tk->selfclose ? i : find_close(t, i, to);
644 buf_t sub;
645 render_state sub_st = *st;
646 char *line, *nl;
647 buf_init(&sub);
648 sub_st.out = &sub;
649 render_tokens(t, i + 1, end ? end - 1 : i + 1, &sub_st);
650 if (sub.p) {
651 line = sub.p;
652 while (line && *line) {
653 nl = strchr(line, '\n');
654 if (nl) *nl = '\0';
655 if (*line) buf_addf(out, "> %s\n", line);
656 else buf_add(out, ">\n");
657 if (!nl) break;
658 line = nl + 1;
659 }
660 free(sub.p);
661 }
662 ensure_blank_line(out);
663 i = end - 1;
664 break;
665 }
666 if (strcmp(nm, "ul") == 0 || strcmp(nm, "ol") == 0) {
667 /* nm[1] is 'l' for ol and 'l' for ul too - the difference is
668 * nm[0]: 'o' versus 'u'. Comparing the second character made
669 * every unordered list render as a numbered one. */
670 int d = st->list_depth;
671 if (d < 12) {
672 st->list_ordered[d] = (nm[0] == 'o');
673 st->list_count[d] = 0;
674 }
675 st->list_depth++;
676 ensure_newline(out);
677 break;
678 }
679 if (strcmp(nm, "li") == 0) {
680 /* The marker belongs to the INNERMOST open list: an <li>
681 * always sits directly inside its own ul/ol, so depth-1 is
682 * the list it belongs to, and its own counter is the one that
683 * increments (which restarts numbering for a nested sublist
684 * while the parent keeps counting). */
685 int d = st->list_depth > 0 ? st->list_depth - 1 : 0;
686 int k;
687 ensure_newline(out);
688 for (k = 0; k < d; k++) buf_add(out, " ");
689 if (d < 12 && st->list_ordered[d]) {
690 st->list_count[d]++;
691 buf_addf(out, "%d. ", st->list_count[d]);
692 } else {
693 buf_add(out, "- ");
694 }
695 break;
696 }
697 if (strcmp(nm, "pre") == 0) {
698 size_t end = tk->selfclose ? i : find_close(t, i, to);
699 size_t j;
700 ensure_blank_line(out);
701 buf_add(out, "```\n");
702 st->in_pre = 1;
703 /* emit raw text tokens between i+1..end-1 (decode entities,
704 * keep whitespace) */
705 for (j = i + 1; j + 1 < end; j++) {
706 if (t->v[j].kind == TOK_TEXT) buf_add(out, t->v[j].text);
707 else if (t->v[j].kind == TOK_OPEN &&
708 strcmp(t->v[j].name, "br") == 0) buf_add(out, "\n");
709 }
710 st->in_pre = 0;
711 ensure_newline(out);
712 buf_add(out, "```\n");
713 ensure_blank_line(out);
714 i = end - 1;
715 break;
716 }
717 if (strcmp(nm, "code") == 0) {
718 if (!st->in_pre) buf_add(out, "`");
719 break;
720 }
721 if (strcmp(nm, "a") == 0) {
722 char href[1200] = "", abs[1400];
723 size_t end = tk->selfclose ? i + 1 : find_close(t, i, to);
724 if (end > i + 1) {
725 buf_t sub;
726 render_state sub_st = *st;
727 attr_get(tk->attrs, "href", href, sizeof href);
728 buf_init(&sub);
729 sub_st.out = &sub;
730 render_tokens(t, i + 1, end - 1, &sub_st);
731 if (sub.p) {
732 char *p = sub.p;
733 while (*p && (unsigned char)*p <= ' ') p++;
734 if (*p) {
735 buf_add(out, "[");
736 buf_add(out, p);
737 buf_add(out, "](");
738 absolutise(href, abs, sizeof abs);
739 buf_add(out, abs);
740 buf_add(out, ")");
741 }
742 free(sub.p);
743 }
744 }
745 i = end - 1;
746 break;
747 }
748 if (strcmp(nm, "strong") == 0 || strcmp(nm, "b") == 0) {
749 buf_add(out, "**");
750 break;
751 }
752 if (strcmp(nm, "em") == 0 || strcmp(nm, "i") == 0) {
753 buf_add(out, "*");
754 break;
755 }
756 if (strcmp(nm, "table") == 0) {
757 ensure_blank_line(out);
758 st->first_row = 1;
759 break;
760 }
761 if (strcmp(nm, "tr") == 0) {
762 st->in_table_row = 1;
763 st->row_cells = 0;
764 st->row_had_th = 0;
765 ensure_newline(out);
766 break;
767 }
768 if (strcmp(nm, "td") == 0 || strcmp(nm, "th") == 0) {
769 /* Cells separate with a pipe, and the row opens with one:
770 * "| a | b |". Without the leading bar a row of more than
771 * one cell was a line of text with a bar stuck in the
772 * middle, which no Markdown renderer will pick up. */
773 if (st->row_cells) buf_add(out, " |");
774 else buf_add(out, "|");
775 buf_add(out, " ");
776 st->row_cells++;
777 if (nm[1] == 'h') st->row_had_th = 1;
778 break;
779 }
780 break;
781 }
782 case TOK_CLOSE: {
783 const char *nm = tk->name;
784 if (strcmp(nm, "ul") == 0 || strcmp(nm, "ol") == 0) {
785 if (st->list_depth > 0) st->list_depth--;
786 ensure_newline(out);
787 break;
788 }
789 if (strcmp(nm, "li") == 0) { ensure_newline(out); break; }
790 if (strcmp(nm, "a") == 0) break; /* consumed at open */
791 if (strcmp(nm, "strong") == 0 || strcmp(nm, "b") == 0) {
792 buf_add(out, "**");
793 break;
794 }
795 if (strcmp(nm, "em") == 0 || strcmp(nm, "i") == 0) {
796 buf_add(out, "*");
797 break;
798 }
799 if (strcmp(nm, "code") == 0) {
800 if (!st->in_pre) buf_add(out, "`");
801 break;
802 }
803 if (strcmp(nm, "p") == 0 || strcmp(nm, "div") == 0 ||
804 strcmp(nm, "section") == 0 || strcmp(nm, "article") == 0 ||
805 strcmp(nm, "main") == 0 || strcmp(nm, "header") == 0 ||
806 strcmp(nm, "figure") == 0 || strcmp(nm, "figcaption") == 0 ||
807 strcmp(nm, "ul") == 0) {
808 ensure_blank_line(out);
809 break;
810 }
811 if (strcmp(nm, "tr") == 0) {
812 st->in_table_row = 0;
813 /* close the row: "| a | b |" */
814 if (st->row_cells) buf_add(out, " |");
815 ensure_newline(out);
816 if (st->first_row && st->row_cells > 0) {
817 int c;
818 for (c = 0; c < st->row_cells; c++)
819 buf_add(out, c ? " | ---" : "| ---");
820 buf_add(out, " |");
821 ensure_newline(out);
822 st->first_row = 0;
823 }
824 break;
825 }
826 if (strcmp(nm, "table") == 0) {
827 ensure_blank_line(out);
828 break;
829 }
830 break;
831 }
832 }
833 }
834}
835
836/* ------------------------------------------------------------------ */
837/* Public entry points */
838/* ------------------------------------------------------------------ */
839
840char *fx_html_to_markdown(const char *html, size_t len, size_t *out_len)
841{
842 toks t;
843 buf_t out;
844 render_state st;
845
846 memset(&st, 0, sizeof st);
847 buf_init(&out);
848 st.out = &out;
849 tokenize(html, len, &t);
850 render_tokens(&t, 0, t.n, &st);
851 toks_free(&t);
852
853 /* tidy: strip trailing whitespace runs and clamp to a single trailing \n */
854 if (out.p) {
855 while (out.n && (unsigned char)out.p[out.n - 1] <= ' ') out.n--;
856 if (out.n) { out.p[out.n] = '\0'; buf_add(&out, "\n"); }
857 else { out.p[0] = '\0'; }
858 }
859 if (out_len) *out_len = out.n;
860 if (!out.p) {
861 char *e = (char *)sx_malloc(1);
862 e[0] = '\0';
863 return e;
864 }
865 return out.p;
866}
867
868char *fx_html_title(const char *html, size_t len, size_t *out_len)
869{
870 toks t;
871 size_t i;
872 char *result = NULL;
873
874 tokenize(html, len, &t);
875 for (i = 0; i < t.n; i++) {
876 if (t.v[i].kind == TOK_OPEN && strcmp(t.v[i].name, "meta") == 0) {
877 char prop[64] = "", name[64] = "", content[512] = "";
878 attr_get(t.v[i].attrs, "property", prop, sizeof prop);
879 if (!prop[0]) attr_get(t.v[i].attrs, "name", name, sizeof name);
880 if ((prop[0] && sx_strcasecmp(prop, "og:title") == 0) ||
881 (name[0] && sx_strcasecmp(name, "og:title") == 0)) {
882 if (attr_get(t.v[i].attrs, "content", content, sizeof content) &&
883 content[0]) {
884 buf_t b;
885 buf_init(&b);
886 collapse_ws_append(&b, content);
887 if (b.n) {
888 b.p[b.n] = '\0';
889 result = b.p;
890 break;
891 }
892 free(b.p);
893 }
894 }
895 }
896 }
897 if (!result) {
898 for (i = 0; i < t.n; i++) {
899 if (t.v[i].kind == TOK_OPEN && strcmp(t.v[i].name, "title") == 0) {
900 size_t j;
901 for (j = i + 1; j < t.n && t.v[j].kind != TOK_CLOSE; j++) {
902 if (t.v[j].kind == TOK_TEXT && t.v[j].text &&
903 t.v[j].text[0]) {
904 buf_t b;
905 buf_init(&b);
906 collapse_ws_append(&b, t.v[j].text);
907 if (b.n) { b.p[b.n] = '\0'; result = b.p; }
908 else free(b.p);
909 break;
910 }
911 }
912 break;
913 }
914 }
915 }
916 toks_free(&t);
917 if (out_len) *out_len = result ? strlen(result) : 0;
918 return result;
919}
920
921/* word-normalised comparison (letters+digits runs, lowercased) */
922static size_t norm_words(const char *s, size_t n, char *out, size_t outsz)
923{
924 size_t o = 0, i = 0;
925 int sep = 1;
926 for (i = 0; i < n; i++) {
927 char c = s[i];
928 if (isalnum((unsigned char)c)) {
929 if (o + 2 >= outsz) break;
930 if (sep && o) out[o++] = ' ';
931 sep = 0;
932 out[o++] = (char)tolower((unsigned char)c);
933 } else {
934 sep = 1;
935 }
936 }
937 out[o] = '\0';
938 return o;
939}
940
941int fx_md_starts_with_title(const char *md, size_t md_len,
942 const char *title, size_t title_len)
943{
944 char tw[1024], mw[4096];
945 size_t tl, ml, k;
946
947 if (!md || !title || !title_len) return 0;
948 tl = norm_words(title, title_len, tw, sizeof tw);
949 if (!tl) return 0;
950 if (md_len > 800) md_len = 800; /* the heading is near the top */
951 ml = norm_words(md, md_len, mw, sizeof mw);
952 if (!ml) return 0;
953 if (ml < tl) return 0;
954 for (k = 0; k < tl; k++) if (mw[k] != tw[k]) return 0;
955 /* the next char must be a word boundary (space or end) */
956 if (ml > tl && mw[tl] != ' ') return 0;
957 return 1;
958}