Skip to content
pi-c Artifact [bab909bb57]
Login

Artifact [bab909bb57]

Artifact bab909bb5786b7217e9c91eab33e94012542a2106527ed7680692f71974c3520:


/* Syntax highlighting: one table-driven lexer for the C-like languages plus
 * small line lexers for diff and markdown. See highlight.h. */
#include "tui/highlight.h"

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#define NONE TUI_HL_N

typedef struct {
    char *p;
    size_t n, cap;
    int oom;
    const tui_hl_theme *th;
} out_t;

static void put(out_t *o, const char *s, size_t n)
{
    if (o->oom || n == 0)
        return;
    if (o->n + n + 1 > o->cap) {
        size_t cap = o->cap ? o->cap : 256;
        while (cap < o->n + n + 1)
            cap *= 2;
        char *q = realloc(o->p, cap);
        if (!q) {
            o->oom = 1;
            return;
        }
        o->p = q;
        o->cap = cap;
    }
    memcpy(o->p + o->n, s, n);
    o->n += n;
}

/* Emits s[0..n) in class cls, split at newlines; ESC bytes are dropped. */
static void emit(out_t *o, int cls, const char *s, size_t n)
{
    const char *sgr = (cls < TUI_HL_N && o->th) ? o->th->sgr[cls] : NULL;
    size_t i = 0;
    while (i < n) {
        size_t j = i;
        while (j < n && s[j] != '\n' && s[j] != 0x1b)
            j++;
        if (j > i) {
            if (sgr) {
                put(o, sgr, strlen(sgr));
                put(o, s + i, j - i);
                put(o, "\x1b[0m", 4);
            } else {
                put(o, s + i, j - i);
            }
        }
        if (j < n && s[j] == '\n')
            put(o, "\n", 1);
        i = j < n ? j + 1 : j;
    }
}

typedef struct {
    const char *kw;      /* space-separated keywords */
    const char *types;   /* space-separated builtin type names */
    const char *lit;     /* space-separated literals */
    const char *lc1;     /* line comment starters */
    const char *lc2;
    const char *bc_open; /* block comment, or NULL */
    const char *bc_close;
    const char *quotes;  /* string delimiters */
    int icase;           /* keywords case-insensitive */
    int preproc;         /* '#word' at line start is a keyword */
    int dollar;          /* $var / ${var} are variables */
    int triple;          /* python """ and ''' */
    int keys;            /* "key": / key: is a variable (json, yaml) */
    int dash_ident;      /* '-' and '.' continue identifiers (yaml) */
    int lifetimes;       /* rust 'a */
} lang_t;

static const lang_t L_GENERIC = {.quotes = "\"'`", .lc1 = "//", .lc2 = "#", .bc_open = "/*", .bc_close = "*/"};

static const lang_t L_C = {
    .kw = "if else for while do switch case default break continue return goto sizeof typedef struct union "
          "enum static extern const volatile inline register restrict auto class namespace template typename "
          "public private protected virtual override final new delete this using try catch throw operator "
          "constexpr noexcept nullptr explicit friend mutable static_assert _Static_assert _Alignas _Alignof "
          "_Generic decltype",
    .types = "int char short long float double void unsigned signed bool size_t ssize_t uint8_t uint16_t uint32_t "
             "uint64_t int8_t int16_t int32_t int64_t uintptr_t intptr_t ptrdiff_t FILE _Bool wchar_t "
             "char8_t char16_t char32_t",
    .lit = "true false NULL nullptr",
    .lc1 = "//", .bc_open = "/*", .bc_close = "*/", .quotes = "\"'", .preproc = 1};

static const lang_t L_SH = {
    .kw = "if then else elif fi for while until do done case esac in function select time return break "
          "continue exit export local readonly declare unset source alias set shift trap eval exec cd echo "
          "printf test read",
    .lit = "true false", .lc1 = "#", .quotes = "\"'`", .dollar = 1};

static const lang_t L_PY = {
    .kw = "and as assert async await break class continue def del elif else except finally for from global "
          "if import in is lambda nonlocal not or pass raise return try while with yield match case self cls "
          "print",
    .types = "int str float bool list dict set tuple bytes object type complex frozenset bytearray",
    .lit = "True False None", .lc1 = "#", .quotes = "\"'", .triple = 1};

static const lang_t L_JS = {
    .kw = "break case catch class const continue debugger default delete do else export extends finally for "
          "function if import in instanceof new return super switch this throw try typeof var let void while "
          "with yield async await of static get set from as interface type enum implements namespace declare "
          "abstract readonly public private protected keyof infer satisfies",
    .types = "string number boolean any unknown never object symbol bigint void Promise Array Map Set Record "
             "Partial Readonly",
    .lit = "true false null undefined NaN Infinity", .lc1 = "//", .bc_open = "/*", .bc_close = "*/",
    .quotes = "\"'`"};

static const lang_t L_GO = {
    .kw = "break case chan const continue default defer else fallthrough for func go goto if import "
          "interface map package range return select struct switch type var",
    .types = "bool byte complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune string "
             "uint uint8 uint16 uint32 uint64 uintptr any comparable",
    .lit = "true false nil iota", .lc1 = "//", .bc_open = "/*", .bc_close = "*/", .quotes = "\"'`"};

static const lang_t L_RUST = {
    .kw = "as async await break const continue crate dyn else enum extern fn for if impl in let loop match "
          "mod move mut pub ref return self Self static struct super trait type unsafe use where while "
          "macro_rules",
    .types = "bool char str String Vec Option Result Box Rc Arc u8 u16 u32 u64 u128 usize i8 i16 i32 i64 "
             "i128 isize f32 f64",
    .lit = "true false None Some Ok Err", .lc1 = "//", .bc_open = "/*", .bc_close = "*/", .quotes = "\"'",
    .lifetimes = 1};

static const lang_t L_JSON = {.lit = "true false null", .quotes = "\"", .keys = 1};

static const lang_t L_YAML = {.lit = "true false null yes no on off True False Null ~", .lc1 = "#",
                              .quotes = "\"'", .keys = 1, .dash_ident = 1};

static const lang_t L_SQL = {
    .kw = "select from where and or not in is as on join inner left right outer full cross group by order "
          "having limit offset insert into values update set delete create table index view drop alter add "
          "column primary key foreign references unique default check constraint union all distinct case "
          "when then else end exists between like ilike begin commit rollback transaction with returning "
          "using asc desc if cascade truncate explain pragma trigger",
    .types = "int integer bigint smallint text varchar char boolean bool real float double numeric decimal "
             "date time timestamp blob serial uuid json jsonb",
    .lit = "true false null", .lc1 = "--", .bc_open = "/*", .bc_close = "*/", .quotes = "\"'`", .icase = 1};

static int word_in(const char *list, const char *w, size_t n, int icase)
{
    if (!list)
        return 0;
    const char *p = list;
    while (*p) {
        size_t m = 0;
        while (p[m] && p[m] != ' ')
            m++;
        if (m == n) {
            size_t i = 0;
            for (; i < n; i++) {
                char a = p[i], b = w[i];
                if (icase) {
                    a = (char)tolower((unsigned char)a);
                    b = (char)tolower((unsigned char)b);
                }
                if (a != b)
                    break;
            }
            if (i == n)
                return 1;
        }
        p += m;
        while (*p == ' ')
            p++;
    }
    return 0;
}

static int is_id0(unsigned char c)
{
    return isalpha(c) || c == '_' || c >= 0x80;
}

static int is_id(unsigned char c)
{
    return isalnum(c) || c == '_' || c >= 0x80;
}

static int starts(const char *s, size_t n, const char *pre)
{
    size_t m = strlen(pre);
    return m > 0 && n >= m && memcmp(s, pre, m) == 0;
}

/* True when, after optional blanks at s[i..n), the next byte is c. */
static int next_is(const char *s, size_t i, size_t n, char c)
{
    while (i < n && (s[i] == ' ' || s[i] == '\t'))
        i++;
    return i < n && s[i] == c;
}

/* After a ':' (or at end) is a key separator: followed by blank/EOL (yaml) or anything (json). */
static int key_colon(const char *s, size_t i, size_t n, int yaml)
{
    while (i < n && (s[i] == ' ' || s[i] == '\t'))
        i++;
    if (i >= n || s[i] != ':')
        return 0;
    if (!yaml)
        return 1;
    return i + 1 >= n || s[i + 1] == ' ' || s[i + 1] == '\t' || s[i + 1] == '\n' || s[i + 1] == '\r';
}

static void lex(out_t *o, const lang_t *L, const char *s, size_t n)
{
    size_t i = 0;
    int bol = 1; /* only blanks so far on this line */
    while (i < n) {
        unsigned char c = (unsigned char)s[i];
        size_t st = i;
        if (c == '\n') {
            emit(o, NONE, s + i, 1);
            i++;
            bol = 1;
            continue;
        }
        if (c == ' ' || c == '\t' || c == '\r') {
            while (i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r'))
                i++;
            emit(o, NONE, s + st, i - st);
            continue;
        }
        int was_bol = bol;
        bol = 0;
        if (L->bc_open && starts(s + i, n - i, L->bc_open)) {
            i += strlen(L->bc_open);
            size_t cl = strlen(L->bc_close);
            while (i < n && !(n - i >= cl && memcmp(s + i, L->bc_close, cl) == 0))
                i++;
            i = i + cl <= n && i < n ? i + cl : n;
            emit(o, TUI_HL_COMMENT, s + st, i - st);
            continue;
        }
        if ((L->lc1 && starts(s + i, n - i, L->lc1)) || (L->lc2 && starts(s + i, n - i, L->lc2))) {
            if (!(L->keys && L->dash_ident && c == '#' && i > 0 && s[i - 1] != ' ' && s[i - 1] != '\t' &&
                  s[i - 1] != '\n')) {
                while (i < n && s[i] != '\n')
                    i++;
                emit(o, TUI_HL_COMMENT, s + st, i - st);
                continue;
            }
        }
        if (L->preproc && c == '#' && was_bol) {
            i++;
            while (i < n && (s[i] == ' ' || s[i] == '\t'))
                i++;
            while (i < n && is_id((unsigned char)s[i]))
                i++;
            emit(o, TUI_HL_KEYWORD, s + st, i - st);
            continue;
        }
        if (L->dollar && c == '$' && i + 1 < n) {
            i++;
            if (s[i] == '{') {
                while (i < n && s[i] != '}' && s[i] != '\n')
                    i++;
                if (i < n && s[i] == '}')
                    i++;
            } else if (s[i] == '(' ) {
                emit(o, TUI_HL_PUNCT, s + st, 2);
                i++;
                continue;
            } else if (is_id0((unsigned char)s[i])) {
                while (i < n && is_id((unsigned char)s[i]))
                    i++;
            } else {
                i++; /* $?, $1, $$ ... */
            }
            emit(o, TUI_HL_VARIABLE, s + st, i - st);
            continue;
        }
        if (L->quotes && strchr(L->quotes, (char)c)) {
            char q = (char)c;
            if (L->lifetimes && q == '\'' && !(i + 2 < n && (s[i + 1] == '\\' || s[i + 2] == '\''))) {
                i++;
                while (i < n && is_id((unsigned char)s[i]))
                    i++;
                emit(o, TUI_HL_TYPE, s + st, i - st);
                continue;
            }
            int multi = q == '`';
            if (L->triple && n - i >= 3 && s[i + 1] == q && s[i + 2] == q) {
                multi = 1;
                i += 3;
                while (i < n && !(n - i >= 3 && s[i] == q && s[i + 1] == q && s[i + 2] == q))
                    i++;
                i = i < n ? i + 3 : n;
            } else {
                i++;
                while (i < n && s[i] != q && (multi || s[i] != '\n')) {
                    if (s[i] == '\\' && i + 1 < n && (multi || s[i + 1] != '\n') && !(q == '\'' && L == &L_SH))
                        i++;
                    i++;
                }
                if (i < n && s[i] == q)
                    i++;
            }
            int cls = TUI_HL_STRING;
            if (L->keys && key_colon(s, i, n, L == &L_YAML))
                cls = TUI_HL_VARIABLE;
            emit(o, cls, s + st, i - st);
            continue;
        }
        if (isdigit(c) || (c == '.' && i + 1 < n && isdigit((unsigned char)s[i + 1]))) {
            i++;
            while (i < n && (isalnum((unsigned char)s[i]) || s[i] == '_' || s[i] == '.' ||
                             ((s[i] == '+' || s[i] == '-') && (s[i - 1] == 'e' || s[i - 1] == 'E') &&
                              i + 1 < n && isdigit((unsigned char)s[i + 1]) && !(s[st] == '0' && st + 1 < n &&
                              (s[st + 1] == 'x' || s[st + 1] == 'X')))))
                i++;
            emit(o, TUI_HL_NUMBER, s + st, i - st);
            continue;
        }
        if (is_id0(c)) {
            i++;
            while (i < n && (is_id((unsigned char)s[i]) ||
                             (L->dash_ident && (s[i] == '-' || s[i] == '.') && i + 1 < n && is_id((unsigned char)s[i + 1]))))
                i++;
            size_t w = i - st;
            int cls = NONE;
            if (L->keys && key_colon(s, i, n, L == &L_YAML))
                cls = TUI_HL_VARIABLE;
            else if (word_in(L->lit, s + st, w, L->icase))
                cls = TUI_HL_KEYWORD;
            else if (word_in(L->kw, s + st, w, L->icase))
                cls = TUI_HL_KEYWORD;
            else if (word_in(L->types, s + st, w, L->icase))
                cls = TUI_HL_TYPE;
            else if (!L->keys && isupper(c) && w > 1 && !L->dollar && L != &L_SQL)
                cls = TUI_HL_TYPE;
            else if (!L->keys && next_is(s, i, n, '('))
                cls = TUI_HL_FUNCTION;
            emit(o, cls, s + st, w);
            continue;
        }
        i++;
        if (strchr("+-*/%=<>!&|^~?:", (char)c) && c != 0)
            emit(o, TUI_HL_OPERATOR, s + st, 1);
        else if (strchr("()[]{},;.@\\", (char)c) && c != 0)
            emit(o, TUI_HL_PUNCT, s + st, 1);
        else
            emit(o, NONE, s + st, 1);
    }
}

/* Runs fn on each line (without its '\n'), re-emitting the newline. */
static void lines(out_t *o, const char *s, size_t n, void (*fn)(out_t *, const char *, size_t, int *), int *state)
{
    size_t i = 0;
    while (i < n) {
        size_t j = i;
        while (j < n && s[j] != '\n')
            j++;
        fn(o, s + i, j - i, state);
        if (j < n)
            emit(o, NONE, "\n", 1);
        i = j < n ? j + 1 : j;
    }
}

static void diff_line(out_t *o, const char *s, size_t n, int *state)
{
    (void)state;
    int cls = NONE;
    if (starts(s, n, "+++") || starts(s, n, "---") || starts(s, n, "diff ") || starts(s, n, "index ") ||
        starts(s, n, "@@") || starts(s, n, "new file") || starts(s, n, "deleted file") ||
        starts(s, n, "similarity") || starts(s, n, "rename ") || starts(s, n, "\\ "))
        cls = TUI_HL_META;
    else if (n > 0 && s[0] == '+')
        cls = TUI_HL_ADD;
    else if (n > 0 && s[0] == '-')
        cls = TUI_HL_DEL;
    emit(o, cls, s, n);
}

static void md_line(out_t *o, const char *s, size_t n, int *fence)
{
    size_t k = 0;
    while (k < n && k < 3 && s[k] == ' ')
        k++;
    if (n - k >= 3 && (starts(s + k, n - k, "```") || starts(s + k, n - k, "~~~"))) {
        *fence = !*fence;
        emit(o, TUI_HL_PUNCT, s, n);
        return;
    }
    if (*fence) {
        emit(o, TUI_HL_STRING, s, n);
        return;
    }
    if (k < n && s[k] == '#') {
        size_t h = k;
        while (h < n && s[h] == '#')
            h++;
        if (h - k <= 6 && (h == n || s[h] == ' ')) {
            emit(o, TUI_HL_KEYWORD, s, n);
            return;
        }
    }
    if (k < n && s[k] == '>') {
        emit(o, TUI_HL_COMMENT, s, n);
        return;
    }
    size_t i = 0;
    if (k + 1 < n && (s[k] == '-' || s[k] == '*' || s[k] == '+') && s[k + 1] == ' ') {
        emit(o, NONE, s, k);
        emit(o, TUI_HL_PUNCT, s + k, 1);
        i = k + 1;
    }
    while (i < n) {
        size_t st = i;
        if (s[i] == '`') {
            size_t e = i + 1;
            while (e < n && s[e] != '`')
                e++;
            if (e < n) {
                emit(o, TUI_HL_STRING, s + i, e + 1 - i);
                i = e + 1;
                continue;
            }
        }
        if (s[i] == '[') {
            size_t e = i + 1;
            while (e < n && s[e] != ']')
                e++;
            if (e + 1 < n && s[e + 1] == '(') {
                size_t u = e + 2;
                while (u < n && s[u] != ')')
                    u++;
                if (u < n) {
                    emit(o, TUI_HL_FUNCTION, s + i, e + 1 - i);
                    emit(o, TUI_HL_COMMENT, s + e + 1, u + 1 - (e + 1));
                    i = u + 1;
                    continue;
                }
            }
        }
        i++;
        while (i < n && s[i] != '`' && s[i] != '[')
            i++;
        emit(o, NONE, s + st, i - st);
    }
}

static int lang_eq(const char *l, size_t n, const char *name)
{
    return strlen(name) == n && strncasecmp(l, name, n) == 0;
}

static const char *const LANGS[][8] = {
    {"c", "h", "cpp", "c++", "cc", "cxx", "hpp", "hh"},
    {"sh", "bash", "zsh", "shell", "console", "shellscript", "ksh"},
    {"py", "python", "python3", "py3"},
    {"js", "javascript", "jsx", "mjs", "cjs", "ts", "typescript", "tsx"},
    {"json", "jsonc", "json5"},
    {"go", "golang"},
    {"rs", "rust"},
    {"diff", "patch"},
    {"md", "markdown"},
    {"yaml", "yml"},
    {"sql", "sqlite", "psql", "mysql"},
};
static const lang_t *const LEXERS[] = {&L_C, &L_SH, &L_PY, &L_JS, &L_JSON, &L_GO, &L_RUST, NULL, NULL, &L_YAML, &L_SQL};
enum { K_DIFF = 7, K_MD = 8 };

static int lang_kind(const char *lang)
{
    size_t ln = 0;
    if (!lang)
        return -1;
    while (*lang == ' ' || *lang == '.')
        lang++;
    while (lang[ln] && lang[ln] != ' ' && lang[ln] != '\t' && lang[ln] != '{' && lang[ln] != ',' && lang[ln] != ':')
        ln++;
    for (size_t k = 0; k < sizeof LANGS / sizeof LANGS[0]; k++)
        for (size_t a = 0; a < 8 && LANGS[k][a]; a++)
            if (lang_eq(lang, ln, LANGS[k][a]))
                return (int)k;
    return -1;
}

int tui_highlight_known(const char *lang)
{
    return lang_kind(lang) >= 0;
}

int tui_highlight(const char *lang, const char *code, size_t len, const tui_hl_theme *theme, char **out,
                  size_t *out_len)
{
    out_t o = {.th = theme};
    int kind = lang_kind(lang);
    if (len == 0)
        code = "";
    if (kind == K_DIFF) {
        lines(&o, code, len, diff_line, NULL);
    } else if (kind == K_MD) {
        int fence = 0;
        lines(&o, code, len, md_line, &fence);
    } else {
        lex(&o, kind >= 0 ? LEXERS[kind] : &L_GENERIC, code, len);
    }
    if (o.oom) {
        free(o.p);
        return -1;
    }
    if (!o.p) {
        o.p = malloc(1);
        if (!o.p)
            return -1;
    }
    o.p[o.n] = 0;
    *out = o.p;
    *out_len = o.n;
    return 0;
}