xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / tui / editor.zig

13.6 KB
1const std = @import("std");
2const render = @import("render.zig");
3const input = @import("input.zig");
4const utf8 = @import("../text.zig");
5
6const TAB = 4;
7
8fn isSpace(cp: u21) bool {
9    return cp == ' ' or cp == '\t' or cp == '\n' or cp == '\r' or cp == 0x0b or cp == 0x0c or cp == 0xa0;
10}
11
12fn cpAt(line: []const u8, col: usize) u21 {
13    var i: usize = 0;
14    var count: usize = 0;
15    while (utf8.decodeAt(line, i)) |d| {
16        if (count == col) return d.cp;
17        i += d.len;
18        count += 1;
19    }
20    return 0;
21}
22
23fn byteOf(line: []const u8, col: usize) usize {
24    var i: usize = 0;
25    var count: usize = 0;
26    while (count < col) : (count += 1) {
27        i += (utf8.decodeAt(line, i) orelse break).len;
28    }
29    return i;
30}
31
32fn sub(a: std.mem.Allocator, line: []const u8, start: usize, end: usize) []const u8 {
33    const s = byteOf(line, start);
34    const e = byteOf(line, end);
35    return a.dupe(u8, line[s..e]) catch "";
36}
37
38fn wordStart(line: []const u8, col: usize) usize {
39    var i = col;
40    while (i > 0 and isSpace(cpAt(line, i - 1))) i -= 1;
41    while (i > 0 and !isSpace(cpAt(line, i - 1))) i -= 1;
42    return i;
43}
44
45fn wordEnd(line: []const u8, col: usize) usize {
46    const n = utf8.cpLen(line);
47    var i = col;
48    while (i < n and isSpace(cpAt(line, i))) i += 1;
49    while (i < n and !isSpace(cpAt(line, i))) i += 1;
50    return i;
51}
52
53pub const Render = struct {
54    rows: []const []const u8,
55    cursor_row: usize,
56    cursor_col: usize,
57};
58
59pub const Action = enum { submit, changed, none };
60
61const Line = std.ArrayList(u8);
62
63pub const Editor = struct {
64    lines: std.ArrayList(Line) = .empty,
65    row: usize = 0,
66    col: usize = 0,
67    width: usize = 80,
68    arena: std.heap.ArenaAllocator,
69    a: std.mem.Allocator = undefined,
70    s: std.mem.Allocator = undefined,
71
72    pub fn init(backing: std.mem.Allocator) Editor {
73        return .{ .arena = std.heap.ArenaAllocator.init(backing) };
74    }
75
76    pub fn bind(self: *Editor) void {
77        self.a = self.arena.allocator();
78        self.lines = .empty;
79        self.lines.append(self.a, .empty) catch {};
80    }
81
82    pub fn contents(self: *Editor) []const u8 {
83        var out: std.ArrayList(u8) = .empty;
84        for (self.lines.items, 0..) |line, i| {
85            if (i > 0) out.append(self.a, '\n') catch {};
86            out.appendSlice(self.a, line.items) catch {};
87        }
88        return out.items;
89    }
90
91    pub fn clear(self: *Editor) void {
92        _ = self.arena.reset(.retain_capacity);
93        self.a = self.arena.allocator();
94        self.lines = .empty;
95        self.lines.append(self.a, .empty) catch {};
96        self.row = 0;
97        self.col = 0;
98    }
99
100    pub fn setText(self: *Editor, draft: []const u8) void {
101        self.lines = .empty;
102        var it = std.mem.splitScalar(u8, draft, '\n');
103        while (it.next()) |text| {
104            var line: Line = .empty;
105            line.appendSlice(self.a, text) catch {};
106            self.lines.append(self.a, line) catch {};
107        }
108        if (self.lines.items.len == 0) self.lines.append(self.a, .empty) catch {};
109        self.row = self.lines.items.len - 1;
110        self.col = utf8.cpLen(self.lines.items[self.row].items);
111    }
112
113    pub fn handle(self: *Editor, key: input.Key) Action {
114        switch (key) {
115            .submit => return .submit,
116            .newline => {
117                self.insert("\n");
118                return .changed;
119            },
120            .text => |t| {
121                self.insert(t);
122                return .changed;
123            },
124            .backspace => {
125                self.backspace();
126                return .changed;
127            },
128            .delete => {
129                self.deleteForward();
130                return .changed;
131            },
132            .word_back => {
133                self.wordBack();
134                return .changed;
135            },
136            .left => {
137                self.left();
138                return .changed;
139            },
140            .right => {
141                self.right();
142                return .changed;
143            },
144            .word_left => {
145                self.wordLeft();
146                return .changed;
147            },
148            .word_right => {
149                self.wordRight();
150                return .changed;
151            },
152            .up => {
153                self.up();
154                return .changed;
155            },
156            .down => {
157                self.down();
158                return .changed;
159            },
160            .home => {
161                self.col = 0;
162                return .changed;
163            },
164            .end => {
165                self.col = utf8.cpLen(self.lines.items[self.row].items);
166                return .changed;
167            },
168            .doc_start => {
169                self.row = 0;
170                self.col = 0;
171                return .changed;
172            },
173            .doc_end => {
174                self.row = self.lines.items.len - 1;
175                self.col = utf8.cpLen(self.lines.items[self.row].items);
176                return .changed;
177            },
178            else => return .none,
179        }
180    }
181
182    fn cells(self: *Editor, line: []const u8) []usize {
183        var out: std.ArrayList(usize) = .empty;
184        out.append(self.s, 0) catch {};
185        var col: usize = 0;
186        var i: usize = 0;
187        while (render.nextCluster(line, i)) |cluster| {
188            const tab = cluster.text.len == 1 and cluster.text[0] == '\t';
189            const advance = if (tab) TAB - (col % TAB) else cluster.width;
190            const cps = utf8.cpLen(cluster.text);
191            col += advance;
192            var m: usize = 0;
193            while (m < cps) : (m += 1) out.append(self.s, col) catch {};
194            i += cluster.text.len;
195        }
196        if (out.items.len == 0) out.append(self.s, 0) catch {};
197        return out.items;
198    }
199
200    fn colAtCell(self: *Editor, line: []const u8, cell: usize) usize {
201        const cs = self.cells(line);
202        var i = cs.len - 1;
203        while (i > 0 and cs[i] > cell) i -= 1;
204        return i;
205    }
206
207    fn caret(self: *Editor) struct { row: usize, col: usize } {
208        const width = @max(self.width, 1);
209        const line = self.lines.items[self.row].items;
210        const cell = self.cells(line)[self.col];
211        const rows = render.wrapLine(self.s, render.expandTabs(self.s, line, TAB), width);
212        var used: usize = 0;
213        for (rows, 0..) |r, i| {
214            const w = render.displayWidth(r);
215            if (cell < used + w) return .{ .row = i, .col = cell - used };
216            used += w;
217        }
218        const last = render.displayWidth(rows[rows.len - 1]);
219        return .{ .row = rows.len - 1, .col = @min(last, width - 1) };
220    }
221
222    pub fn layout(self: *Editor, width: usize, max_rows: usize) Render {
223        self.width = @max(1, width);
224        const view = @max(1, max_rows);
225        const n = self.lines.items.len;
226        const heights = self.s.alloc(usize, n) catch return .{ .rows = &.{}, .cursor_row = 0, .cursor_col = 0 };
227        var caret_line: usize = 0;
228        var caret_cell: usize = 0;
229        for (self.lines.items, 0..) |line, i| {
230            heights[i] = render.physicalRows(render.expandTabs(self.s, line.items, TAB), self.width);
231            if (i == self.row) {
232                caret_line = i;
233                caret_cell = self.cells(line.items)[self.col];
234            }
235        }
236        var start = caret_line;
237        var used = heights[caret_line];
238        while (start > 0 and used + heights[start - 1] <= view) {
239            start -= 1;
240            used += heights[start];
241        }
242        var end = caret_line + 1;
243        while (end < n and used + heights[end] <= view) {
244            used += heights[end];
245            end += 1;
246        }
247        var rows: std.ArrayList([]const u8) = .empty;
248        for (self.lines.items[start..end]) |line| rows.append(self.s, line.items) catch {};
249        return .{
250            .rows = rows.items,
251            .cursor_row = caret_line - start,
252            .cursor_col = caret_cell,
253        };
254    }
255
256    fn insert(self: *Editor, draft: []const u8) void {
257        const line = &self.lines.items[self.row];
258        const at = byteOf(line.items, self.col);
259        if (std.mem.indexOfScalar(u8, draft, '\n') == null) {
260            line.insertSlice(self.a, at, draft) catch {};
261            self.col += utf8.cpLen(draft);
262            return;
263        }
264        const tail = self.a.dupe(u8, line.items[at..]) catch "";
265        line.shrinkRetainingCapacity(at);
266        var parts = std.mem.splitScalar(u8, draft, '\n');
267        line.appendSlice(self.a, parts.next() orelse "") catch {};
268        var fresh: std.ArrayList(Line) = .empty;
269        while (parts.next()) |text| {
270            var l: Line = .empty;
271            l.appendSlice(self.a, text) catch {};
272            fresh.append(self.a, l) catch {};
273        }
274        const lasti = fresh.items.len - 1;
275        const anchor = utf8.cpLen(fresh.items[lasti].items);
276        fresh.items[lasti].appendSlice(self.a, tail) catch {};
277        var at_row = self.row + 1;
278        for (fresh.items) |l| {
279            self.lines.insert(self.a, at_row, l) catch {};
280            at_row += 1;
281        }
282        self.row = at_row - 1;
283        self.col = anchor;
284    }
285
286    fn replaceCols(self: *Editor, line: *Line, from: usize, to: usize, text: []const u8) void {
287        const start = byteOf(line.items, from);
288        const end = byteOf(line.items, to);
289        line.replaceRange(self.a, start, end - start, text) catch {};
290    }
291
292    fn backspace(self: *Editor) void {
293        if (self.col > 0) {
294            self.replaceCols(&self.lines.items[self.row], self.col - 1, self.col, "");
295            self.col -= 1;
296            return;
297        }
298        if (self.row > 0) {
299            const prev = &self.lines.items[self.row - 1];
300            const cur = self.lines.items[self.row];
301            const previous = utf8.cpLen(prev.items);
302            prev.appendSlice(self.a, cur.items) catch {};
303            _ = self.lines.orderedRemove(self.row);
304            self.row -= 1;
305            self.col = previous;
306        }
307    }
308
309    fn deleteForward(self: *Editor) void {
310        const line = &self.lines.items[self.row];
311        const n = utf8.cpLen(line.items);
312        if (self.col < n) {
313            self.replaceCols(line, self.col, self.col + 1, "");
314            return;
315        }
316        if (self.row < self.lines.items.len - 1) {
317            const cur = &self.lines.items[self.row];
318            const next = self.lines.items[self.row + 1];
319            cur.appendSlice(self.a, next.items) catch {};
320            _ = self.lines.orderedRemove(self.row + 1);
321        }
322    }
323
324    fn left(self: *Editor) void {
325        if (self.col > 0) {
326            self.col -= 1;
327        } else if (self.row > 0) {
328            self.row -= 1;
329            self.col = utf8.cpLen(self.lines.items[self.row].items);
330        }
331    }
332
333    fn right(self: *Editor) void {
334        if (self.col < utf8.cpLen(self.lines.items[self.row].items)) {
335            self.col += 1;
336        } else if (self.row < self.lines.items.len - 1) {
337            self.row += 1;
338            self.col = 0;
339        }
340    }
341
342    fn up(self: *Editor) void {
343        const width = @max(self.width, 1);
344        const line = self.lines.items[self.row].items;
345        const ct = self.caret();
346        if (ct.row > 0) {
347            self.col = self.colAtCell(line, self.cells(line)[self.col] - width);
348            return;
349        }
350        if (self.row == 0) return;
351        self.row -= 1;
352        const previous = self.lines.items[self.row].items;
353        const expanded = render.expandTabs(self.s, previous, TAB);
354        const last_row = render.wrapLine(self.s, expanded, width).len - 1;
355        self.col = self.colAtCell(previous, last_row * width + ct.col);
356    }
357
358    fn down(self: *Editor) void {
359        const width = @max(self.width, 1);
360        const line = self.lines.items[self.row].items;
361        const ct = self.caret();
362        const expanded = render.expandTabs(self.s, line, TAB);
363        if (ct.row < render.wrapLine(self.s, expanded, width).len - 1) {
364            self.col = self.colAtCell(line, self.cells(line)[self.col] + width);
365            return;
366        }
367        if (self.row == self.lines.items.len - 1) return;
368        self.row += 1;
369        self.col = self.colAtCell(self.lines.items[self.row].items, ct.col);
370    }
371
372    fn wordLeft(self: *Editor) void {
373        const line = self.lines.items[self.row].items;
374        const start = wordStart(line, self.col);
375        if (start != self.col) {
376            self.col = start;
377            return;
378        }
379        if (self.row == 0) return;
380        self.row -= 1;
381        const previous = self.lines.items[self.row].items;
382        self.col = wordStart(previous, utf8.cpLen(previous));
383    }
384
385    fn wordRight(self: *Editor) void {
386        const line = self.lines.items[self.row].items;
387        const end = wordEnd(line, self.col);
388        if (end != self.col) {
389            self.col = end;
390            return;
391        }
392        if (self.row == self.lines.items.len - 1) return;
393        self.row += 1;
394        self.col = wordEnd(self.lines.items[self.row].items, 0);
395    }
396
397    fn wordBack(self: *Editor) void {
398        const start = wordStart(self.lines.items[self.row].items, self.col);
399        self.replaceCols(&self.lines.items[self.row], start, self.col, "");
400        self.col = start;
401    }
402
403    pub fn completeWord(self: *Editor, step: *const fn (word: []const u8) ?[]const u8) bool {
404        const line = &self.lines.items[self.row];
405        const start = wordStart(line.items, self.col);
406        if (start == self.col) return false;
407        if (isSpace(cpAt(line.items, self.col - 1))) return false;
408        const word = sub(self.s, line.items, start, self.col);
409        const completed = step(word) orelse return false;
410        self.replaceCols(line, start, self.col, completed);
411        self.col = start + utf8.cpLen(completed);
412        return true;
413    }
414};