Artifact 5fac367f8d8db7da419d72a3579d94e21b68e89459fb7d11b4276cd15e87b70d:
- File
src/tui/highlight.h
— part of check-in
[f84ad487f5]
at
2026-11-19 23:12:08
on branch highlight
— TUI: a syntax highlighter for code blocks
src/tui/highlight.c colours fenced code with ANSI SGR using Pi's token classes and its dark and light theme colours: C and C++, shell, Python, JavaScript and TypeScript, JSON, Go, Rust, diff, Markdown, YAML and SQL, with a generic fallback. Linear, safe on arbitrary bytes (a random input test under ASan), every styled span closed before each newline so lines wrap on their own. Not wired into the renderer yet. (user: dmestas, size: 1901) [annotate] [blame] [check-ins using] [more...]
/* Syntax highlighting for fenced code blocks (highlight.c). * Pure function: no I/O, no globals. Small hand-written lexers, linear time, * safe on arbitrary bytes. Token classes and default colours follow Pi's * syntax theme tokens (syntaxComment, syntaxKeyword, syntaxFunction, * syntaxVariable, syntaxString, syntaxNumber, syntaxType, syntaxOperator, * syntaxPunctuation) plus diff add/del/meta. */ #ifndef PIC_TUI_HIGHLIGHT_H #define PIC_TUI_HIGHLIGHT_H #include <stddef.h> typedef enum { TUI_HL_COMMENT, TUI_HL_KEYWORD, TUI_HL_FUNCTION, TUI_HL_VARIABLE, TUI_HL_STRING, TUI_HL_NUMBER, TUI_HL_TYPE, TUI_HL_OPERATOR, TUI_HL_PUNCT, TUI_HL_ADD, TUI_HL_DEL, TUI_HL_META, TUI_HL_N } tui_hl_class; /* One SGR opening sequence per class (e.g. "\x1b[38;2;138;149;224m"), or * NULL to leave that class unstyled. Strings must outlive the call. */ typedef struct { const char *sgr[TUI_HL_N]; } tui_hl_theme; extern const tui_hl_theme tui_hl_theme_dark; /* Pi's dark theme colours */ extern const tui_hl_theme tui_hl_theme_light; /* Pi's light theme colours */ /* Highlights code[0..len) as language lang (a fence info string such as * "c", "ts" or "python title=x"; NULL or unknown uses a generic lexer for * strings, numbers and comments). On success *out is a malloc'd NUL-terminated * string the caller frees, and *out_len its length. Supported: c, c++, shell, * python, js/ts, json, go, rust, diff, markdown, yaml, sql. * * Every styled span is "SGR text ESC[0m" and never crosses a '\n', so each * output line is self-contained and wraps cleanly with tui_wrap. ESC bytes in * the input are dropped. A NULL theme yields the text unstyled. Returns 0, or * -1 on out of memory. */ int tui_highlight(const char *lang, const char *code, size_t len, const tui_hl_theme *theme, char **out, size_t *out_len); #endif