/* UTF-8 text measurement and wrapping for the terminal (width.c). * No I/O; the cluster flag below is its only state. Text may contain ANSI escape * sequences (CSI "ESC [ ... final" and OSC "ESC ] ... BEL or ESC \"); they * take no columns and are never split. */ #ifndef PIC_TUI_WIDTH_H #define PIC_TUI_WIDTH_H #include #include /* Decodes one code point at s (len > 0). Returns the bytes used (1..4); * invalid or truncated UTF-8 decodes as U+FFFD using 1 byte. */ size_t tui_utf8_decode(const char *s, size_t len, uint32_t *cp); /* Columns a code point takes: 0 for combining marks, zero-width * characters (ZWJ, variation selectors) and C0/C1 controls; 2 for East Asian * wide and fullwidth characters and emoji (U+1F300..U+1FAFF and the like); * 1 otherwise. */ int tui_cp_width(uint32_t cp); /* Grapheme clusters (terminal mode 2027). Off by default: every code point is measured alone. The terminal * interface turns it on when the terminal reports it clusters, and every width, fit and wrap below, and the * editor's cursor, then take a ZWJ sequence, an emoji with a skin tone or VS16, a keycap or a flag as one * two-column cell. This one flag is the module's only state. */ void tui_width_clusters(int on); int tui_width_clusters_on(void); /* The bytes (1 or more) and columns of the character at s (len > 0): a code point, or with clusters on its whole * cluster. Not for escape sequences or newlines. */ size_t tui_cluster_at(const char *s, size_t len, int *cols); /* Display columns of s[0..len), escape sequences excluded. A tab counts 4. */ size_t tui_width(const char *s, size_t len); /* The longest prefix of s[0..len) (in bytes) that fits in cols columns, * never splitting a code point or an escape sequence; it stops before a "\n". */ size_t tui_fit(const char *s, size_t len, size_t cols); /* A growable list of malloc'd, NUL-terminated lines. */ typedef struct { char **lines; size_t n, cap; } tui_lines; int tui_lines_add(tui_lines *l, const char *s, size_t len); /* copies; 0 or -1 */ void tui_lines_clear(tui_lines *l); /* frees the lines, keeps nothing */ /* Appends text wrapped to cols (>= 1) columns to out: a line per "\n", each * broken at the last space that fits, or hard-broken inside a word longer * than cols. Tabs become 4 spaces. Trailing spaces at a break are dropped. * SGR state (ESC [ ... m) carries across breaks: a broken line ends with * ESC [0m when a style is active and the next line starts by re-opening it. * The output is sanitized: only SGR escapes are kept (every other CSI, OSC * and ESC x sequence is dropped), as are the controls \r, \b, BEL and the * other C0/C1 controls (U+0000-001F and U+007F-009F, except "\n" and tab). * Every produced line has tui_width(line) <= cols. 0 or -1 (out of memory). */ int tui_wrap(const char *text, size_t len, size_t cols, tui_lines *out); #endif