Skip to content
pi-c Documentation
Login

Documentation

/* Unit tests for the terminal UI modules (width, term decoder, render, editor). */
#include "tui/editor.h"
#include "tui/render.h"
#include "tui/term.h"
#include "tui/width.h"

#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define SYNC_ON "\x1b[?2026h"
#define SYNC_OFF "\x1b[?2026l"
#define HIDE "\x1b[?25l"
#define SHOW "\x1b[?25h"

static void fail(const char *what, const char *fmt, ...)
{
    va_list ap;
    fprintf(stderr, "FAIL: %s: ", what);
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fputc('\n', stderr);
    exit(1);
}

static void pass(const char *what)
{
    printf("PASS: %s\n", what);
}

/* Escapes control bytes so a failure message is readable. */
static void show(const char *s, size_t n, char *out, size_t cap)
{
    size_t o = 0;
    for (size_t i = 0; i < n && o + 8 < cap; i++) {
        unsigned char c = (unsigned char)s[i];
        if (c == 0x1b)
            o += (size_t)snprintf(out + o, cap - o, "\\e");
        else if (c == '\n')
            o += (size_t)snprintf(out + o, cap - o, "\\n");
        else if (c == '\r')
            o += (size_t)snprintf(out + o, cap - o, "\\r");
        else if (c < 0x20)
            o += (size_t)snprintf(out + o, cap - o, "\\x%02x", c);
        else
            out[o++] = (char)c;
    }
    out[o] = 0;
}

static void check_str(const char *what, const char *got, const char *want)
{
    if (strcmp(got, want) != 0) {
        char a[1024], b[1024];
        show(got, strlen(got), a, sizeof a);
        show(want, strlen(want), b, sizeof b);
        fail(what, "got \"%s\" want \"%s\"", a, b);
    }
}

static void check_int(const char *what, long got, long want)
{
    if (got != want)
        fail(what, "got %ld want %ld", got, want);
}

/* ---- width ------------------------------------------------------------- */

static void test_width(void)
{
    uint32_t cp;
    check_int("decode ascii", (long)tui_utf8_decode("a", 1, &cp), 1);
    check_int("decode ascii cp", cp, 'a');
    check_int("decode 2-byte", (long)tui_utf8_decode("\xC3\xA9", 2, &cp), 2);
    check_int("decode 2-byte cp", cp, 0xE9);
    check_int("decode 3-byte", (long)tui_utf8_decode("\xE4\xB8\xAD", 3, &cp), 3);
    check_int("decode 3-byte cp", cp, 0x4E2D);
    check_int("decode 4-byte", (long)tui_utf8_decode("\xF0\x9F\x98\x80", 4, &cp), 4);
    check_int("decode 4-byte cp", cp, 0x1F600);
    check_int("decode truncated", (long)tui_utf8_decode("\xE4\xB8", 2, &cp), 1);
    check_int("decode truncated cp", cp, 0xFFFD);
    check_int("decode overlong", (long)tui_utf8_decode("\xC0\x80", 2, &cp), 1);
    check_int("decode surrogate", (long)tui_utf8_decode("\xED\xA0\x80", 3, &cp), 1);
    check_int("decode stray continuation", (long)tui_utf8_decode("\x80", 1, &cp), 1);
    check_int("decode real U+FFFD", (long)tui_utf8_decode("\xEF\xBF\xBD", 3, &cp), 3);
    pass("utf8 decode");

    check_int("width a", tui_cp_width('a'), 1);
    check_int("width nul", tui_cp_width(0), 0);
    check_int("width esc", tui_cp_width(0x1b), 0);
    check_int("width C1", tui_cp_width(0x85), 0);
    check_int("width e-acute", tui_cp_width(0xE9), 1);
    check_int("width combining acute", tui_cp_width(0x301), 0);
    check_int("width combining 1AB0", tui_cp_width(0x1AB0), 0);
    check_int("width combining 1DC0", tui_cp_width(0x1DC0), 0);
    check_int("width combining 20D0", tui_cp_width(0x20D0), 0);
    check_int("width ZWSP", tui_cp_width(0x200B), 0);
    check_int("width ZWJ", tui_cp_width(0x200D), 0);
    check_int("width VS16", tui_cp_width(0xFE0F), 0);
    check_int("width VS supplement", tui_cp_width(0xE0100), 0);
    check_int("width CJK", tui_cp_width(0x4E2D), 2);
    check_int("width hangul", tui_cp_width(0xAC00), 2);
    check_int("width jamo", tui_cp_width(0x1100), 2);
    check_int("width fullwidth A", tui_cp_width(0xFF21), 2);
    check_int("width 303F narrow", tui_cp_width(0x303F), 1);
    check_int("width emoji", tui_cp_width(0x1F600), 2);
    check_int("width emoji 1F9FF", tui_cp_width(0x1F9FF), 2);
    check_int("width CJK ext B", tui_cp_width(0x20000), 2);
    check_int("width cent sign", tui_cp_width(0xA2), 1);
    check_int("width plain symbol", tui_cp_width(0x2603), 1);
    pass("code point width");

    const char *s = "\x1b[31mred\x1b[0m";
    check_int("width ignores sgr", (long)tui_width(s, strlen(s)), 3);
    s = "\x1b]8;;http://x\x1b\\link\x1b]8;;\x1b\\";
    check_int("width ignores osc", (long)tui_width(s, strlen(s)), 4);
    s = "\x1b]0;title\a" "ab";
    check_int("width ignores osc bel", (long)tui_width(s, strlen(s)), 2);
    check_int("width tab", (long)tui_width("a\tb", 3), 6);
    check_int("width cjk string", (long)tui_width("\xE4\xB8\xAD\xE6\x96\x87", 6), 4);
    check_int("width combining string", (long)tui_width("e\xCC\x81", 3), 1);
    check_int("width truncated escape", (long)tui_width("a\x1b[3", 4), 1);
    pass("display width");

    check_int("fit all", (long)tui_fit("hello", 5, 10), 5);
    check_int("fit prefix", (long)tui_fit("hello", 5, 3), 3);
    check_int("fit wide", (long)tui_fit("\xE4\xB8\xAD\xE6\x96\x87", 6, 3), 3);
    check_int("fit wide exact", (long)tui_fit("\xE4\xB8\xAD\xE6\x96\x87", 6, 4), 6);
    s = "\x1b[31mabc";
    check_int("fit keeps escape whole", (long)tui_fit(s, strlen(s), 2), 7);
    check_int("fit zero cols", (long)tui_fit("abc", 3, 0), 0);
    pass("fit");
}

static void lines_eq(const char *what, const tui_lines *l, size_t n, ...)
{
    va_list ap;
    va_start(ap, n);
    if (l->n != n) {
        for (size_t i = 0; i < l->n; i++)
            fprintf(stderr, "  line %zu: \"%s\"\n", i, l->lines[i]);
        fail(what, "got %zu lines want %zu", l->n, n);
    }
    for (size_t i = 0; i < n; i++) {
        const char *want = va_arg(ap, const char *);
        char label[128];
        snprintf(label, sizeof label, "%s line %zu", what, i);
        check_str(label, l->lines[i], want);
    }
    va_end(ap);
}

static void wrap_check(const char *what, const char *text, size_t cols, size_t n, ...)
{
    tui_lines l = {0};
    if (tui_wrap(text, strlen(text), cols, &l) != 0)
        fail(what, "wrap failed");
    va_list ap;
    va_start(ap, n);
    if (l.n != n)
        fail(what, "got %zu lines want %zu", l.n, n);
    for (size_t i = 0; i < n; i++) {
        const char *want = va_arg(ap, const char *);
        char label[128];
        snprintf(label, sizeof label, "%s line %zu", what, i);
        check_str(label, l.lines[i], want);
        if (tui_width(l.lines[i], strlen(l.lines[i])) > cols)
            fail(what, "line %zu wider than %zu", i, cols);
    }
    va_end(ap);
    tui_lines_clear(&l);
}

static void test_wrap(void)
{
    tui_lines l = {0};
    check_int("lines add", tui_lines_add(&l, "abc", 2), 0);
    check_str("lines copy", l.lines[0], "ab");
    tui_lines_clear(&l);
    check_int("lines cleared", (long)l.n, 0);
    pass("lines list");

    wrap_check("wrap short", "hello", 10, 1, "hello");
    wrap_check("wrap empty", "", 10, 1, "");
    wrap_check("wrap newline", "ab\ncd", 10, 2, "ab", "cd");
    wrap_check("wrap trailing newline", "ab\n", 10, 2, "ab", "");
    wrap_check("wrap words", "hello world foo", 11, 2, "hello world", "foo");
    wrap_check("wrap drops spaces at break", "hello   world", 6, 2, "hello", "world");
    wrap_check("wrap hard break", "abcdefghij", 4, 3, "abcd", "efgh", "ij");
    wrap_check("wrap long word after text", "ab cdefghij", 4, 3, "ab", "cdef", "ghij");
    wrap_check("wrap exact fit", "abcd efgh", 4, 2, "abcd", "efgh");
    wrap_check("wrap space at edge", "abcd efgh", 5, 2, "abcd", "efgh");
    wrap_check("wrap tab", "a\tb", 10, 1, "a    b");
    wrap_check("wrap wide", "\xE4\xB8\xAD\xE6\x96\x87\xE5\xAD\x97", 4, 2,
               "\xE4\xB8\xAD\xE6\x96\x87", "\xE5\xAD\x97");
    wrap_check("wrap keeps leading indent", "  ab", 10, 1, "  ab");
    pass("wrap plain");

    wrap_check("wrap sgr carries", "\x1b[31mred green blue\x1b[0m", 9, 2,
               "\x1b[31mred green\x1b[0m", "\x1b[31mblue\x1b[0m");
    wrap_check("wrap sgr reset before break", "\x1b[1mbold\x1b[0m plain text", 10, 2,
               "\x1b[1mbold\x1b[0m plain", "text");
    wrap_check("wrap sgr hard break", "\x1b[32mabcdef", 3, 2, "\x1b[32mabc\x1b[0m", "\x1b[32mdef");
    wrap_check("wrap sgr across newline", "\x1b[4mab\ncd", 10, 2, "\x1b[4mab\x1b[0m", "\x1b[4mcd");
    wrap_check("wrap sgr two styles", "\x1b[1m\x1b[31mab cd", 2, 2,
               "\x1b[1m\x1b[31mab\x1b[0m", "\x1b[1m\x1b[31mcd");
    pass("wrap sgr");

    wrap_check("wrap drops non-SGR csi", "a\x1b[2Jb\x1b[?25lc", 10, 1, "abc");
    wrap_check("wrap drops osc", "a\x1b]0;title\ab\x1b]8;;u\x1b\\c", 10, 1, "abc");
    wrap_check("wrap drops ESC x", "a\x1b" "7b", 10, 1, "ab");
    wrap_check("wrap drops C0 controls", "a\rb\bc\ad\x01" "e\x7f", 10, 1, "abcde");
    wrap_check("wrap drops C1 controls", "a\xC2\x85" "b\xC2\x9F", 10, 1, "ab");
    wrap_check("wrap keeps sgr among dropped", "\x1b[1ma\x1b[Kb", 10, 1, "\x1b[1mab");
    check_int("fit stops at newline", (long)tui_fit("ab\ncd", 5, 10), 2);
    pass("wrap sanitizes");
}

/* ---- key decoder ------------------------------------------------------- */

static const char *key_name(tui_key_kind k)
{
    static const char *names[] = {
        "CHAR", "ENTER", "NEWLINE", "TAB", "BACKSPACE", "DELETE", "LEFT", "RIGHT", "UP", "DOWN",
        "HOME", "END", "PAGEUP", "PAGEDOWN", "WORD_LEFT", "WORD_RIGHT", "DELETE_WORD", "KILL_LINE",
        "KILL_START", "ESC", "CTRL_C", "CTRL_D", "CTRL_L", "CTRL_O", "PASTE",
    };
    return (size_t)k < sizeof names / sizeof names[0] ? names[k] : "?";
}

/* Drains the decoder into a space-separated description. */
static void drain(tui_keys *k, char *out, size_t cap)
{
    size_t o = 0;
    tui_key key;
    out[0] = 0;
    while (tui_keys_next(k, &key)) {
        if (o)
            o += (size_t)snprintf(out + o, cap - o, " ");
        if (key.kind == TUI_KEY_CHAR) {
            o += (size_t)snprintf(out + o, cap - o, "CHAR:%s", key.text);
        } else if (key.kind == TUI_KEY_PASTE) {
            char esc[512];
            show(key.paste, key.paste_len, esc, sizeof esc);
            o += (size_t)snprintf(out + o, cap - o, "PASTE:%s", esc);
            free(key.paste);
        } else {
            o += (size_t)snprintf(out + o, cap - o, "%s", key_name(key.kind));
        }
    }
}

static void decode_check(const char *what, const char *bytes, size_t n, const char *want)
{
    tui_keys *k = tui_keys_new();
    char got[1024];
    tui_keys_feed(k, bytes, n);
    drain(k, got, sizeof got);
    check_str(what, got, want);
    tui_keys_free(k);
}

#define DECODE(what, bytes, want) decode_check(what, bytes, sizeof(bytes) - 1, want)

static void test_decoder(void)
{
    DECODE("printable", "abc", "CHAR:a CHAR:b CHAR:c");
    DECODE("utf8 2-byte", "\xC3\xA9", "CHAR:\xC3\xA9");
    DECODE("utf8 3-byte", "\xE4\xB8\xAD", "CHAR:\xE4\xB8\xAD");
    DECODE("utf8 emoji", "\xF0\x9F\x98\x80", "CHAR:\xF0\x9F\x98\x80");
    DECODE("space", " ", "CHAR: ");
    DECODE("invalid bytes dropped", "\xFF\x80z", "CHAR:z");
    pass("decode printable");

    DECODE("cr", "\r", "ENTER");
    DECODE("lf", "\n", "NEWLINE");
    DECODE("tab", "\t", "TAB");
    DECODE("del", "\x7f", "BACKSPACE");
    DECODE("ctrl-h", "\x08", "BACKSPACE");
    DECODE("ctrl-a", "\x01", "HOME");
    DECODE("ctrl-e", "\x05", "END");
    DECODE("ctrl-c", "\x03", "CTRL_C");
    DECODE("ctrl-d", "\x04", "CTRL_D");
    DECODE("ctrl-k", "\x0b", "KILL_LINE");
    DECODE("ctrl-l", "\x0c", "CTRL_L");
    DECODE("ctrl-o", "\x0f", "CTRL_O");
    DECODE("ctrl-u", "\x15", "KILL_START");
    DECODE("ctrl-w", "\x17", "DELETE_WORD");
    DECODE("other control dropped", "\x02\x1a", "");
    pass("decode control keys");

    DECODE("csi arrows", "\x1b[A\x1b[B\x1b[C\x1b[D", "UP DOWN RIGHT LEFT");
    DECODE("ss3 arrows", "\x1bOA\x1bOB\x1bOC\x1bOD", "UP DOWN RIGHT LEFT");
    DECODE("csi home end", "\x1b[H\x1b[F", "HOME END");
    DECODE("ss3 home end", "\x1bOH\x1bOF", "HOME END");
    DECODE("tilde home end", "\x1b[1~\x1b[4~\x1b[7~\x1b[8~", "HOME END HOME END");
    DECODE("delete pgup pgdn", "\x1b[3~\x1b[5~\x1b[6~", "DELETE PAGEUP PAGEDOWN");
    pass("decode navigation");

    DECODE("alt-b alt-f", "\x1b" "b\x1b" "f", "WORD_LEFT WORD_RIGHT");
    DECODE("alt arrows", "\x1b[1;3D\x1b[1;3C", "WORD_LEFT WORD_RIGHT");
    DECODE("ctrl arrows", "\x1b[1;5D\x1b[1;5C", "WORD_LEFT WORD_RIGHT");
    DECODE("shift arrow is plain", "\x1b[1;2D", "LEFT");
    DECODE("alt backspace", "\x1b\x7f", "DELETE_WORD");
    DECODE("alt enter", "\x1b\r", "NEWLINE");
    DECODE("alt unknown dropped", "\x1bx", "");
    pass("decode word keys");

    DECODE("shift-enter kitty", "\x1b[13;2u", "NEWLINE");
    DECODE("shift-enter modifyOtherKeys", "\x1b[27;2;13~", "NEWLINE");
    DECODE("enter kitty plain", "\x1b[13u", "ENTER");
    DECODE("enter kitty mod 1", "\x1b[13;1u", "ENTER");
    pass("decode shift-enter");

    DECODE("unknown csi dropped", "\x1b[99;1Xa", "CHAR:a");
    DECODE("unknown csi with intermediate", "\x1b[?25$pb", "CHAR:b");
    DECODE("backtab dropped", "\x1b[Z", "");
    DECODE("esc then csi", "\x1b\x1b[A", "ESC UP");
    pass("decode unknown sequences");

    /* Split sequences: a CSI cut at every byte boundary still decodes. */
    {
        tui_keys *k = tui_keys_new();
        const char seq[] = "\x1b[1;5D";
        char got[128];
        for (size_t i = 0; i + 1 < sizeof seq; i++) {
            tui_keys_feed(k, seq + i, 1);
            if (i + 2 < sizeof seq) {
                drain(k, got, sizeof got);
                check_str("split csi nothing early", got, "");
                check_int("split csi waiting", tui_keys_waiting(k), 1);
            }
        }
        drain(k, got, sizeof got);
        check_str("split csi done", got, "WORD_LEFT");
        check_int("split csi not waiting", tui_keys_waiting(k), 0);
        const char u[] = "\xF0\x9F";
        tui_keys_feed(k, u, 2);
        check_int("split utf8 waiting", tui_keys_waiting(k), 1);
        tui_keys_feed(k, "\x98\x80", 2);
        drain(k, got, sizeof got);
        check_str("split utf8 done", got, "CHAR:\xF0\x9F\x98\x80");
        tui_keys_free(k);
    }
    pass("decode split input");

    {
        tui_keys *k = tui_keys_new();
        char got[128];
        tui_keys_feed(k, "\x1b", 1);
        drain(k, got, sizeof got);
        check_str("lone esc pending", got, "");
        check_int("lone esc waiting", tui_keys_waiting(k), 1);
        tui_keys_flush(k);
        drain(k, got, sizeof got);
        check_str("lone esc flushed", got, "ESC");
        check_int("lone esc done", tui_keys_waiting(k), 0);

        tui_keys_feed(k, "\x1b[", 2);
        check_int("unfinished csi waiting", tui_keys_waiting(k), 1);
        for (int i = 0; i < 2; i++) {
            tui_keys_flush(k);
            check_int("unfinished csi kept through flush", tui_keys_waiting(k), 1);
        }
        tui_keys_feed(k, "A", 1);
        drain(k, got, sizeof got);
        check_str("late rest completes the csi", got, "UP");
        tui_keys_feed(k, "\x1b[", 2);
        for (int i = 0; i < 3; i++)
            tui_keys_flush(k);
        drain(k, got, sizeof got);
        check_str("unfinished csi dropped after 3 flushes", got, "");
        check_int("unfinished csi done", tui_keys_waiting(k), 0);
        tui_keys_feed(k, "\xE4\xB8", 2);
        tui_keys_flush(k);
        tui_keys_feed(k, "\xAD", 1);
        drain(k, got, sizeof got);
        check_str("utf8 split across a flush", got, "CHAR:\xE4\xB8\xAD");

        tui_keys_feed(k, "\x1b", 1);
        tui_keys_feed(k, "[A", 2);
        drain(k, got, sizeof got);
        check_str("esc then rest is a key", got, "UP");
        tui_keys_free(k);
    }
    pass("lone esc");

    DECODE("paste", "\x1b[200~hello\x1b[201~", "PASTE:hello");
    DECODE("paste crlf", "\x1b[200~a\r\nb\rc\nd\x1b[201~", "PASTE:a\\nb\\nc\\nd");
    DECODE("paste keeps escapes inside", "\x1b[200~x\x1b[Ay\x1b[201~", "PASTE:x\\e[Ay");
    DECODE("paste empty", "\x1b[200~\x1b[201~", "PASTE:");
    DECODE("keys around paste", "a\x1b[200~b\x1b[201~c", "CHAR:a PASTE:b CHAR:c");
    {
        tui_keys *k = tui_keys_new();
        char got[256];
        const char *parts[] = {"\x1b[20", "0~line1\r", "\nline2\x1b", "[20", "1", "~z"};
        for (size_t i = 0; i < sizeof parts / sizeof parts[0]; i++) {
            tui_keys_feed(k, parts[i], strlen(parts[i]));
            drain(k, got, sizeof got);
            if (i < 5)
                check_str("paste split quiet", got, "");
            else
                check_str("paste split done", got, "PASTE:line1\\nline2 CHAR:z");
        }
        /* a lone ESC inside a paste is not flushed away */
        tui_keys_feed(k, "\x1b[200~ab\x1b", 9);
        check_int("paste not waiting", tui_keys_waiting(k), 0);
        tui_keys_flush(k);
        tui_keys_feed(k, "[201~", 5);
        drain(k, got, sizeof got);
        check_str("paste survives flush", got, "PASTE:ab");
        tui_keys_free(k);
    }
    pass("decode bracketed paste");
}

/* ---- render ------------------------------------------------------------ */

static int rfd[2];

static void render_expect(const char *what, const char *want)
{
    char got[4096];
    ssize_t n = read(rfd[0], got, sizeof got - 1);
    if (n < 0)
        n = 0;
    got[n] = 0;
    check_str(what, got, want);
    if (read(rfd[0], got, 1) > 0)
        fail(what, "extra output after the expected frame");
}

static void test_render(void)
{
    if (pipe(rfd) != 0)
        fail("render", "pipe");
    int fl = fcntl(rfd[0], F_GETFL);
    fcntl(rfd[0], F_SETFL, fl | O_NONBLOCK);
    tui_render *r = tui_render_new(rfd[1]);

    const char *ab[] = {"a", "b"};
    tui_render_draw(r, ab, 2, 1, 3, 24);
    render_expect("first draw", SYNC_ON HIDE "a\r\nb" "\r" "\x1b[4G" SHOW SYNC_OFF);

    const char *abc[] = {"a", "b", "c"};
    tui_render_draw(r, abc, 3, 2, 0, 24);
    render_expect("append writes only the new line", SYNC_ON HIDE "\r\nc" "\r" SHOW SYNC_OFF);

    const char *aXc[] = {"a", "X", "c"};
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("middle change", SYNC_ON HIDE "\x1b[1A" "\r\x1b[J" "X\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_draw(r, aXc, 3, 0, 0, 24);
    render_expect("identical lines move only the cursor", SYNC_ON HIDE "\x1b[2A" "\r" SHOW SYNC_OFF);

    const char *aX[] = {"a", "X"};
    tui_render_draw(r, aX, 2, 1, 0, 24);
    render_expect("shrink", SYNC_ON HIDE "\x1b[2B" "\r\x1b[J" "\x1b[1A" "\r" SHOW SYNC_OFF);
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("regrow", SYNC_ON HIDE "\r\n" "c" "\r\x1b[2G" SHOW SYNC_OFF);

    const char *done[] = {"done"};
    tui_render_commit(r, done, 1);
    render_expect("commit", SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "done\r\n" "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_invalidate(r);
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("invalidate redraws everything",
                  SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("no redraw after invalidate is consumed", SYNC_ON HIDE "\r" "\x1b[2G" SHOW SYNC_OFF);

    const char *many[] = {"l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9"};
    tui_render_draw(r, many, 10, 9, 1, 4);
    render_expect("more lines than rows keeps the last rows-1",
                  SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "l7\r\nl8\r\nl9" "\r\x1b[2G" SHOW SYNC_OFF);
    tui_render_draw(r, many, 10, -1, 0, 4);
    render_expect("hidden cursor stays hidden", SYNC_ON HIDE SYNC_OFF);

    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("redraw after clip", SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);
    tui_render_invalidate(r);
    tui_render_commit(r, done, 1);
    render_expect("commit while invalid does not redraw old lines",
                  SYNC_ON HIDE "\x1b[2A" "\r\x1b[J" "done\r\n" SHOW SYNC_OFF);
    tui_render_draw(r, aXc, 3, 2, 1, 24);
    render_expect("draw after invalid commit rewrites fully",
                  SYNC_ON HIDE "a\r\nX\r\nc" "\r\x1b[2G" SHOW SYNC_OFF);

    tui_render_finish(r);
    render_expect("finish", "\r\n" SHOW);
    tui_render_free(r);

    /* An empty live area: commit just writes the lines. */
    r = tui_render_new(rfd[1]);
    tui_render_commit(r, done, 1);
    render_expect("commit with empty live area", SYNC_ON HIDE "done\r\n" SHOW SYNC_OFF);
    tui_render_free(r);

    /* A closed fd reports an error. */
    r = tui_render_new(-1);
    check_int("write error", tui_render_draw(r, ab, 2, 0, 0, 24), -1);
    tui_render_free(r);
    close(rfd[0]);
    close(rfd[1]);
    pass("render");
}

/* ---- editor ------------------------------------------------------------ */

static int press(tui_editor *e, tui_key_kind kind)
{
    tui_key k;
    memset(&k, 0, sizeof k);
    k.kind = kind;
    return tui_editor_key(e, &k);
}

static void type(tui_editor *e, const char *s)
{
    while (*s) {
        uint32_t cp;
        size_t n = tui_utf8_decode(s, strlen(s), &cp);
        tui_key k;
        memset(&k, 0, sizeof k);
        k.kind = TUI_KEY_CHAR;
        memcpy(k.text, s, n);
        tui_editor_key(e, &k);
        s += n;
    }
}

static void paste_text(tui_editor *e, const char *s)
{
    tui_key k;
    memset(&k, 0, sizeof k);
    k.kind = TUI_KEY_PASTE;
    k.paste = (char *)(uintptr_t)s;
    k.paste_len = strlen(s);
    tui_editor_key(e, &k);
}

/* The editor's text, "|" marking nothing: read it with take on a copy. */
static char *text_of(tui_editor *e)
{
    tui_lines l = {0};
    int row, col;
    tui_editor_render(e, 1000, &l, &row, &col);
    size_t cap = 1;
    for (size_t i = 0; i < l.n; i++)
        cap += strlen(l.lines[i]) + 1;
    char *out = calloc(cap, 1);
    for (size_t i = 0; i < l.n; i++) {
        if (i)
            strcat(out, "\n");
        strcat(out, l.lines[i] + 2);
    }
    tui_lines_clear(&l);
    return out;
}

static void text_is(const char *what, tui_editor *e, const char *want)
{
    char *t = text_of(e);
    check_str(what, t, want);
    free(t);
}

static void cursor_is(const char *what, tui_editor *e, size_t cols, int want_row, int want_col)
{
    tui_lines l = {0};
    int row, col;
    if (tui_editor_render(e, cols, &l, &row, &col) != 0)
        fail(what, "render failed");
    if (row != want_row || col != want_col)
        fail(what, "cursor at %d,%d want %d,%d", row, col, want_row, want_col);
    tui_lines_clear(&l);
}

static void take_is(const char *what, tui_editor *e, const char *want)
{
    char *t = tui_editor_take(e);
    if (!t)
        fail(what, "take returned NULL");
    check_str(what, t, want);
    free(t);
}

static void test_editor(void)
{
    tui_editor *e = tui_editor_new();
    check_int("new is empty", tui_editor_empty(e), 1);
    type(e, "hello");
    text_is("typing", e, "hello");
    check_int("typing makes it non-empty", tui_editor_empty(e), 0);
    check_int("enter submits", press(e, TUI_KEY_ENTER), TUI_EDIT_SUBMIT);
    take_is("take returns text", e, "hello");
    check_int("empty after take", tui_editor_empty(e), 1);
    check_int("empty enter ignored", press(e, TUI_KEY_ENTER), TUI_EDIT_NONE);
    type(e, "  ");
    check_int("blank enter ignored", press(e, TUI_KEY_ENTER), TUI_EDIT_NONE);
    check_int("typing reports changed", press(e, TUI_KEY_NEWLINE), TUI_EDIT_CHANGED);
    check_int("blank multi-line enter ignored", press(e, TUI_KEY_ENTER), TUI_EDIT_NONE);
    check_int("unhandled key", press(e, TUI_KEY_CTRL_C), TUI_EDIT_NONE);
    check_int("tab not handled", press(e, TUI_KEY_TAB), TUI_EDIT_NONE);
    tui_editor_clear(e);
    pass("editor type and submit");

    type(e, "ab");
    press(e, TUI_KEY_NEWLINE);
    type(e, "cd");
    text_is("newline", e, "ab\ncd");
    press(e, TUI_KEY_HOME);
    check_int("backspace joins lines", press(e, TUI_KEY_BACKSPACE), TUI_EDIT_CHANGED);
    text_is("joined", e, "abcd");
    cursor_is("cursor after join", e, 80, 0, 4);
    press(e, TUI_KEY_BACKSPACE);
    text_is("backspace", e, "acd");
    press(e, TUI_KEY_DELETE);
    text_is("delete", e, "ad");
    press(e, TUI_KEY_HOME);
    check_int("backspace at start", press(e, TUI_KEY_BACKSPACE), TUI_EDIT_NONE);
    press(e, TUI_KEY_END);
    check_int("delete at end", press(e, TUI_KEY_DELETE), TUI_EDIT_NONE);
    tui_editor_clear(e);
    type(e, "a\xC3\xA9\xE4\xB8\xAD");
    press(e, TUI_KEY_BACKSPACE);
    text_is("backspace removes a whole UTF-8 char", e, "a\xC3\xA9");
    press(e, TUI_KEY_LEFT);
    press(e, TUI_KEY_DELETE);
    text_is("delete removes a whole UTF-8 char", e, "a");
    tui_editor_clear(e);
    pass("editor backspace and delete");

    tui_editor_free(e); /* a fresh editor: no history yet */
    e = tui_editor_new();
    type(e, "one");
    press(e, TUI_KEY_NEWLINE);
    type(e, "two2");
    press(e, TUI_KEY_NEWLINE);
    type(e, "x");
    check_int("up moves", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
    check_int("up again", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
    check_int("up on first line without history", press(e, TUI_KEY_UP), TUI_EDIT_NONE);
    cursor_is("up keeps the column (clamped)", e, 80, 0, 3);
    press(e, TUI_KEY_END);
    press(e, TUI_KEY_DOWN);
    cursor_is("down into a longer line", e, 80, 1, 5);
    press(e, TUI_KEY_DOWN);
    cursor_is("down into a shorter line", e, 80, 2, 3);
    press(e, TUI_KEY_UP);
    cursor_is("goal column is remembered", e, 80, 1, 5);
    for (int i = 0; i < 4; i++)
        press(e, TUI_KEY_LEFT);
    cursor_is("left crosses a line break", e, 80, 0, 5);
    press(e, TUI_KEY_RIGHT);
    cursor_is("right crosses a line break", e, 80, 1, 2);
    tui_editor_clear(e);
    pass("editor vertical movement");

    type(e, "first");
    take_is("take first", e, "first");
    type(e, "second");
    take_is("take second", e, "second");
    type(e, "draft");
    check_int("up into history", press(e, TUI_KEY_UP), TUI_EDIT_CHANGED);
    text_is("newest entry", e, "second");
    press(e, TUI_KEY_UP);
    text_is("older entry", e, "first");
    check_int("up past the oldest", press(e, TUI_KEY_UP), TUI_EDIT_NONE);
    text_is("still the oldest", e, "first");
    press(e, TUI_KEY_DOWN);
    text_is("back to newer", e, "second");
    press(e, TUI_KEY_DOWN);
    text_is("unsent text restored", e, "draft");
    check_int("down past the newest", press(e, TUI_KEY_DOWN), TUI_EDIT_NONE);
    tui_editor_clear(e);
    type(e, "second");
    take_is("no repeat of last entry", e, "second");
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_UP);
    text_is("history has no duplicate", e, "first");
    tui_editor_clear(e);
    for (int i = 0; i < 210; i++) {
        char b[16];
        snprintf(b, sizeof b, "m%d", i);
        type(e, b);
        take_is("fill history", e, b);
    }
    for (int i = 0; i < 300; i++)
        press(e, TUI_KEY_UP);
    text_is("history capped at 200", e, "m10");
    tui_editor_clear(e);
    pass("editor history");

    type(e, "foo bar  baz");
    press(e, TUI_KEY_WORD_LEFT);
    cursor_is("word left", e, 80, 0, 11);
    press(e, TUI_KEY_WORD_LEFT);
    cursor_is("word left again", e, 80, 0, 6);
    press(e, TUI_KEY_WORD_RIGHT);
    cursor_is("word right", e, 80, 0, 9);
    press(e, TUI_KEY_DELETE_WORD);
    text_is("delete word", e, "foo   baz");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_WORD_RIGHT);
    cursor_is("word right from start", e, 80, 0, 5);
    press(e, TUI_KEY_KILL_LINE);
    text_is("kill line", e, "foo");
    tui_editor_set(e, "abc\ndef");
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_END);
    press(e, TUI_KEY_KILL_LINE);
    text_is("kill line at end joins next", e, "abcdef");
    press(e, TUI_KEY_RIGHT);
    press(e, TUI_KEY_KILL_START);
    text_is("kill start", e, "ef");
    tui_editor_set(e, "ab\ncd");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_KILL_START);
    text_is("kill start at line start joins previous", e, "abcd");
    pass("editor word moves and kills");

    tui_editor_clear(e);
    paste_text(e, "short\npaste");
    text_is("small paste literal", e, "short\npaste");
    tui_editor_clear(e);
    check_int("empty after clear", tui_editor_empty(e), 1);

    char big[256] = "";
    for (int i = 1; i <= 20; i++) {
        char l[16];
        snprintf(l, sizeof l, "line%d%s", i, i < 20 ? "\n" : "");
        strcat(big, l);
    }
    type(e, "x ");
    paste_text(e, big);
    text_is("big paste collapsed", e, "x [paste #1 +20 lines]");
    type(e, " y");
    check_int("marker plus text can submit", press(e, TUI_KEY_ENTER), TUI_EDIT_SUBMIT);
    char *taken = tui_editor_take(e);
    char want[320];
    snprintf(want, sizeof want, "x %s y", big);
    check_str("take expands marker", taken, want);
    free(taken);

    paste_text(e, big);
    text_is("numbering restarts after submit", e, "[paste #1 +20 lines]");
    paste_text(e, big);
    text_is("second paste", e, "[paste #1 +20 lines][paste #2 +20 lines]");
    check_int("backspace on marker", press(e, TUI_KEY_BACKSPACE), TUI_EDIT_CHANGED);
    text_is("marker removed whole", e, "[paste #1 +20 lines]");
    press(e, TUI_KEY_HOME);
    press(e, TUI_KEY_DELETE);
    text_is("delete removes a whole marker", e, "");
    check_int("paste table cleared on removal still safe", tui_editor_empty(e), 1);

    /* cursor moves jump over a marker whole */
    tui_editor_clear(e);
    type(e, "ab");
    paste_text(e, big);
    type(e, "cd");
    for (int i = 0; i < 3; i++)
        press(e, TUI_KEY_LEFT);
    cursor_is("left from after marker lands before it", e, 80, 0, 4);
    press(e, TUI_KEY_RIGHT);
    cursor_is("right from before marker lands after it", e, 80, 0, 2 + 2 + 20);
    press(e, TUI_KEY_LEFT);
    type(e, "X");
    press(e, TUI_KEY_WORD_RIGHT);
    cursor_is("word right does not stop inside the marker", e, 80, 0, 2 + 3 + 20);
    press(e, TUI_KEY_WORD_LEFT);
    cursor_is("word left does not stop inside the marker", e, 80, 0, 2 + 3);
    press(e, TUI_KEY_RIGHT);
    press(e, TUI_KEY_RIGHT);
    type(e, "Y");
    taken = tui_editor_take(e);
    snprintf(want, sizeof want, "abX%scYd", big);
    check_str("typing beside a marker keeps it expandable", taken, want);
    free(taken);
    tui_editor_clear(e);
    paste_text(e, big);
    type(e, "\nabcdefghijklmnopqrstuvwxyz");
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_END);
    press(e, TUI_KEY_DOWN);
    press(e, TUI_KEY_UP);
    press(e, TUI_KEY_LEFT);
    type(e, "Q");
    taken = tui_editor_take(e);
    snprintf(want, sizeof want, "Q%s\nabcdefghijklmnopqrstuvwxyz", big);
    check_str("up/down never land inside a marker", taken, want);
    free(taken);
    tui_editor_clear(e);

    char *chars = malloc(1201);
    memset(chars, 'z', 1200);
    chars[1200] = 0;
    paste_text(e, chars);
    text_is("long single line collapsed ", e, "[paste #1 1200 chars]");
    taken = tui_editor_take(e);
    check_str("long paste expands", taken, chars);
    free(taken);
    free(chars);
    paste_text(e, "[paste #1 +20 lines]");
    take_is("typed lookalike marker is literal", e, "[paste #1 +20 lines]");
    tui_editor_clear(e);
    pass("editor paste markers");

    tui_editor_clear(e);
    tui_editor_set(e, "hello");
    cursor_is("set puts cursor at end", e, 80, 0, 7);
    tui_lines l = {0};
    int row, col;
    check_int("render ok", tui_editor_render(e, 80, &l, &row, &col), 0);
    lines_eq("render one line", &l, 1, "> hello");
    tui_lines_clear(&l);

    tui_editor_set(e, "aaa bbb ccc");
    check_int("render wrapped", tui_editor_render(e, 10, &l, &row, &col), 0);
    lines_eq("wrapped lines", &l, 2, "> aaa bbb", "  ccc");
    check_int("wrapped cursor row", row, 1);
    check_int("wrapped cursor col", col, 5);
    tui_lines_clear(&l);

    tui_editor_set(e, "ab\ncd");
    tui_editor_render(e, 80, &l, &row, &col);
    lines_eq("render multi-line prefixes", &l, 2, "> ab", "  cd");
    tui_lines_clear(&l);

    tui_editor_set(e, "\xE4\xB8\xAD\xE6\x96\x87x");
    cursor_is("cursor after wide chars", e, 80, 0, 7);
    press(e, TUI_KEY_LEFT);
    cursor_is("cursor between wide and narrow", e, 80, 0, 6);
    press(e, TUI_KEY_LEFT);
    cursor_is("cursor between wide chars", e, 80, 0, 4);

    tui_editor_set(e, "\xE4\xB8\xAD\xE6\x96\x87\xE5\xAD\x97\xE5\xAD\x97");
    tui_editor_render(e, 9, &l, &row, &col); /* wrap width 6: three wide chars a row */
    lines_eq("wide chars wrap", &l, 2, "> \xE4\xB8\xAD\xE6\x96\x87\xE5\xAD\x97", "  \xE5\xAD\x97");
    check_int("wide wrap cursor row", row, 1);
    check_int("wide wrap cursor col", col, 4);
    tui_lines_clear(&l);

    tui_editor_set(e, "abcdefgh");
    tui_editor_render(e, 8, &l, &row, &col); /* wrap width 5 */
    lines_eq("hard wrap in editor", &l, 2, "> abcde", "  fgh");
    check_int("cursor at end after hard wrap row", row, 1);
    check_int("cursor at end after hard wrap col", col, 5);
    tui_lines_clear(&l);
    tui_editor_set(e, "abcde");
    cursor_is("cursor at end of a full line stays on screen", e, 8, 0, 7);

    tui_editor_set(e, "ab\n");
    cursor_is("cursor on trailing empty line", e, 80, 1, 2);
    tui_editor_set(e, "");
    cursor_is("cursor in empty editor", e, 80, 0, 2);
    tui_editor_free(e);
    pass("editor render");
}

int main(void)
{
    test_width();
    test_wrap();
    test_decoder();
    test_render();
    test_editor();
    return 0;
}