Skip to content
pi-c Documentation
Login

Documentation

/* HTML to readable markdown-ish text (htmltext.h). One pass over the bytes: tags are told apart
 * from text, a handful of elements set the line structure, and everything else is its content.
 * Output is built with a pending break and a pending space, so runs of white space and of blank
 * lines collapse as a reader would see them. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "htmltext.h"

typedef struct {
    char *p;
    size_t len, cap;
    int oom;
} ht_hb;

static void ht_hb_add(ht_hb *b, const char *s, size_t n) {
    if (b->oom || n == 0) {
        return;
    }
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 4096;
        char *q;
        while (cap < b->len + n + 1) {
            cap *= 2;
        }
        q = realloc(b->p, cap);
        if (!q) {
            b->oom = 1;
            return;
        }
        b->p = q;
        b->cap = cap;
    }
    memcpy(b->p + b->len, s, n);
    b->len += n;
    b->p[b->len] = '\0';
}

static void ht_hb_adds(ht_hb *b, const char *s) { ht_hb_add(b, s, strlen(s)); }

#define HT_MAX_DEPTH 64

typedef struct {
    ht_hb out;
    int want_nl;    /* line breaks owed before the next text: 0, 1 or 2 */
    int want_space; /* a space owed before the next text on this line */
    int bol;        /* the output is at the start of a line */
    int quote;      /* blockquote depth */
    int ndepth;     /* list depth */
    char kind[HT_MAX_DEPTH]; /* 'u' or 'o' for each open list */
    int count[HT_MAX_DEPTH];
    char marker[16]; /* the list marker owed to the next line, "" when none */
    int marker_indent;
    int cell;    /* cells already written in this table row */
    int in_pre;  /* inside <pre> */
    ht_hb title;
    pic_html_resolve_fn resolve;
    void *ctx;
} ht_conv;

static void ht_block(ht_conv *c, int n) {
    if (n > c->want_nl) {
        c->want_nl = n;
    }
    c->want_space = 0;
}

/* Writes the owed breaks, the quote and list prefixes and space, then S. */
static void ht_put(ht_conv *c, const char *s, size_t n) {
    if (n == 0) {
        return;
    }
    if (c->out.len == 0) {
        c->want_nl = 0;
        c->want_space = 0;
    }
    if (c->want_nl > 0 && c->out.len > 0) {
        for (int i = 0; i < c->want_nl; i++) {
            ht_hb_add(&c->out, "\n", 1);
        }
        c->bol = 1;
    }
    c->want_nl = 0;
    if (c->bol) {
        for (int i = 0; i < c->quote; i++) {
            ht_hb_adds(&c->out, "> ");
        }
        if (c->marker[0]) {
            for (int i = 0; i < c->marker_indent; i++) {
                ht_hb_adds(&c->out, "  ");
            }
            ht_hb_adds(&c->out, c->marker);
            c->marker[0] = '\0';
        } else if (c->ndepth > 0 && !c->in_pre) {
            for (int i = 0; i < c->ndepth; i++) {
                ht_hb_adds(&c->out, "  ");
            }
        }
    } else if (c->want_space) {
        ht_hb_adds(&c->out, " ");
    }
    c->want_space = 0;
    c->bol = 0;
    ht_hb_add(&c->out, s, n);
}

static void ht_puts_(ht_conv *c, const char *s) { ht_put(c, s, strlen(s)); }

/* ---- ht_entities ---------------------------------------------------------------------------- */

static size_t ht_utf8_put(unsigned long cp, char *out) {
    if (cp == 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
        cp = 0xfffd;
    }
    if (cp < 0x80) {
        out[0] = (char)cp;
        return 1;
    }
    if (cp < 0x800) {
        out[0] = (char)(0xc0 | (cp >> 6));
        out[1] = (char)(0x80 | (cp & 0x3f));
        return 2;
    }
    if (cp < 0x10000) {
        out[0] = (char)(0xe0 | (cp >> 12));
        out[1] = (char)(0x80 | ((cp >> 6) & 0x3f));
        out[2] = (char)(0x80 | (cp & 0x3f));
        return 3;
    }
    out[0] = (char)(0xf0 | (cp >> 18));
    out[1] = (char)(0x80 | ((cp >> 12) & 0x3f));
    out[2] = (char)(0x80 | ((cp >> 6) & 0x3f));
    out[3] = (char)(0x80 | (cp & 0x3f));
    return 4;
}

static const struct {
    const char *name;
    unsigned long cp;
} ht_entities[] = {
    {"amp", '&'},      {"lt", '<'},       {"gt", '>'},        {"quot", '"'},     {"apos", '\''},    {"nbsp", 0xa0},
    {"copy", 0xa9},    {"reg", 0xae},     {"trade", 0x2122},  {"mdash", 0x2014}, {"ndash", 0x2013}, {"hellip", 0x2026},
    {"lsquo", 0x2018}, {"rsquo", 0x2019}, {"ldquo", 0x201c},  {"rdquo", 0x201d}, {"laquo", 0xab},    {"raquo", 0xbb},
    {"bull", 0x2022},  {"middot", 0xb7},  {"times", 0xd7},    {"euro", 0x20ac},  {"pound", 0xa3},    {"yen", 0xa5},
    {"cent", 0xa2},    {"sect", 0xa7},    {"deg", 0xb0},      {"plusmn", 0xb1},  {"micro", 0xb5},    {"para", 0xb6},
    {"larr", 0x2190},  {"rarr", 0x2192},  {"uarr", 0x2191},   {"darr", 0x2193},  {"eacute", 0xe9},  {"egrave", 0xe8},
    {"agrave", 0xe0},  {"aacute", 0xe1},  {"ccedil", 0xe7},   {"ntilde", 0xf1},  {"uuml", 0xfc},    {"ouml", 0xf6},
    {"auml", 0xe4},    {"szlig", 0xdf},   {"iacute", 0xed},   {"oacute", 0xf3},  {"uacute", 0xfa},  {"ecirc", 0xea},
};

/* The ht_entity at S (which starts with '&'), written to OUT; its length in S, or 0 when it is not
 * one (the '&' is then text). */
static size_t ht_entity(const char *s, size_t avail, char *out, size_t *outn) {
    size_t i = 1;
    if (avail > 2 && s[1] == '#') {
        unsigned long cp = 0;
        int hex = s[2] == 'x' || s[2] == 'X';
        size_t start = hex ? 3 : 2;
        for (i = start; i < avail && i < start + 8 && (hex ? isxdigit((unsigned char)s[i]) : isdigit((unsigned char)s[i])); i++) {
            cp = cp * (hex ? 16 : 10) + (unsigned long)(isdigit((unsigned char)s[i]) ? s[i] - '0' : (tolower((unsigned char)s[i]) - 'a' + 10));
        }
        if (i == start) {
            return 0;
        }
        if (i < avail && s[i] == ';') {
            i++;
        }
        *outn = ht_utf8_put(cp, out);
        return i;
    }
    while (i < avail && i < 10 && isalnum((unsigned char)s[i])) {
        i++;
    }
    if (i == 1 || i >= avail || s[i] != ';') {
        return 0;
    }
    for (size_t k = 0; k < sizeof ht_entities / sizeof ht_entities[0]; k++) {
        if (strlen(ht_entities[k].name) == i - 1 && strncmp(ht_entities[k].name, s + 1, i - 1) == 0) {
            *outn = ht_utf8_put(ht_entities[k].cp, out);
            return i + 1;
        }
    }
    return 0;
}

/* S decoded (ht_entities) into a new string; NULL when out of memory. */
static char *ht_decode(const char *s, size_t n) {
    char *out = malloc(n + 1), buf[8];
    size_t o = 0;
    if (!out) {
        return NULL;
    }
    for (size_t i = 0; i < n;) {
        size_t took, k;
        if (s[i] == '&' && (took = ht_entity(s + i, n - i, buf, &k)) > 0) {
            memcpy(out + o, buf, k); /* an ht_entity is always longer than what it stands for */
            o += k;
            i += took;
        } else {
            out[o++] = s[i++];
        }
    }
    out[o] = '\0';
    return out;
}

/* ---- tags -------------------------------------------------------------------------------- */

typedef struct {
    char name[16];
    int closing, selfclose;
    const char *attrs; /* after the name, up to the closing '>' */
    size_t attrs_len;
} ht_tag;

/* The value of attribute NAME in the ht_tag, decoded (malloc'd), or NULL. */
static char *ht_attr(const ht_tag *t, const char *name) {
    const char *p = t->attrs, *end = t->attrs + t->attrs_len;
    size_t nl = strlen(name);
    while (p < end) {
        const char *ns, *ne, *vs = NULL, *ve = NULL;
        while (p < end && (isspace((unsigned char)*p) || *p == '/')) {
            p++;
        }
        ns = p;
        while (p < end && !isspace((unsigned char)*p) && *p != '=' && *p != '/' && *p != '>') {
            p++;
        }
        ne = p;
        while (p < end && isspace((unsigned char)*p)) {
            p++;
        }
        if (p < end && *p == '=') {
            p++;
            while (p < end && isspace((unsigned char)*p)) {
                p++;
            }
            if (p < end && (*p == '"' || *p == '\'')) {
                char q = *p++;
                vs = p;
                while (p < end && *p != q) {
                    p++;
                }
                ve = p;
                if (p < end) {
                    p++;
                }
            } else {
                vs = p;
                while (p < end && !isspace((unsigned char)*p)) {
                    p++;
                }
                ve = p;
            }
        }
        if (ne > ns && (size_t)(ne - ns) == nl && strncasecmp(ns, name, nl) == 0) {
            return vs ? ht_decode(vs, (size_t)(ve - vs)) : strdup("");
        }
        if (ne == ns) {
            p++;
        }
    }
    return NULL;
}

/* The end of the ht_tag starting at S ('<'): the index of its '>' (quotes respected), or n. */
static size_t ht_tag_end(const char *s, size_t n) {
    char q = 0;
    for (size_t i = 1; i < n; i++) {
        if (q) {
            q = s[i] == q ? 0 : q;
        } else if (s[i] == '"' || s[i] == '\'') {
            q = s[i];
        } else if (s[i] == '>') {
            return i;
        }
    }
    return n;
}

static int ht_one_of(const char *name, const char *const *list) {
    for (; *list; list++) {
        if (strcmp(name, *list) == 0) {
            return 1;
        }
    }
    return 0;
}

static const char *const ht_raw_text[] = {"script", "style", NULL};
/* Elements ht_dropped with all they hold. */
static const char *const ht_dropped[] = {"script", "style", "noscript", "template", "svg", "nav", "iframe", "object", "embed",
                                      "canvas", "select", "button", "dialog", NULL};
static const char *const ht_blocks[] = {"p",       "div",     "section", "article", "main",     "header", "footer", "aside",
                                     "address", "figure",  "figcaption", "details", "summary", "form",   "fieldset", "dl",
                                     "dt",      "dd",      "center",  "body",    "html",     NULL};

/* Index just past the close ht_tag matching an open one of NAME at S[from], counting nesting;
 * n when there is none. For raw-text elements nesting is not counted. *INNER is where the
 * content ends (the '<' of the close ht_tag), n when there is none. */
static size_t ht_skip_element(const char *s, size_t n, size_t from, const char *name, size_t *inner) {
    size_t nl = strlen(name);
    int depth = 1, raw = ht_one_of(name, ht_raw_text);
    for (size_t i = from; i < n; i++) {
        if (s[i] != '<') {
            continue;
        }
        if (i + 1 < n && s[i + 1] == '!' && !raw) {
            if (i + 3 < n && strncmp(s + i, "<!--", 4) == 0) {
                const char *e = strstr(s + i + 4, "-->");
                if (!e) {
                    return n;
                }
                i = (size_t)(e - s) + 2;
            }
            continue;
        }
        {
            int closing = i + 1 < n && s[i + 1] == '/';
            size_t at = i + 1 + (size_t)closing;
            if (at + nl <= n && strncasecmp(s + at, name, nl) == 0 &&
                (at + nl == n || !(isalnum((unsigned char)s[at + nl]) || s[at + nl] == '-'))) {
                size_t e = ht_tag_end(s + i, n - i);
                if (closing) {
                    if (--depth == 0 || raw) {
                        if (inner) {
                            *inner = i;
                        }
                        return e >= n - i ? n : i + e + 1;
                    }
                } else if (!raw && !(e > 1 && s[i + e - 1] == '/')) {
                    depth++;
                }
            }
        }
    }
    if (inner) {
        *inner = n;
    }
    return n;
}

static void ht_list_open(ht_conv *c, char kind, int start) {
    if (c->ndepth < HT_MAX_DEPTH) {
        c->kind[c->ndepth] = kind;
        c->count[c->ndepth] = start;
        c->ndepth++;
    }
    ht_block(c, c->ndepth == 1 ? 2 : 1);
}

static void ht_list_close(ht_conv *c) {
    if (c->ndepth > 0) {
        c->ndepth--;
    }
    c->marker[0] = '\0';
    ht_block(c, c->ndepth == 0 ? 2 : 1);
}

static void ht_li_open(ht_conv *c) {
    ht_block(c, 1);
    if (c->ndepth == 0) {
        (void)snprintf(c->marker, sizeof c->marker, "- ");
        c->marker_indent = 0;
        return;
    }
    if (c->kind[c->ndepth - 1] == 'o') {
        (void)snprintf(c->marker, sizeof c->marker, "%d. ", c->count[c->ndepth - 1]++);
    } else {
        (void)snprintf(c->marker, sizeof c->marker, "- ");
    }
    c->marker_indent = c->ndepth - 1;
}

/* Lines of S, each on a line of its own (white space kept), through ht_put so prefixes apply. */
static void ht_put_lines(ht_conv *c, const char *s, size_t n) {
    int blanks = 0, first = 1;
    for (size_t at = 0; at <= n;) {
        const char *nl = memchr(s + at, '\n', n - at);
        size_t ll = nl ? (size_t)(nl - (s + at)) : n - at;
        if (ll == 0) {
            blanks++;
        } else {
            if (!first) {
                c->want_nl = 1 + blanks;
            }
            ht_put(c, s + at, ll);
            blanks = 0;
            first = 0;
        }
        at += ll + 1;
    }
}

static char *ht_dup_n(const char *s, size_t n) {
    char *d = malloc(n + 1);
    if (d) {
        memcpy(d, s, n);
        d[n] = '\0';
    }
    return d;
}

/* The ht_tag at S[i] ('<', closing at S[i+e]): its name, lowercased, and its attributes. */
static void ht_tag_at(const char *s, size_t i, size_t e, ht_tag *t) {
    size_t k = 0;
    memset(t, 0, sizeof *t);
    t->closing = s[i + 1] == '/';
    for (size_t j = i + 1 + (size_t)t->closing; j < i + e && (isalnum((unsigned char)s[j]) || s[j] == '-') && k < sizeof t->name - 1; j++) {
        t->name[k++] = (char)tolower((unsigned char)s[j]);
    }
    t->attrs = s + i + 1 + (size_t)t->closing + k;
    t->attrs_len = i + e > (size_t)(t->attrs - s) ? i + e - (size_t)(t->attrs - s) : 0;
    t->selfclose = e > 1 && s[i + e - 1] == '/';
}

/* <pre>, its text as it is in a fence; the index past </pre>. */
static size_t ht_do_pre(ht_conv *c, const char *s, size_t n, size_t from) {
    size_t inner, end = ht_skip_element(s, n, from, "pre", &inner);
    ht_hb raw = {0};
    char *lang = NULL;
    size_t skip = 0;
    for (size_t i = from; i < inner;) {
        if (s[i] == '<' && i + 1 < inner && (isalpha((unsigned char)s[i + 1]) || s[i + 1] == '/')) {
            size_t e = ht_tag_end(s + i, inner - i);
            ht_tag t;
            ht_tag_at(s, i, e, &t);
            if (strcmp(t.name, "br") == 0) {
                ht_hb_adds(&raw, "\n");
            } else if (strcmp(t.name, "code") == 0 && !t.closing && !lang) {
                char *cl = ht_attr(&t, "class"), *m;
                m = cl ? strstr(cl, "language-") : NULL;
                m = m ? m + 9 : (cl && strstr(cl, "lang-") ? strstr(cl, "lang-") + 5 : NULL);
                if (m) {
                    lang = ht_dup_n(m, strspn(m, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_#"));
                }
                free(cl);
            }
            i += e + 1 > inner - i ? inner - i : e + 1;
            continue;
        }
        if (s[i] == '&') {
            char buf[8];
            size_t k, took = ht_entity(s + i, inner - i, buf, &k);
            if (took) {
                ht_hb_add(&raw, buf, k);
                i += took;
                continue;
            }
        }
        if (s[i] != '\r') {
            ht_hb_add(&raw, s + i, 1);
        }
        i++;
    }
    while (raw.p && raw.p[skip] == '\n') {
        skip++;
    }
    while (raw.len > skip && (raw.p[raw.len - 1] == '\n' || raw.p[raw.len - 1] == ' ')) {
        raw.p[--raw.len] = '\0';
    }
    if (raw.len > skip) {
        ht_block(c, 2);
        c->in_pre = 1;
        ht_puts_(c, "```");
        if (lang && *lang) {
            ht_puts_(c, lang);
        }
        c->want_nl = 1;
        ht_put_lines(c, raw.p + skip, raw.len - skip);
        c->want_nl = 1;
        ht_puts_(c, "```");
        c->in_pre = 0;
        ht_block(c, 2);
    }
    free(raw.p);
    free(lang);
    return end;
}

/* The label of <a>...</a>: the text of what is inside, its images by their alt text, white space
 * collapsed (malloc'd). */
static char *ht_anchor_label(const char *s, size_t from, size_t stop) {
    ht_hb text = {0};
    size_t o = 0;
    int sp = 1;
    char *w;
    for (size_t i = from; i < stop;) {
        if (s[i] == '<' && i + 1 < stop && (isalpha((unsigned char)s[i + 1]) || s[i + 1] == '/' || s[i + 1] == '!')) {
            size_t e;
            ht_tag t;
            if (i + 3 < stop && strncmp(s + i, "<!--", 4) == 0) {
                const char *ce = strstr(s + i + 4, "-->");
                i = ce && (size_t)(ce - s) + 3 <= stop ? (size_t)(ce - s) + 3 : stop;
                continue;
            }
            e = ht_tag_end(s + i, stop - i);
            ht_tag_at(s, i, e, &t);
            if (strcmp(t.name, "img") == 0) {
                char *alt = ht_attr(&t, "alt");
                if (alt && *alt) {
                    ht_hb_adds(&text, " ");
                    ht_hb_adds(&text, alt);
                }
                free(alt);
            } else {
                ht_hb_adds(&text, " ");
            }
            i += e + 1 > stop - i ? stop - i : e + 1;
            continue;
        }
        if (s[i] == '&') {
            char buf[8];
            size_t k, took = ht_entity(s + i, stop - i, buf, &k);
            if (took) {
                ht_hb_add(&text, buf, k);
                i += took;
                continue;
            }
        }
        ht_hb_add(&text, s + i, 1);
        i++;
    }
    w = text.p;
    for (size_t i = 0; w && i < text.len; i++) {
        if (isspace((unsigned char)w[i]) || ((unsigned char)w[i] == 0xc2 && i + 1 < text.len && (unsigned char)w[i + 1] == 0xa0)) {
            i += isspace((unsigned char)w[i]) ? 0 : 1;
            if (!sp) {
                w[o++] = ' ';
            }
            sp = 1;
        } else {
            w[o++] = w[i];
            sp = 0;
        }
    }
    if (w) {
        if (o > 0 && w[o - 1] == ' ') {
            o--;
        }
        w[o] = '\0';
    }
    return w ? w : ht_dup_n("", 0);
}

/* <a>: written as one unit, [label](link). The index past </a>, or FROM when it is never closed
 * (the ht_tag is then ht_dropped and the page goes on). */
static size_t ht_do_anchor(ht_conv *c, const char *s, size_t n, size_t from, const ht_tag *t) {
    size_t inner, end = ht_skip_element(s, n, from, "a", &inner);
    char *href, *label;
    if (inner >= n) {
        return from;
    }
    href = ht_attr(t, "href");
    label = ht_anchor_label(s, from, inner);
    if (label && *label) {
        if (href && *href && href[0] != '#' && strncasecmp(href, "javascript:", 11) != 0 && strncasecmp(href, "mailto:", 7) != 0 &&
            strncasecmp(href, "tel:", 4) != 0 && strncasecmp(href, "data:", 5) != 0) {
            char *abs = c->resolve ? c->resolve(c->ctx, href) : NULL;
            ht_puts_(c, "[");
            c->want_space = 0;
            ht_puts_(c, label);
            ht_hb_adds(&c->out, "](");
            ht_hb_adds(&c->out, abs ? abs : href);
            ht_hb_adds(&c->out, ")");
            free(abs);
        } else {
            ht_puts_(c, label);
        }
    }
    free(label);
    free(href);
    return end;
}

/* An inline ht_mark: before the next word it opens, glued to it; as a close it follows the last
 * word, and any space owed stays owed. */
static void ht_mark(ht_conv *c, const char *m, int closing) {
    if (closing) {
        int sp = c->want_space;
        c->want_space = 0;
        ht_hb_adds(&c->out, m);
        c->want_space = sp;
    } else {
        ht_puts_(c, m);
        c->want_space = 0;
    }
}

/* ---- the pass ---------------------------------------------------------------------------- */

static void ht_text_run(ht_conv *c, const char *s, size_t n) {
    size_t i = 0;
    while (i < n) {
        size_t j;
        ht_hb word = {0};
        if (isspace((unsigned char)s[i])) {
            while (i < n && isspace((unsigned char)s[i])) {
                i++;
            }
            if (!c->bol && c->out.len > 0) {
                c->want_space = 1;
            }
            continue;
        }
        for (j = i; j < n && !isspace((unsigned char)s[j]);) {
            char buf[8];
            size_t k, took;
            if (s[j] == '&' && (took = ht_entity(s + j, n - j, buf, &k)) > 0) {
                if (k == 2 && (unsigned char)buf[0] == 0xc2 && (unsigned char)buf[1] == 0xa0) {
                    ht_hb_adds(&word, " "); /* a no-break space is a word break here */
                } else {
                    ht_hb_add(&word, buf, k);
                }
                j += took;
            } else {
                ht_hb_add(&word, s + j, 1);
                j++;
            }
        }
        if (word.p) {
            size_t from = 0;
            while (from < word.len && word.p[from] == ' ') {
                from++;
                if (!c->bol) {
                    c->want_space = 1;
                }
            }
            if (word.len > from) {
                ht_put(c, word.p + from, word.len - from);
            }
        }
        free(word.p);
        i = j;
    }
}

char *pic_html_to_text(const char *s, size_t n, pic_html_resolve_fn resolve, void *ctx) {
    ht_conv c;
    size_t i = 0;
    int in_title = 0;
    ht_hb res = {0};
    memset(&c, 0, sizeof c);
    c.resolve = resolve;
    c.ctx = ctx;
    c.bol = 1;
    while (i < n && !c.out.oom && !c.title.oom) {
        const char *lt = memchr(s + i, '<', n - i);
        size_t textn = lt ? (size_t)(lt - (s + i)) : n - i, e;
        ht_tag t;
        if (textn > 0) {
            if (in_title) {
                ht_hb_add(&c.title, s + i, textn);
            } else {
                ht_text_run(&c, s + i, textn);
            }
            i += textn;
        }
        if (i >= n) {
            break;
        }
        /* s[i] is '<' */
        if (i + 1 >= n || !(isalpha((unsigned char)s[i + 1]) || s[i + 1] == '/' || s[i + 1] == '!' || s[i + 1] == '?')) {
            if (in_title) {
                ht_hb_add(&c.title, "&lt;", 4);
            } else {
                ht_text_run(&c, "&lt;", 4);
            }
            i++;
            continue;
        }
        if (s[i + 1] == '!' || s[i + 1] == '?') {
            if (i + 3 < n && strncmp(s + i, "<!--", 4) == 0) {
                const char *ce = strstr(s + i + 4, "-->");
                i = ce ? (size_t)(ce - s) + 3 : n;
            } else if (i + 8 < n && strncmp(s + i, "<![CDATA[", 9) == 0) {
                const char *ce = strstr(s + i + 9, "]]>");
                size_t stop = ce ? (size_t)(ce - s) : n;
                ht_text_run(&c, s + i + 9, stop - i - 9);
                i = ce ? stop + 3 : n;
            } else {
                i += ht_tag_end(s + i, n - i) + 1;
            }
            continue;
        }
        e = ht_tag_end(s + i, n - i);
        ht_tag_at(s, i, e, &t);
        i += e + 1 > n - i ? n - i : e + 1;
        if (t.name[0] == '\0') {
            continue;
        }
        if (strcmp(t.name, "title") == 0) {
            in_title = !t.closing;
            continue;
        }
        in_title = 0;
        if (ht_one_of(t.name, ht_dropped)) {
            if (!t.closing && !t.selfclose) {
                i = ht_skip_element(s, n, i, t.name, NULL);
            }
            continue;
        }
        if (t.closing && (strcmp(t.name, "pre") == 0 || strcmp(t.name, "a") == 0)) {
            continue;
        }
        if (strcmp(t.name, "pre") == 0) {
            i = ht_do_pre(&c, s, n, i);
        } else if (strcmp(t.name, "a") == 0) {
            i = ht_do_anchor(&c, s, n, i, &t);
        } else if (t.name[0] == 'h' && t.name[1] >= '1' && t.name[1] <= '6' && t.name[2] == '\0') {
            ht_block(&c, 2);
            if (t.closing) {
                c.marker[0] = '\0';
            } else {
                memset(c.marker, '#', (size_t)(t.name[1] - '0'));
                c.marker[t.name[1] - '0'] = ' ';
                c.marker[t.name[1] - '0' + 1] = '\0';
                c.marker_indent = 0;
            }
        } else if (strcmp(t.name, "br") == 0) {
            ht_block(&c, 1);
        } else if (strcmp(t.name, "hr") == 0) {
            ht_block(&c, 2);
            ht_puts_(&c, "---");
            ht_block(&c, 2);
        } else if (strcmp(t.name, "p") == 0 || strcmp(t.name, "table") == 0 || strcmp(t.name, "caption") == 0) {
            ht_block(&c, 2);
        } else if (ht_one_of(t.name, ht_blocks)) {
            ht_block(&c, 1);
        } else if (strcmp(t.name, "ul") == 0 || strcmp(t.name, "ol") == 0) {
            if (t.closing) {
                ht_list_close(&c);
            } else {
                char *st = ht_attr(&t, "start");
                ht_list_open(&c, t.name[0] == 'o' ? 'o' : 'u', st ? atoi(st) : 1);
                free(st);
            }
        } else if (strcmp(t.name, "li") == 0) {
            if (!t.closing) {
                ht_li_open(&c);
            }
        } else if (strcmp(t.name, "blockquote") == 0) {
            ht_block(&c, 2);
            c.quote += t.closing ? (c.quote > 0 ? -1 : 0) : 1;
        } else if (strcmp(t.name, "tr") == 0) {
            ht_block(&c, 1);
            c.cell = 0;
        } else if (strcmp(t.name, "td") == 0 || strcmp(t.name, "th") == 0) {
            if (!t.closing && c.cell++ > 0 && !c.bol) {
                c.want_space = 1;
                ht_puts_(&c, "|");
                c.want_space = 1;
            }
        } else if (strcmp(t.name, "strong") == 0 || strcmp(t.name, "b") == 0) {
            ht_mark(&c, "**", t.closing);
        } else if (strcmp(t.name, "em") == 0 || strcmp(t.name, "i") == 0) {
            ht_mark(&c, "*", t.closing);
        } else if (strcmp(t.name, "code") == 0 || strcmp(t.name, "kbd") == 0 || strcmp(t.name, "samp") == 0) {
            ht_mark(&c, "`", t.closing);
        } else if (strcmp(t.name, "img") == 0 && !t.closing) {
            char *alt = ht_attr(&t, "alt"), *src = ht_attr(&t, "src");
            if (alt && *alt) {
                int link = src && *src && strncasecmp(src, "data:", 5) != 0;
                char *abs = link && c.resolve ? c.resolve(c.ctx, src) : NULL;
                ht_puts_(&c, "![");
                c.want_space = 0;
                ht_hb_adds(&c.out, alt);
                ht_hb_adds(&c.out, "]");
                if (link) {
                    ht_hb_adds(&c.out, "(");
                    ht_hb_adds(&c.out, abs ? abs : src);
                    ht_hb_adds(&c.out, ")");
                }
                free(abs);
            }
            free(alt);
            free(src);
        }
    }
    if (c.out.oom || c.title.oom) {
        free(c.out.p);
        free(c.title.p);
        return NULL;
    }
    if (c.title.p) {
        char *t = ht_decode(c.title.p, c.title.len);
        ht_hb tt = {0};
        int sp = 1;
        for (const char *q = t; q && *q; q++) {
            if (isspace((unsigned char)*q)) {
                sp = 1;
            } else {
                if (sp && tt.len > 0) {
                    ht_hb_adds(&tt, " ");
                }
                ht_hb_add(&tt, q, 1);
                sp = 0;
            }
        }
        if (tt.len > 0) {
            ht_hb_adds(&res, "Title: ");
            ht_hb_add(&res, tt.p, tt.len);
            ht_hb_adds(&res, "\n\n");
        }
        free(tt.p);
        free(t);
    }
    ht_hb_add(&res, c.out.p ? c.out.p : "", c.out.len);
    while (res.len > 0 && (res.p[res.len - 1] == '\n' || res.p[res.len - 1] == ' ')) {
        res.p[--res.len] = '\0';
    }
    free(c.out.p);
    free(c.title.p);
    if (res.oom) {
        free(res.p);
        return NULL;
    }
    return res.p ? res.p : ht_dup_n("", 0);
}