xonecas.io
7814
Ta

tiny-c-agent / commit bc37a5d

feat: tui

xonecas2026-10-02 bc37a5d9c472883938f52be3672875fbe66bd1f6 parent b7399b7

22 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

Makefile+4−3
@@ -14,7 +14,8 @@ BUILD := build
1414 BIN := $(BUILD)/cage
1515
1616 PKGS := libuv libcurl ncursesw yyjson tree-sitter \
17- tree-sitter-javascript tree-sitter-bash
17+ tree-sitter-javascript tree-sitter-bash \
18+ tree-sitter-markdown tree-sitter-markdown-inline
1819
1920 TSJSON := third_party/tree-sitter-json
2021
@@ -23,11 +24,11 @@ OBJS := $(patsubst src/%.c,$(BUILD)/obj/%.o,$(SRCS))
2324 TSJSON_OBJ := $(BUILD)/obj/$(TSJSON)/src/parser.o
2425 DEPS := $(OBJS:.o=.d) $(TSJSON_OBJ:.o=.d)
2526
26-BASE := -std=$(STD) $(OPT)
27+BASE := -std=$(STD) $(OPT) -pthread
2728
2829 CPPFLAGS += -D_GNU_SOURCE -Isrc -I$(TSJSON)/src -MMD -MP
2930 CFLAGS += $(BASE) $(WARN) $(shell pkg-config --cflags $(PKGS))
30-LDLIBS += $(shell pkg-config --libs $(PKGS)) -lqjs
31+LDLIBS += $(shell pkg-config --libs $(PKGS)) -lqjs -pthread
3132
3233 .PHONY: all deps catalog run clean
3334 all: $(BIN)
src/codemode.c+3−0
@@ -258,6 +258,9 @@ cage_tool_result cage_runtime_run(cage_runtime *r, const char *script,
258258 cage_tool_output_fn out, void *out_user,
259259 const volatile bool *cancel) {
260260 cage_tool_result res = {0};
261+ // QuickJS records the stack top at runtime creation and checks overflow
262+ // against it. The TUI runs turns on a worker thread, so refresh it here.
263+ JS_UpdateStackTop(r->rt);
261264 r->out = out;
262265 r->out_user = out_user;
263266 r->cancel = cancel;
src/main.c+24−8
@@ -16,6 +16,7 @@
1616 #include "host.h"
1717 #include "resolve.h"
1818 #include "tool.h"
19+#include "tui/tui.h"
1920
2021 static volatile bool g_cancel;
2122
@@ -81,13 +82,8 @@ int main(int argc, char **argv) {
8182 }
8283 }
8384
84- if (!print_mode) {
85- fprintf(stderr, "interactive mode is not implemented; use -p PROMPT\n");
86- return 2;
87- }
88-
8985 char *stdin_prompt = NULL;
90- if (!prompt) {
86+ if (print_mode && !prompt) {
9187 if (isatty(fileno(stdin))) {
9288 fprintf(stderr, "-p requires a prompt\n");
9389 return 2;
@@ -125,14 +121,34 @@ int main(int argc, char **argv) {
125121 char cwd[PATH_MAX];
126122 if (!getcwd(cwd, sizeof cwd)) strcpy(cwd, ".");
127123
124+ cage_runtime *runtime = cage_runtime_new(model.supports_images);
125+ cage_hosts_register(runtime);
126+
127+ if (!print_mode) {
128+ // The TUI owns the terminal and its own signal handlers.
129+ cage_tui_config tc = {
130+ .cfg = cfg,
131+ .model = model,
132+ .system_prompt = system_prompt,
133+ .runtime = runtime,
134+ .cwd = cwd,
135+ };
136+ int code = cage_tui_run(&tc);
137+ cage_runtime_free(runtime);
138+ free(system_prompt);
139+ cage_config_free(cfg);
140+ free(err);
141+ free(stdin_prompt);
142+ curl_global_cleanup();
143+ return code;
144+ }
145+
128146 cage_session *session = cage_session_open(cfg->sessions_dir, cwd, prompt, &err);
129147 if (!session) {
130148 fprintf(stderr, "%s\n", err ? err : "session error");
131149 return 1;
132150 }
133151
134- cage_runtime *runtime = cage_runtime_new(model.supports_images);
135- cage_hosts_register(runtime);
136152 cage_tool tool = cage_codemode_tool();
137153
138154 signal(SIGINT, on_signal);
src/tui/buf.h+84−0
@@ -0,0 +1,84 @@
1+// cage TUI: a growable byte buffer, used to assemble styled output.
2+
3+#ifndef CAGE_TUI_BUF_H
4+#define CAGE_TUI_BUF_H
5+
6+#include <stdarg.h>
7+#include <stdio.h>
8+#include <stdlib.h>
9+#include <string.h>
10+
11+typedef struct {
12+ char *data;
13+ size_t len;
14+ size_t cap;
15+} tui_buf;
16+
17+static inline void buf_init(tui_buf *b) {
18+ b->data = NULL;
19+ b->len = 0;
20+ b->cap = 0;
21+}
22+
23+static inline void buf_free(tui_buf *b) {
24+ free(b->data);
25+ buf_init(b);
26+}
27+
28+static inline void buf_clear(tui_buf *b) {
29+ b->len = 0;
30+ if (b->data) b->data[0] = '\0';
31+}
32+
33+static inline void buf_reserve(tui_buf *b, size_t extra) {
34+ if (b->len + extra + 1 <= b->cap) return;
35+ size_t cap = b->cap ? b->cap : 64;
36+ while (cap < b->len + extra + 1) cap *= 2;
37+ b->data = realloc(b->data, cap);
38+ if (!b->data) abort();
39+ b->cap = cap;
40+}
41+
42+static inline void buf_add(tui_buf *b, const char *s, size_t n) {
43+ if (n == 0) return;
44+ buf_reserve(b, n);
45+ memcpy(b->data + b->len, s, n);
46+ b->len += n;
47+ b->data[b->len] = '\0';
48+}
49+
50+static inline void buf_adds(tui_buf *b, const char *s) {
51+ buf_add(b, s, strlen(s));
52+}
53+
54+static inline void buf_addc(tui_buf *b, char c) {
55+ buf_add(b, &c, 1);
56+}
57+
58+static inline void buf_addf(tui_buf *b, const char *fmt, ...) {
59+ va_list ap;
60+ va_start(ap, fmt);
61+ va_list ap2;
62+ va_copy(ap2, ap);
63+ int n = vsnprintf(NULL, 0, fmt, ap);
64+ va_end(ap);
65+ if (n < 0) {
66+ va_end(ap2);
67+ return;
68+ }
69+ buf_reserve(b, (size_t)n);
70+ vsnprintf(b->data + b->len, (size_t)n + 1, fmt, ap2);
71+ b->len += (size_t)n;
72+ va_end(ap2);
73+}
74+
75+// Hands the string to the caller and resets the buffer.
76+static inline char *buf_steal(tui_buf *b) {
77+ char *d = b->data;
78+ b->data = NULL;
79+ b->len = 0;
80+ b->cap = 0;
81+ return d;
82+}
83+
84+#endif
src/tui/commands.c+123−0
@@ -0,0 +1,123 @@
1+#include "commands.h"
2+
3+#include <stdlib.h>
4+#include <string.h>
5+
6+#include "buf.h"
7+#include "complete.h"
8+#include "theme.h"
9+
10+// The keybindings the TUI accepts, in the order /help prints them.
11+static const char *const KEYBINDINGS[][2] = {
12+ {"Enter", "submit"},
13+ {"Shift+Enter", "newline (Ctrl+J also works)"},
14+ {"Esc", "pause the turn at the next step boundary"},
15+ {"Ctrl+C", "cancel the turn"},
16+ {"Ctrl+D", "exit on an empty draft"},
17+ {"Tab", "complete command or path"},
18+};
19+
20+// One aligned `key description` block; the key column is dimmed.
21+static char *keyed(const char *key, const char *description, size_t width) {
22+ tui_buf b;
23+ buf_init(&b);
24+ buf_adds(&b, " ");
25+ tui_buf pad;
26+ buf_init(&pad);
27+ buf_adds(&pad, key);
28+ while (pad.len < width) buf_addc(&pad, ' ');
29+ fg_dim(&b, pad.data ? pad.data : "");
30+ buf_free(&pad);
31+ buf_adds(&b, " ");
32+ buf_adds(&b, description);
33+ return b.data ? buf_steal(&b) : strdup("");
34+}
35+
36+static void run_help(cage_command_ctx *ctx, const char *args) {
37+ (void)args;
38+ size_t ncmd = 2;
39+ const char *names[][2] = {
40+ {"/help", "list commands and keybindings"},
41+ {"/new", "start a new session"},
42+ };
43+ size_t width = 0;
44+ for (size_t i = 0; i < ncmd; i++)
45+ if (strlen(names[i][0]) > width) width = strlen(names[i][0]);
46+ for (size_t i = 0; i < sizeof KEYBINDINGS / sizeof KEYBINDINGS[0]; i++)
47+ if (strlen(KEYBINDINGS[i][0]) > width) width = strlen(KEYBINDINGS[i][0]);
48+
49+ ctx->write(ctx->user, strdup("commands"));
50+ for (size_t i = 0; i < ncmd; i++)
51+ ctx->write(ctx->user, keyed(names[i][0], names[i][1], width));
52+ ctx->write(ctx->user, strdup(""));
53+ ctx->write(ctx->user, strdup("keybindings"));
54+ for (size_t i = 0; i < sizeof KEYBINDINGS / sizeof KEYBINDINGS[0]; i++)
55+ ctx->write(ctx->user, keyed(KEYBINDINGS[i][0], KEYBINDINGS[i][1], width));
56+}
57+
58+static void run_new(cage_command_ctx *ctx, const char *args) {
59+ (void)args;
60+ ctx->new_session(ctx->user);
61+ ctx->write(ctx->user, strdup("new session"));
62+}
63+
64+static const cage_command COMMANDS[] = {
65+ {"help", "list commands and keybindings", run_help},
66+ {"new", "start a new session", run_new},
67+};
68+
69+const cage_command *cage_find_command(const char *text, const char **args) {
70+ if (text[0] != '/') return NULL;
71+ const char *p = text + 1;
72+ size_t n = 0;
73+ while (p[n] && p[n] != ' ' && p[n] != '\t' && p[n] != '\n') n++;
74+ for (size_t i = 0; i < sizeof COMMANDS / sizeof COMMANDS[0]; i++) {
75+ if (strlen(COMMANDS[i].name) == n && strncmp(COMMANDS[i].name, p, n) == 0) {
76+ const char *rest = p + n;
77+ while (*rest == ' ' || *rest == '\t') rest++;
78+ *args = rest;
79+ return &COMMANDS[i];
80+ }
81+ }
82+ return NULL;
83+}
84+
85+char *cage_complete_command(const char *draft) {
86+ if (draft[0] != '/') return NULL;
87+ for (const char *p = draft; *p; p++)
88+ if (*p == ' ' || *p == '\t' || *p == '\n') return NULL;
89+ const char *typed = draft + 1;
90+ size_t tn = strlen(typed);
91+ const cage_command *match = NULL;
92+ size_t nmatch = 0;
93+ char *shared = NULL;
94+ for (size_t i = 0; i < sizeof COMMANDS / sizeof COMMANDS[0]; i++) {
95+ if (strncmp(COMMANDS[i].name, typed, tn) != 0) continue;
96+ nmatch++;
97+ if (!match) match = &COMMANDS[i];
98+ if (!shared) shared = strdup(COMMANDS[i].name);
99+ else {
100+ char *next = cage_common_prefix(shared, COMMANDS[i].name);
101+ free(shared);
102+ shared = next;
103+ }
104+ }
105+ char *result = NULL;
106+ if (nmatch == 1) {
107+ tui_buf b;
108+ buf_init(&b);
109+ buf_addc(&b, '/');
110+ buf_adds(&b, match->name);
111+ result = b.data ? buf_steal(&b) : NULL;
112+ buf_free(&b);
113+ } else if (nmatch > 1 && strlen(shared) > tn) {
114+ tui_buf b;
115+ buf_init(&b);
116+ buf_addc(&b, '/');
117+ buf_adds(&b, shared);
118+ result = b.data ? buf_steal(&b) : NULL;
119+ buf_free(&b);
120+ }
121+ free(shared);
122+ return result;
123+}
src/tui/commands.h+27−0
@@ -0,0 +1,27 @@
1+// cage TUI commands: slash commands the editor submits.
2+
3+#ifndef CAGE_TUI_COMMANDS_H
4+#define CAGE_TUI_COMMANDS_H
5+
6+#include <stddef.h>
7+
8+// What a command may reach. The TUI provides the callbacks.
9+typedef struct {
10+ void *user; // opaque, the TUI
11+ void (*write)(void *user, char *line); // commits a styled line, taking ownership
12+ void (*new_session)(void *user); // starts a fresh session
13+} cage_command_ctx;
14+
15+typedef struct {
16+ const char *name; // no leading slash, lowercase
17+ const char *description; // one line, shown by /help
18+ void (*run)(cage_command_ctx *ctx, const char *args);
19+} cage_command;
20+
21+// `/name` for a known name, else NULL. `*args` receives the text after it.
22+const cage_command *cage_find_command(const char *text, const char **args);
23+
24+// Tab completion for a half-typed command name; NULL leaves the draft alone.
25+char *cage_complete_command(const char *draft);
26+
27+#endif
src/tui/complete.c+128−0
@@ -0,0 +1,128 @@
1+#include "complete.h"
2+
3+#include "buf.h"
4+
5+#include <dirent.h>
6+#include <limits.h>
7+#include <stdbool.h>
8+#include <stdio.h>
9+#include <stdlib.h>
10+#include <string.h>
11+#include <sys/stat.h>
12+
13+char *cage_common_prefix(const char *a, const char *b) {
14+ size_t i = 0;
15+ while (a[i] && b[i] && a[i] == b[i]) i++;
16+ char *out = malloc(i + 1);
17+ if (!out) abort();
18+ memcpy(out, a, i);
19+ out[i] = '\0';
20+ return out;
21+}
22+
23+// A word must carry path syntax to be completed: a leading `~`, `./`, `../`,
24+// `.`/`..`, `/`, or a word segment followed by a slash.
25+static bool path_like(const char *w) {
26+ if (w[0] == '~' || w[0] == '/') return true;
27+ if (w[0] == '.' && (w[1] == '\0' || w[1] == '/' ||
28+ (w[1] == '.' && (w[2] == '\0' || w[2] == '/'))))
29+ return true;
30+ const char *slash = strchr(w, '/');
31+ if (slash && slash != w) return true;
32+ return false;
33+}
34+
35+char *cage_complete_path(const char *word, const char *cwd) {
36+ if (!path_like(word)) return NULL;
37+
38+ const char *slashp = strrchr(word, '/');
39+ const char *prefix = slashp ? slashp + 1 : word;
40+ size_t prefix_len = strlen(prefix);
41+
42+ // Locate the directory to list.
43+ char dir[PATH_MAX];
44+ const char *home = getenv("HOME");
45+ if (word[0] == '~' && home) {
46+ size_t n = slashp ? (size_t)(slashp - (word + 1)) : strlen(word + 1);
47+ if (n >= sizeof dir) return NULL;
48+ snprintf(dir, sizeof dir, "%s%.*s", home, (int)n, word + 1);
49+ } else if (slashp) {
50+ size_t n = (size_t)(slashp - word);
51+ if (n == 0) {
52+ snprintf(dir, sizeof dir, "/");
53+ } else if (word[0] == '/') {
54+ if (n >= sizeof dir) return NULL;
55+ snprintf(dir, sizeof dir, "%.*s", (int)n, word);
56+ } else {
57+ if (n + strlen(cwd) + 2 >= sizeof dir) return NULL;
58+ snprintf(dir, sizeof dir, "%s/%.*s", cwd, (int)n, word);
59+ }
60+ } else {
61+ snprintf(dir, sizeof dir, "%s", cwd);
62+ }
63+
64+ DIR *d = opendir(dir);
65+ if (!d) return NULL;
66+
67+ // Candidates: matching names, dirs grown a trailing slash.
68+ char **cands = NULL;
69+ size_t n = 0, cap = 0;
70+ struct dirent *ent;
71+ while ((ent = readdir(d)) != NULL) {
72+ const char *name = ent->d_name;
73+ if (strncmp(name, prefix, prefix_len) != 0) continue;
74+ if (name[0] == '.' && prefix[0] != '.') continue;
75+ char path[PATH_MAX];
76+ bool isdir = false;
77+ if (snprintf(path, sizeof path, "%s/%s", dir, name) < (int)sizeof path) {
78+ struct stat st;
79+ if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) isdir = true;
80+ }
81+ size_t nl = strlen(name);
82+ char *cand = malloc(nl + 2);
83+ if (!cand) abort();
84+ memcpy(cand, name, nl);
85+ if (isdir) cand[nl++] = '/';
86+ cand[nl] = '\0';
87+ if (n == cap) {
88+ cap = cap ? cap * 2 : 16;
89+ cands = realloc(cands, cap * sizeof *cands);
90+ if (!cands) abort();
91+ }
92+ cands[n++] = cand;
93+ }
94+ closedir(d);
95+
96+ char *result = NULL;
97+ // The bytes before the prefix; equal to the word length minus the prefix.
98+ size_t keep = strlen(word) - prefix_len;
99+ if (n == 1) {
100+ if (strcmp(cands[0], prefix) != 0) {
101+ tui_buf b;
102+ buf_init(&b);
103+ buf_add(&b, word, keep);
104+ buf_adds(&b, cands[0]);
105+ result = b.data ? buf_steal(&b) : NULL;
106+ buf_free(&b);
107+ }
108+ } else if (n > 1) {
109+ char *shared = strdup(cands[0]);
110+ for (size_t i = 1; i < n; i++) {
111+ char *next = cage_common_prefix(shared, cands[i]);
112+ free(shared);
113+ shared = next;
114+ }
115+ if (strlen(shared) > prefix_len) {
116+ tui_buf b;
117+ buf_init(&b);
118+ buf_add(&b, word, keep);
119+ buf_adds(&b, shared);
120+ result = b.data ? buf_steal(&b) : NULL;
121+ buf_free(&b);
122+ }
123+ free(shared);
124+ }
125+ for (size_t i = 0; i < n; i++) free(cands[i]);
126+ free(cands);
127+ return result;
128+}
src/tui/complete.h+13−0
@@ -0,0 +1,13 @@
1+// cage TUI completion: path completion and the shared prefix helper.
2+
3+#ifndef CAGE_TUI_COMPLETE_H
4+#define CAGE_TUI_COMPLETE_H
5+
6+// Case-sensitive longest common prefix. Both inputs must be non-NULL.
7+char *cage_common_prefix(const char *a, const char *b);
8+
9+// Completes `word` as a file path. Returns malloc'd text, or NULL when there is
10+// nothing more to add.
11+char *cage_complete_path(const char *word, const char *cwd);
12+
13+#endif
src/tui/editor.c+645−0
@@ -0,0 +1,645 @@
1+#include "editor.h"
2+
3+#include <stdlib.h>
4+#include <string.h>
5+
6+#include "buf.h"
7+
8+#define TAB 4
9+
10+struct cage_editor {
11+ char **lines;
12+ size_t nlines;
13+ size_t row;
14+ size_t col; // code point index within the row
15+ int scroll;
16+ int width;
17+ bool masked;
18+ char *text; // cached join, valid until the next change
19+ bool text_dirty;
20+};
21+
22+static void *xmalloc(size_t n) {
23+ void *p = malloc(n);
24+ if (!p) abort();
25+ return p;
26+}
27+
28+static char *xstrdup(const char *s) {
29+ size_t n = strlen(s) + 1;
30+ char *p = xmalloc(n);
31+ memcpy(p, s, n);
32+ return p;
33+}
34+
35+static size_t cp_count(const char *s) {
36+ size_t n = 0, len = strlen(s);
37+ for (size_t i = 0; i < len;) {
38+ uint32_t cp;
39+ int b = cage_utf8_decode(s + i, len - i, &cp);
40+ if (b <= 0) break;
41+ i += (size_t)b;
42+ n++;
43+ }
44+ return n;
45+}
46+
47+// Byte offset of code point index `idx`, clamped to the end.
48+static size_t cp_off(const char *s, size_t idx) {
49+ size_t i = 0, n = 0, len = strlen(s);
50+ while (n < idx && i < len) {
51+ uint32_t cp;
52+ int b = cage_utf8_decode(s + i, len - i, &cp);
53+ if (b <= 0) break;
54+ i += (size_t)b;
55+ n++;
56+ }
57+ return i;
58+}
59+
60+// The code points [a, b) as a new string.
61+static char *cp_slice(const char *s, size_t a, size_t b) {
62+ size_t start = cp_off(s, a);
63+ size_t end = cp_off(s, b);
64+ size_t n = end > start ? end - start : 0;
65+ char *out = xmalloc(n + 1);
66+ memcpy(out, s + start, n);
67+ out[n] = '\0';
68+ return out;
69+}
70+
71+static bool cp_is_space(uint32_t cp) {
72+ return cp == ' ' || cp == '\t' || cp == '\n' || cp == '\r' || cp == '\v' || cp == '\f';
73+}
74+
75+// First code point index of the word before `col`.
76+static size_t word_start(const char *s, size_t col) {
77+ // Materialize code points for simple indexing.
78+ size_t len = strlen(s);
79+ size_t cap = 8, n = 0;
80+ uint32_t *cps = xmalloc(cap * sizeof *cps);
81+ for (size_t i = 0; i < len;) {
82+ uint32_t cp;
83+ int b = cage_utf8_decode(s + i, len - i, &cp);
84+ if (b <= 0) break;
85+ if (n == cap) {
86+ cap *= 2;
87+ cps = realloc(cps, cap * sizeof *cps);
88+ if (!cps) abort();
89+ }
90+ cps[n++] = cp;
91+ i += (size_t)b;
92+ }
93+ size_t i = col;
94+ while (i > 0 && cp_is_space(cps[i - 1])) i--;
95+ while (i > 0 && !cp_is_space(cps[i - 1])) i--;
96+ free(cps);
97+ return i;
98+}
99+
100+// One past the word at or after `col`.
101+static size_t word_end(const char *s, size_t col) {
102+ size_t len = strlen(s);
103+ size_t cap = 8, n = 0;
104+ uint32_t *cps = xmalloc(cap * sizeof *cps);
105+ for (size_t i = 0; i < len;) {
106+ uint32_t cp;
107+ int b = cage_utf8_decode(s + i, len - i, &cp);
108+ if (b <= 0) break;
109+ if (n == cap) {
110+ cap *= 2;
111+ cps = realloc(cps, cap * sizeof *cps);
112+ if (!cps) abort();
113+ }
114+ cps[n++] = cp;
115+ i += (size_t)b;
116+ }
117+ size_t i = col;
118+ while (i < n && cp_is_space(cps[i])) i++;
119+ while (i < n && !cp_is_space(cps[i])) i++;
120+ free(cps);
121+ return i;
122+}
123+
124+cage_editor *cage_editor_new(void) {
125+ cage_editor *e = calloc(1, sizeof *e);
126+ if (!e) abort();
127+ e->nlines = 1;
128+ e->lines = xmalloc(sizeof *e->lines);
129+ e->lines[0] = xstrdup("");
130+ e->width = 80;
131+ e->text_dirty = true;
132+ return e;
133+}
134+
135+void cage_editor_free(cage_editor *e) {
136+ if (!e) return;
137+ for (size_t i = 0; i < e->nlines; i++) free(e->lines[i]);
138+ free(e->lines);
139+ free(e->text);
140+ free(e);
141+}
142+
143+const char *cage_editor_text(cage_editor *e) {
144+ if (!e->text_dirty) return e->text;
145+ tui_buf b;
146+ buf_init(&b);
147+ for (size_t i = 0; i < e->nlines; i++) {
148+ if (i) buf_addc(&b, '\n');
149+ buf_adds(&b, e->lines[i]);
150+ }
151+ free(e->text);
152+ e->text = b.data ? buf_steal(&b) : xstrdup("");
153+ buf_free(&b);
154+ e->text_dirty = false;
155+ return e->text;
156+}
157+
158+void cage_editor_set_masked(cage_editor *e, bool masked) {
159+ e->masked = masked;
160+}
161+
162+void cage_editor_clear(cage_editor *e) {
163+ for (size_t i = 0; i < e->nlines; i++) free(e->lines[i]);
164+ e->nlines = 1;
165+ e->lines = realloc(e->lines, sizeof *e->lines);
166+ e->lines[0] = xstrdup("");
167+ e->row = 0;
168+ e->col = 0;
169+ e->scroll = 0;
170+ e->text_dirty = true;
171+}
172+
173+void cage_editor_set_text(cage_editor *e, const char *text) {
174+ for (size_t i = 0; i < e->nlines; i++) free(e->lines[i]);
175+ // Split on newline.
176+ size_t cap = 8, n = 0;
177+ char **lines = xmalloc(cap * sizeof *lines);
178+ const char *p = text;
179+ for (;;) {
180+ const char *nl = strchr(p, '\n');
181+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
182+ char *line = xmalloc(len + 1);
183+ memcpy(line, p, len);
184+ line[len] = '\0';
185+ if (n == cap) {
186+ cap *= 2;
187+ lines = realloc(lines, cap * sizeof *lines);
188+ if (!lines) abort();
189+ }
190+ lines[n++] = line;
191+ if (!nl) break;
192+ p = nl + 1;
193+ }
194+ free(e->lines);
195+ e->lines = lines;
196+ e->nlines = n;
197+ e->row = n - 1;
198+ e->col = cp_count(e->lines[e->row]);
199+ e->scroll = 0;
200+ e->text_dirty = true;
201+}
202+
203+static char *display_line(cage_editor *e, size_t line) {
204+ if (!e->masked) return xstrdup(e->lines[line]);
205+ size_t n = cp_count(e->lines[line]);
206+ char *out = xmalloc(n + 1);
207+ memset(out, '*', n);
208+ out[n] = '\0';
209+ return out;
210+}
211+
212+// Display column of every code point boundary in `line`, tabs expanded.
213+static int *cells_of(const char *line, size_t *n_out) {
214+ size_t len = strlen(line);
215+ size_t cap = 16, n = 0;
216+ int *out = xmalloc(cap * sizeof *out);
217+ out[n++] = 0;
218+ int col = 0;
219+ for (size_t i = 0; i < len;) {
220+ uint32_t cp;
221+ int b = cage_utf8_decode(line + i, len - i, &cp);
222+ if (b <= 0) break;
223+ if (cp == '\t') col += TAB - (col % TAB);
224+ else col += cage_char_width(cp);
225+ if (n == cap) {
226+ cap *= 2;
227+ out = realloc(out, cap * sizeof *out);
228+ if (!out) abort();
229+ }
230+ out[n++] = col;
231+ i += (size_t)b;
232+ }
233+ *n_out = n;
234+ return out;
235+}
236+
237+// The caret column nearest `cell`, never past the end of the line.
238+static size_t col_at_cell(const char *line, int cell) {
239+ size_t n;
240+ int *cells = cells_of(line, &n);
241+ size_t i = n - 1;
242+ while (i > 0 && cells[i] > cell) i--;
243+ free(cells);
244+ return i;
245+}
246+
247+static void caret(cage_editor *e, int *row_out, int *col_out) {
248+ char *line = display_line(e, e->row);
249+ char *expanded = cage_expand_tabs(line, TAB);
250+ size_t nrows;
251+ char **chunks = cage_wrap_line(expanded, e->width, &nrows);
252+ size_t ncells;
253+ int *cells = cells_of(line, &ncells);
254+ int cell = cells[e->col < ncells ? e->col : ncells - 1];
255+ free(cells);
256+ int row = cell / e->width;
257+ if (row >= (int)nrows) {
258+ *row_out = (int)nrows - 1;
259+ *col_out = cage_display_width(chunks[nrows - 1]);
260+ } else {
261+ *row_out = row;
262+ *col_out = cell - row * e->width;
263+ }
264+ for (size_t i = 0; i < nrows; i++) free(chunks[i]);
265+ free(chunks);
266+ free(expanded);
267+ free(line);
268+}
269+
270+static void insert_text(cage_editor *e, const char *text) {
271+ // Split `text` on newlines.
272+ size_t nparts = 1;
273+ for (const char *p = text; *p; p++)
274+ if (*p == '\n') nparts++;
275+
276+ char *line = e->lines[e->row];
277+ char *before = cp_slice(line, 0, e->col);
278+ char *after = cp_slice(line, e->col, cp_count(line));
279+
280+ if (nparts == 1) {
281+ tui_buf b;
282+ buf_init(&b);
283+ buf_adds(&b, before);
284+ buf_adds(&b, text);
285+ buf_adds(&b, after);
286+ free(e->lines[e->row]);
287+ e->lines[e->row] = b.data ? buf_steal(&b) : xstrdup("");
288+ buf_free(&b);
289+ e->col += cp_count(text);
290+ e->text_dirty = true;
291+ free(before);
292+ free(after);
293+ return;
294+ }
295+
296+ // Build the replacement lines.
297+ size_t cap = 8, n = 0;
298+ char **parts = xmalloc(cap * sizeof *parts);
299+ const char *p = text;
300+ for (;;) {
301+ const char *nl = strchr(p, '\n');
302+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
303+ char *part = xmalloc(len + 1);
304+ memcpy(part, p, len);
305+ part[len] = '\0';
306+ if (n == cap) {
307+ cap *= 2;
308+ parts = realloc(parts, cap * sizeof *parts);
309+ if (!parts) abort();
310+ }
311+ parts[n++] = part;
312+ if (!nl) break;
313+ p = nl + 1;
314+ }
315+
316+ tui_buf head;
317+ buf_init(&head);
318+ buf_adds(&head, before);
319+ buf_adds(&head, parts[0]);
320+ tui_buf tail;
321+ buf_init(&tail);
322+ buf_adds(&tail, parts[n - 1]);
323+ buf_adds(&tail, after);
324+ size_t caret_col = cp_count(parts[n - 1]);
325+ free(parts[0]);
326+ free(parts[n - 1]);
327+
328+ // New line array: [0, row) + head + middle parts + tail + (row, end).
329+ char **nl = xmalloc((e->nlines + 1) * sizeof *nl);
330+ size_t k = 0;
331+ for (size_t i = 0; i < e->row; i++) nl[k++] = e->lines[i];
332+ nl[k++] = head.data ? buf_steal(&head) : xstrdup("");
333+ buf_free(&head);
334+ for (size_t i = 1; i + 1 < n; i++) nl[k++] = parts[i];
335+ nl[k++] = tail.data ? buf_steal(&tail) : xstrdup("");
336+ buf_free(&tail);
337+ for (size_t i = e->row + 1; i < e->nlines; i++) nl[k++] = e->lines[i];
338+ free(e->lines);
339+ e->lines = nl;
340+ e->nlines = k;
341+ e->row += n - 1;
342+ e->col = caret_col;
343+ free(parts);
344+ free(before);
345+ free(after);
346+ e->text_dirty = true;
347+}
348+
349+static void backspace(cage_editor *e) {
350+ if (e->col > 0) {
351+ char *line = e->lines[e->row];
352+ char *before = cp_slice(line, 0, e->col - 1);
353+ char *after = cp_slice(line, e->col, cp_count(line));
354+ tui_buf b;
355+ buf_init(&b);
356+ buf_adds(&b, before);
357+ buf_adds(&b, after);
358+ free(line);
359+ e->lines[e->row] = b.data ? buf_steal(&b) : xstrdup("");
360+ buf_free(&b);
361+ free(before);
362+ free(after);
363+ e->col--;
364+ e->text_dirty = true;
365+ return;
366+ }
367+ if (e->row > 0) {
368+ size_t prev = cp_count(e->lines[e->row - 1]);
369+ tui_buf b;
370+ buf_init(&b);
371+ buf_adds(&b, e->lines[e->row - 1]);
372+ buf_adds(&b, e->lines[e->row]);
373+ free(e->lines[e->row - 1]);
374+ e->lines[e->row - 1] = b.data ? buf_steal(&b) : xstrdup("");
375+ buf_free(&b);
376+ free(e->lines[e->row]);
377+ for (size_t i = e->row; i + 1 < e->nlines; i++) e->lines[i] = e->lines[i + 1];
378+ e->nlines--;
379+ e->row--;
380+ e->col = prev;
381+ e->text_dirty = true;
382+ }
383+}
384+
385+static void delete_forward(cage_editor *e) {
386+ char *line = e->lines[e->row];
387+ size_t n = cp_count(line);
388+ if (e->col < n) {
389+ char *before = cp_slice(line, 0, e->col);
390+ char *after = cp_slice(line, e->col + 1, n);
391+ tui_buf b;
392+ buf_init(&b);
393+ buf_adds(&b, before);
394+ buf_adds(&b, after);
395+ free(line);
396+ e->lines[e->row] = b.data ? buf_steal(&b) : xstrdup("");
397+ buf_free(&b);
398+ free(before);
399+ free(after);
400+ e->text_dirty = true;
401+ return;
402+ }
403+ if (e->row + 1 < e->nlines) {
404+ tui_buf b;
405+ buf_init(&b);
406+ buf_adds(&b, e->lines[e->row]);
407+ buf_adds(&b, e->lines[e->row + 1]);
408+ free(e->lines[e->row]);
409+ e->lines[e->row] = b.data ? buf_steal(&b) : xstrdup("");
410+ buf_free(&b);
411+ free(e->lines[e->row + 1]);
412+ for (size_t i = e->row + 1; i + 1 < e->nlines; i++) e->lines[i] = e->lines[i + 1];
413+ e->nlines--;
414+ e->text_dirty = true;
415+ }
416+}
417+
418+cage_edit_result cage_editor_handle(cage_editor *e, const cage_key *key) {
419+ switch (key->type) {
420+ case CAGE_KEY_SUBMIT:
421+ return CAGE_EDIT_SUBMIT;
422+ case CAGE_KEY_NEWLINE:
423+ insert_text(e, "\n");
424+ return CAGE_EDIT_CHANGED;
425+ case CAGE_KEY_TEXT:
426+ insert_text(e, key->text ? key->text : "");
427+ return CAGE_EDIT_CHANGED;
428+ case CAGE_KEY_BACKSPACE:
429+ backspace(e);
430+ return CAGE_EDIT_CHANGED;
431+ case CAGE_KEY_DELETE:
432+ delete_forward(e);
433+ return CAGE_EDIT_CHANGED;
434+ case CAGE_KEY_WORD_BACK: {
435+ char *line = e->lines[e->row];
436+ size_t start = word_start(line, e->col);
437+ char *before = cp_slice(line, 0, start);
438+ char *after = cp_slice(line, e->col, cp_count(line));
439+ tui_buf b;
440+ buf_init(&b);
441+ buf_adds(&b, before);
442+ buf_adds(&b, after);
443+ free(line);
444+ e->lines[e->row] = b.data ? buf_steal(&b) : xstrdup("");
445+ buf_free(&b);
446+ free(before);
447+ free(after);
448+ e->col = start;
449+ e->text_dirty = true;
450+ return CAGE_EDIT_CHANGED;
451+ }
452+ case CAGE_KEY_LEFT:
453+ if (e->col > 0) e->col--;
454+ else if (e->row > 0) {
455+ e->row--;
456+ e->col = cp_count(e->lines[e->row]);
457+ }
458+ return CAGE_EDIT_CHANGED;
459+ case CAGE_KEY_RIGHT:
460+ if (e->col < cp_count(e->lines[e->row])) e->col++;
461+ else if (e->row + 1 < e->nlines) {
462+ e->row++;
463+ e->col = 0;
464+ }
465+ return CAGE_EDIT_CHANGED;
466+ case CAGE_KEY_WORD_LEFT: {
467+ size_t start = word_start(e->lines[e->row], e->col);
468+ if (start != e->col) {
469+ e->col = start;
470+ return CAGE_EDIT_CHANGED;
471+ }
472+ if (e->row == 0) return CAGE_EDIT_CHANGED;
473+ e->row--;
474+ size_t prev = cp_count(e->lines[e->row]);
475+ e->col = word_start(e->lines[e->row], prev);
476+ return CAGE_EDIT_CHANGED;
477+ }
478+ case CAGE_KEY_WORD_RIGHT: {
479+ size_t end = word_end(e->lines[e->row], e->col);
480+ if (end != e->col) {
481+ e->col = end;
482+ return CAGE_EDIT_CHANGED;
483+ }
484+ if (e->row + 1 >= e->nlines) return CAGE_EDIT_CHANGED;
485+ e->row++;
486+ e->col = word_end(e->lines[e->row], 0);
487+ return CAGE_EDIT_CHANGED;
488+ }
489+ case CAGE_KEY_UP: {
490+ int crow, ccol;
491+ caret(e, &crow, &ccol);
492+ if (crow > 0) {
493+ size_t n;
494+ int *cells = cells_of(e->lines[e->row], &n);
495+ int cell = cells[e->col < n ? e->col : n - 1] - e->width;
496+ free(cells);
497+ e->col = col_at_cell(e->lines[e->row], cell);
498+ return CAGE_EDIT_CHANGED;
499+ }
500+ if (e->row == 0) return CAGE_EDIT_CHANGED;
501+ e->row--;
502+ char *expanded = cage_expand_tabs(e->lines[e->row], TAB);
503+ size_t nrows;
504+ char **chunks = cage_wrap_line(expanded, e->width, &nrows);
505+ int last_row = (int)nrows - 1;
506+ for (size_t i = 0; i < nrows; i++) free(chunks[i]);
507+ free(chunks);
508+ free(expanded);
509+ e->col = col_at_cell(e->lines[e->row], last_row * e->width + ccol);
510+ return CAGE_EDIT_CHANGED;
511+ }
512+ case CAGE_KEY_DOWN: {
513+ int crow, ccol;
514+ caret(e, &crow, &ccol);
515+ char *expanded = cage_expand_tabs(e->lines[e->row], TAB);
516+ size_t nrows;
517+ char **chunks = cage_wrap_line(expanded, e->width, &nrows);
518+ for (size_t i = 0; i < nrows; i++) free(chunks[i]);
519+ free(chunks);
520+ free(expanded);
521+ if (crow < (int)nrows - 1) {
522+ size_t n;
523+ int *cells = cells_of(e->lines[e->row], &n);
524+ int cell = cells[e->col < n ? e->col : n - 1] + e->width;
525+ free(cells);
Cut short: this commit's diff is over 1000 lines.
src/tui/editor.h+48−0
Cut short: this commit's diff is over 1000 lines.
src/tui/highlight.c+436−0
Cut short: this commit's diff is over 1000 lines.
src/tui/highlight.h+18−0
Cut short: this commit's diff is over 1000 lines.
src/tui/stream.c+375−0
Cut short: this commit's diff is over 1000 lines.
src/tui/stream.h+54−0
Cut short: this commit's diff is over 1000 lines.
src/tui/term.c+602−0
Cut short: this commit's diff is over 1000 lines.
src/tui/term.h+79−0
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.c+180−0
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.h+79−0
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.c+1325−0
Cut short: this commit's diff is over 1000 lines.
src/tui/tui.h+26−0
Cut short: this commit's diff is over 1000 lines.
src/tui/usage.c+65−0
Cut short: this commit's diff is over 1000 lines.
src/tui/usage.h+14−0
Cut short: this commit's diff is over 1000 lines.