Skip to content
pi-c Documentation
Login

Documentation

/* UTF-8 text measurement and wrapping for the terminal (width.c).
 * Pure functions: no I/O, no globals. 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 <stddef.h>
#include <stdint.h>

/* 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);

/* 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