xonecas.io
79113
Ma

mini-coding-agent / commit 4b86cf8

fix: code org and dedup

xonecas2026-10-27 4b86cf8aaa8a66d3c0d8b67954f3598b78b72c99 parent 09de22c

14 files changed

src/api.zig+3−10
@@ -3,6 +3,7 @@ const message_mod = @import("message.zig");
33 const models = @import("models.zig");
44 const http = @import("http.zig");
55 const time = @import("time.zig");
6+const json = @import("json.zig");
67
78 pub const Event = union(enum) {
89 retry: struct { attempt: u32, total: u32, delay_ms: u64, reason: []const u8 },
@@ -343,14 +344,6 @@ pub fn finishUsage(msg: *message_mod.AssistantMessage, model: *const models.Mode
343344 msg.usage = u;
344345 }
345346
346-pub fn stringField(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
347- const v = obj.get(key) orelse return null;
348- return switch (v) {
349- .string => |s| if (s.len > 0) s else null,
350- else => null,
351- };
352-}
353-
354347 pub const ToolsForm = struct {
355348 open: []const u8,
356349 entry: []const u8,
@@ -394,9 +387,9 @@ pub fn writeTools(w: *std.Io.Writer, a: std.mem.Allocator, tools_json: []const u
394387
395388 fn writeToolBody(w: *std.Io.Writer, obj: std.json.ObjectMap, params_key: []const u8) !void {
396389 try w.writeAll("\"name\":");
397- try std.json.Stringify.encodeJsonString(stringField(obj, "name") orelse "", .{}, w);
390+ try std.json.Stringify.encodeJsonString(json.stringField(obj, "name") orelse "", .{}, w);
398391 try w.writeAll(",\"description\":");
399- try std.json.Stringify.encodeJsonString(stringField(obj, "description") orelse "", .{}, w);
392+ try std.json.Stringify.encodeJsonString(json.stringField(obj, "description") orelse "", .{}, w);
400393 try w.writeAll(",\"");
401394 try w.writeAll(params_key);
402395 try w.writeAll("\":");
src/http.zig+6−4
@@ -152,9 +152,11 @@ pub fn get(
152152 var attempt: usize = 0;
153153 while (true) : (attempt += 1) {
154154 var out = Attempt{};
155- if (getOnce(a, url, headers, cancel, &out)) |body| return body else |e| out.err = e;
156- const e = out.err orelse error.ReadFailed;
157- if (attempt + 1 >= retry.attempts + 1 or !retryable(e, out.status)) return e;
155+ if (getOnce(a, url, headers, cancel, &out)) |body| {
156+ return body;
157+ } else |e| {
158+ if (attempt >= retry.attempts or !retryable(e, out.status)) return e;
159+ }
158160 try pause(cancel, backoff(retry.base_ms, attempt));
159161 }
160162 }
@@ -192,7 +194,7 @@ pub fn postSse(
192194 err_body.* = null;
193195 const out = postOnce(a, url, headers, body, handler, cancel, err_body, retry.idle_ms);
194196 const e = out.err orelse return;
195- if (out.sent or attempt + 1 >= retry.attempts + 1 or !retryable(e, out.status)) return e;
197+ if (out.sent or attempt >= retry.attempts or !retryable(e, out.status)) return e;
196198 const delay_ms = backoff(retry.base_ms, attempt);
197199 if (notice) |n| {
198200 var buf: [16]u8 = undefined;
src/json.zig+6−0
@@ -9,3 +9,9 @@ pub const Raw = struct {
99 jws.endWriteRaw();
1010 }
1111 };
12+
13+/// A non-empty string field, or null when the key is missing or holds another type.
14+pub fn stringField(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
15+ const value = obj.get(key) orelse return null;
16+ return if (value == .string and value.string.len > 0) value.string else null;
17+}
src/session.zig+6−11
@@ -364,13 +364,8 @@ fn messageRecord(a: std.mem.Allocator, message: message_mod.Message) !MessageRec
364364 }
365365 }
366366
367-fn str(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
368- const value = obj.get(key) orelse return null;
369- return if (value == .string) value.string else null;
370-}
371-
372367 fn dupStr(a: std.mem.Allocator, obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
373- const s = str(obj, key) orelse return null;
368+ const s = json.stringField(obj, key) orelse return null;
374369 return a.dupe(u8, s) catch null;
375370 }
376371
@@ -440,7 +435,7 @@ fn parseParts(a: std.mem.Allocator, parts: []std.json.Value) struct { text: []co
440435 for (parts) |part| {
441436 if (part != .object) continue;
442437 const p = part.object;
443- const kind = str(p, "type") orelse continue;
438+ const kind = json.stringField(p, "type") orelse continue;
444439 if (std.mem.eql(u8, kind, "text")) {
445440 body = dupStr(a, p, "text") orelse body;
446441 } else if (std.mem.eql(u8, kind, "image")) {
@@ -462,14 +457,14 @@ fn parseAssistant(a: std.mem.Allocator, record: std.json.ObjectMap) ?*message_mo
462457 .response_model = dupStr(a, record, "responseModel"),
463458 .raw_stop_reason = dupStr(a, record, "rawStopReason"),
464459 .usage = usageOf(object(record, "usage")),
465- .stop_reason = stopReason(str(record, "stopReason")),
460+ .stop_reason = stopReason(json.stringField(record, "stopReason")),
466461 .error_message = dupStr(a, record, "errorMessage"),
467462 .timestamp = int(record, "timestamp"),
468463 };
469464 for (items(record, "content")) |entry| {
470465 if (entry != .object) continue;
471466 const block = entry.object;
472- const kind = str(block, "type") orelse continue;
467+ const kind = json.stringField(block, "type") orelse continue;
473468 if (std.mem.eql(u8, kind, "text")) {
474469 message.content.append(a, .{ .text = dupStr(a, block, "text") orelse "" }) catch {};
475470 } else if (std.mem.eql(u8, kind, "thinking")) {
@@ -499,10 +494,10 @@ fn parseMessage(a: std.mem.Allocator, scratch: std.mem.Allocator, line: []const
499494 if (std.mem.trim(u8, line, " \t\r").len == 0) return null;
500495 const root = std.json.parseFromSliceLeaky(std.json.Value, scratch, line, .{}) catch return null;
501496 if (root != .object) return null;
502- const kind = str(root.object, "type") orelse return null;
497+ const kind = json.stringField(root.object, "type") orelse return null;
503498 if (!std.mem.eql(u8, kind, "message")) return null;
504499 const record = object(root.object, "message") orelse return null;
505- const role = str(record, "role") orelse return null;
500+ const role = json.stringField(record, "role") orelse return null;
506501
507502 if (std.mem.eql(u8, role, "user")) {
508503 return .{ .user = .{
src/text.zig+23−0
@@ -43,6 +43,29 @@ fn utf8SeqLen(p: []const u8) ?usize {
4343 return null;
4444 }
4545
46+pub const Cp = struct { cp: u21, len: usize };
47+
48+/// The code point at `i` and its byte length. An invalid or truncated byte counts
49+/// as a one-byte code point, so callers always make progress.
50+pub fn decodeAt(bytes: []const u8, i: usize) ?Cp {
51+ if (i >= bytes.len) return null;
52+ const b = bytes[i];
53+ const n = std.unicode.utf8ByteSequenceLength(b) catch return .{ .cp = b, .len = 1 };
54+ if (i + n > bytes.len) return .{ .cp = b, .len = 1 };
55+ return .{ .cp = std.unicode.utf8Decode(bytes[i .. i + n]) catch b, .len = n };
56+}
57+
58+/// Code points in `bytes`, counting each invalid byte as one.
59+pub fn cpLen(bytes: []const u8) usize {
60+ var i: usize = 0;
61+ var n: usize = 0;
62+ while (decodeAt(bytes, i)) |d| {
63+ i += d.len;
64+ n += 1;
65+ }
66+ return n;
67+}
68+
4669 pub fn utf8Clean(a: std.mem.Allocator, text: []const u8) ![]const u8 {
4770 if (std.unicode.utf8ValidateSlice(text)) return text;
4871 var out: std.ArrayList(u8) = .empty;
src/tui/editor.zig+32−55
@@ -1,6 +1,7 @@
11 const std = @import("std");
22 const render = @import("render.zig");
33 const input = @import("input.zig");
4+const utf8 = @import("../text.zig");
45
56 const TAB = 4;
67
@@ -8,25 +9,12 @@ fn isSpace(cp: u21) bool {
89 return cp == ' ' or cp == '\t' or cp == '\n' or cp == '\r' or cp == 0x0b or cp == 0x0c or cp == 0xa0;
910 }
1011
11-fn cpLen(line: []const u8) usize {
12- var i: usize = 0;
13- var count: usize = 0;
14- while (i < line.len) {
15- const n = std.unicode.utf8ByteSequenceLength(line[i]) catch 1;
16- i += @min(@as(usize, n), line.len - i);
17- count += 1;
18- }
19- return count;
20-}
21-
2212 fn cpAt(line: []const u8, col: usize) u21 {
2313 var i: usize = 0;
2414 var count: usize = 0;
25- while (i < line.len) {
26- const n = std.unicode.utf8ByteSequenceLength(line[i]) catch 1;
27- const len = @min(@as(usize, n), line.len - i);
28- if (count == col) return std.unicode.utf8Decode(line[i .. i + len]) catch line[i];
29- i += len;
15+ while (utf8.decodeAt(line, i)) |d| {
16+ if (count == col) return d.cp;
17+ i += d.len;
3018 count += 1;
3119 }
3220 return 0;
@@ -35,10 +23,8 @@ fn cpAt(line: []const u8, col: usize) u21 {
3523 fn byteOf(line: []const u8, col: usize) usize {
3624 var i: usize = 0;
3725 var count: usize = 0;
38- while (i < line.len and count < col) {
39- const n = std.unicode.utf8ByteSequenceLength(line[i]) catch 1;
40- i += @min(@as(usize, n), line.len - i);
41- count += 1;
26+ while (count < col) : (count += 1) {
27+ i += (utf8.decodeAt(line, i) orelse break).len;
4228 }
4329 return i;
4430 }
@@ -57,7 +43,7 @@ fn wordStart(line: []const u8, col: usize) usize {
5743 }
5844
5945 fn wordEnd(line: []const u8, col: usize) usize {
60- const n = cpLen(line);
46+ const n = utf8.cpLen(line);
6147 var i = col;
6248 while (i < n and isSpace(cpAt(line, i))) i += 1;
6349 while (i < n and !isSpace(cpAt(line, i))) i += 1;
@@ -121,7 +107,7 @@ pub const Editor = struct {
121107 }
122108 if (self.lines.items.len == 0) self.lines.append(self.a, .empty) catch {};
123109 self.row = self.lines.items.len - 1;
124- self.col = cpLen(self.lines.items[self.row].items);
110+ self.col = utf8.cpLen(self.lines.items[self.row].items);
125111 }
126112
127113 pub fn handle(self: *Editor, key: input.Key) Action {
@@ -176,7 +162,7 @@ pub const Editor = struct {
176162 return .changed;
177163 },
178164 .end => {
179- self.col = cpLen(self.lines.items[self.row].items);
165+ self.col = utf8.cpLen(self.lines.items[self.row].items);
180166 return .changed;
181167 },
182168 .doc_start => {
@@ -186,7 +172,7 @@ pub const Editor = struct {
186172 },
187173 .doc_end => {
188174 self.row = self.lines.items.len - 1;
189- self.col = cpLen(self.lines.items[self.row].items);
175+ self.col = utf8.cpLen(self.lines.items[self.row].items);
190176 return .changed;
191177 },
192178 else => return .none,
@@ -201,15 +187,9 @@ pub const Editor = struct {
201187 while (render.nextCluster(line, i)) |cluster| {
202188 const tab = cluster.text.len == 1 and cluster.text[0] == '\t';
203189 const advance = if (tab) TAB - (col % TAB) else cluster.width;
204- var cps: usize = 0;
205- var j: usize = 0;
206- while (j < cluster.text.len) {
207- const n = std.unicode.utf8ByteSequenceLength(cluster.text[j]) catch 1;
208- j += @min(@as(usize, n), cluster.text.len - j);
209- cps += 1;
210- }
211- var m: usize = 0;
190+ const cps = utf8.cpLen(cluster.text);
212191 col += advance;
192+ var m: usize = 0;
213193 while (m < cps) : (m += 1) out.append(self.s, col) catch {};
214194 i += cluster.text.len;
215195 }
@@ -278,7 +258,7 @@ pub const Editor = struct {
278258 const at = byteOf(line.items, self.col);
279259 if (std.mem.indexOfScalar(u8, draft, '\n') == null) {
280260 line.insertSlice(self.a, at, draft) catch {};
281- self.col += cpLen(draft);
261+ self.col += utf8.cpLen(draft);
282262 return;
283263 }
284264 const tail = self.a.dupe(u8, line.items[at..]) catch "";
@@ -292,7 +272,7 @@ pub const Editor = struct {
292272 fresh.append(self.a, l) catch {};
293273 }
294274 const lasti = fresh.items.len - 1;
295- const anchor = cpLen(fresh.items[lasti].items);
275+ const anchor = utf8.cpLen(fresh.items[lasti].items);
296276 fresh.items[lasti].appendSlice(self.a, tail) catch {};
297277 var at_row = self.row + 1;
298278 for (fresh.items) |l| {
@@ -303,19 +283,23 @@ pub const Editor = struct {
303283 self.col = anchor;
304284 }
305285
286+ /// Replace the code points in `[from, to)` of `line` with `text`.
287+ fn replaceCols(self: *Editor, line: *Line, from: usize, to: usize, text: []const u8) void {
288+ const start = byteOf(line.items, from);
289+ const end = byteOf(line.items, to);
290+ line.replaceRange(self.a, start, end - start, text) catch {};
291+ }
292+
306293 fn backspace(self: *Editor) void {
307294 if (self.col > 0) {
308- const line = &self.lines.items[self.row];
309- const from = byteOf(line.items, self.col - 1);
310- const to = byteOf(line.items, self.col);
311- line.replaceRange(self.a, from, to - from, "") catch {};
295+ self.replaceCols(&self.lines.items[self.row], self.col - 1, self.col, "");
312296 self.col -= 1;
313297 return;
314298 }
315299 if (self.row > 0) {
316300 const prev = &self.lines.items[self.row - 1];
317301 const cur = self.lines.items[self.row];
318- const previous = cpLen(prev.items);
302+ const previous = utf8.cpLen(prev.items);
319303 prev.appendSlice(self.a, cur.items) catch {};
320304 _ = self.lines.orderedRemove(self.row);
321305 self.row -= 1;
@@ -325,11 +309,9 @@ pub const Editor = struct {
325309
326310 fn deleteForward(self: *Editor) void {
327311 const line = &self.lines.items[self.row];
328- const n = cpLen(line.items);
312+ const n = utf8.cpLen(line.items);
329313 if (self.col < n) {
330- const from = byteOf(line.items, self.col);
331- const to = byteOf(line.items, self.col + 1);
332- line.replaceRange(self.a, from, to - from, "") catch {};
314+ self.replaceCols(line, self.col, self.col + 1, "");
333315 return;
334316 }
335317 if (self.row < self.lines.items.len - 1) {
@@ -345,12 +327,12 @@ pub const Editor = struct {
345327 self.col -= 1;
346328 } else if (self.row > 0) {
347329 self.row -= 1;
348- self.col = cpLen(self.lines.items[self.row].items);
330+ self.col = utf8.cpLen(self.lines.items[self.row].items);
349331 }
350332 }
351333
352334 fn right(self: *Editor) void {
353- if (self.col < cpLen(self.lines.items[self.row].items)) {
335+ if (self.col < utf8.cpLen(self.lines.items[self.row].items)) {
354336 self.col += 1;
355337 } else if (self.row < self.lines.items.len - 1) {
356338 self.row += 1;
@@ -398,7 +380,7 @@ pub const Editor = struct {
398380 if (self.row == 0) return;
399381 self.row -= 1;
400382 const previous = self.lines.items[self.row].items;
401- self.col = wordStart(previous, cpLen(previous));
383+ self.col = wordStart(previous, utf8.cpLen(previous));
402384 }
403385
404386 fn wordRight(self: *Editor) void {
@@ -414,11 +396,8 @@ pub const Editor = struct {
414396 }
415397
416398 fn wordBack(self: *Editor) void {
417- const line = &self.lines.items[self.row];
418- const start = wordStart(line.items, self.col);
419- const from = byteOf(line.items, start);
420- const to = byteOf(line.items, self.col);
421- line.replaceRange(self.a, from, to - from, "") catch {};
399+ const start = wordStart(self.lines.items[self.row].items, self.col);
400+ self.replaceCols(&self.lines.items[self.row], start, self.col, "");
422401 self.col = start;
423402 }
424403
@@ -429,10 +408,8 @@ pub const Editor = struct {
429408 if (isSpace(cpAt(line.items, self.col - 1))) return false;
430409 const word = sub(self.s, line.items, start, self.col);
431410 const completed = step(word) orelse return false;
432- const from = byteOf(line.items, start);
433- const to = byteOf(line.items, self.col);
434- line.replaceRange(self.a, from, to - from, completed) catch {};
435- self.col = start + cpLen(completed);
411+ self.replaceCols(line, start, self.col, completed);
412+ self.col = start + utf8.cpLen(completed);
436413 return true;
437414 }
438415 };
src/tui/format.zig+25−15
@@ -19,7 +19,7 @@ pub const Normalizer = struct {
1919 const text = std.mem.trimEnd(u8, raw, " \t\r");
2020 const ind = indentOf(text);
2121 var rest = text[ind.end..];
22- if (fenceMarker(rest)) |fence_run| return self.fence(a, ind.cols, rest, fence_run);
22+ if (fenceRun(rest)) |fence_run| return self.fence(a, ind.cols, rest, fence_run);
2323 if (isRule(rest)) {
2424 self.reset();
2525 return std.fmt.allocPrint(a, "{s}---", .{spaces(a, ind.cols)}) catch "---";
@@ -98,16 +98,31 @@ fn indentOf(text: []const u8) Indent {
9898 return .{ .end = end, .cols = cols & ~@as(usize, 1) };
9999 }
100100
101-fn fenceMarker(rest: []const u8) ?[]const u8 {
102- if (rest.len == 0) return null;
103- const c = rest[0];
101+/// The fence marker run (``` or ~~~) that opens `line`, if any.
102+pub fn fenceRun(line: []const u8) ?[]const u8 {
103+ var i: usize = 0;
104+ while (i < line.len and i < 3 and line[i] == ' ') i += 1;
105+ if (i >= line.len) return null;
106+ const c = line[i];
104107 if (c != '`' and c != '~') return null;
105108 var n: usize = 0;
106- while (n < rest.len and rest[n] == c) n += 1;
107- return if (n >= 3) rest[0..n] else null;
109+ while (i + n < line.len and line[i + n] == c) n += 1;
110+ return if (n >= 3) line[i .. i + n] else null;
108111 }
109112
110-fn isRule(rest: []const u8) bool {
113+/// Whether `line` closes a fence opened with `opener`: the same byte, at least as
114+/// long a run, and nothing but whitespace after it.
115+pub fn fenceClose(line: []const u8, opener: []const u8) bool {
116+ var i: usize = 0;
117+ while (i < line.len and i < 3 and line[i] == ' ') i += 1;
118+ if (i >= line.len or line[i] != opener[0]) return false;
119+ var n: usize = 0;
120+ while (i + n < line.len and line[i + n] == opener[0]) n += 1;
121+ if (n < opener.len) return false;
122+ return std.mem.trim(u8, line[i + n ..], " \t").len == 0;
123+}
124+
125+pub fn isRule(rest: []const u8) bool {
111126 if (rest.len == 0) return false;
112127 const c = rest[0];
113128 if (c != '-' and c != '*' and c != '_') return false;
@@ -124,7 +139,7 @@ fn isRule(rest: []const u8) bool {
124139
125140 const Heading = struct { level: usize, text: []const u8 };
126141
127-fn heading(rest: []const u8) ?Heading {
142+pub fn heading(rest: []const u8) ?Heading {
128143 var n: usize = 0;
129144 while (n < rest.len and rest[n] == '#') n += 1;
130145 if (n == 0 or n > 6) return null;
@@ -222,11 +237,6 @@ pub fn linkEnd(text: []const u8, open: usize) ?usize {
222237 return null;
223238 }
224239
225-/// The styling pass only adds color, so a cell's own bytes are what gets painted.
226-fn cellWidth(cell: []const u8) usize {
227- return render.displayWidth(cell);
228-}
229-
230240 /// Delimiter row (`|---|:--:|`) as per-column alignments, or null when the line is not one.
231241 fn delimiterRow(a: std.mem.Allocator, line: []const u8) ?[]const Align {
232242 if (std.mem.indexOfScalar(u8, line, '-') == null) return null;
@@ -271,7 +281,7 @@ fn emitRow(a: std.mem.Allocator, block: *std.ArrayList(u8), indent: []const u8,
271281 block.appendNTimes(a, '-', widths[k] - 2) catch {};
272282 block.append(a, if (alignment == .right or alignment == .center) ':' else '-') catch {};
273283 } else {
274- const pad = widths[k] - cellWidth(cell);
284+ const pad = widths[k] - render.displayWidth(cell);
275285 const before: usize = switch (alignment) {
276286 .right => pad,
277287 .center => pad / 2,
@@ -307,7 +317,7 @@ fn formatTable(a: std.mem.Allocator, header: []const u8, aligns: []const Align,
307317 const widths = a.alloc(usize, named) catch return null;
308318 @memset(widths, 3);
309319 for (rows) |cells| {
310- for (cells, 0..) |cell, k| widths[k] = @max(widths[k], cellWidth(cell));
320+ for (cells, 0..) |cell, k| widths[k] = @max(widths[k], render.displayWidth(cell));
311321 }
312322
313323 var block: std.ArrayList(u8) = .empty;
src/tui/highlight.zig+4−37
@@ -194,39 +194,6 @@ fn leadingSpaces(line: []const u8) usize {
194194 return i;
195195 }
196196
197-fn headingLevel(line: []const u8) ?usize {
198- const at = leadingSpaces(line);
199- var n: usize = 0;
200- while (at + n < line.len and line[at + n] == '#') n += 1;
201- if (n == 0 or n > 6) return null;
202- if (at + n < line.len and line[at + n] != ' ' and line[at + n] != '\t') return null;
203- return n;
204-}
205-
206-fn isFenceMarker(line: []const u8) bool {
207- const at = leadingSpaces(line);
208- if (at >= line.len) return false;
209- const c = line[at];
210- if (c != '`' and c != '~') return false;
211- return runLength(line, at, c) >= 3;
212-}
213-
214-fn isRule(line: []const u8) bool {
215- const at = leadingSpaces(line);
216- if (at >= line.len) return false;
217- const c = line[at];
218- if (c != '-' and c != '*' and c != '_') return false;
219- var marks: usize = 0;
220- for (line[at..]) |ch| {
221- if (ch == c) {
222- marks += 1;
223- } else if (ch != ' ' and ch != '\t' and ch != '\r') {
224- return false;
225- }
226- }
227- return marks >= 3;
228-}
229-
230197 /// Byte offset just past a list or quote marker, or null when the line has none.
231198 fn blockMarker(line: []const u8) ?usize {
232199 var at: usize = 0;
@@ -246,7 +213,7 @@ fn blockMarker(line: []const u8) ?usize {
246213
247214 fn markdownLine(a: std.mem.Allocator, line: []const u8, base: u32, spans: *std.ArrayList(Span)) void {
248215 const limit = line.len;
249- if (isFenceMarker(line) or isRule(line)) {
216+ if (format.fenceRun(line) != null or format.isRule(line[leadingSpaces(line)..])) {
250217 addSpan(a, spans, base, 0, limit, muted());
251218 return;
252219 }
@@ -257,11 +224,11 @@ fn markdownLine(a: std.mem.Allocator, line: []const u8, base: u32, spans: *std.A
257224 }
258225 // Headings and rules keep their style when quoted or listed.
259226 const rest = line[start..];
260- if (headingLevel(rest)) |level| {
261- addSpan(a, spans, base, start, limit, styles.roles.heading(level));
227+ if (format.heading(rest[leadingSpaces(rest)..])) |h| {
228+ addSpan(a, spans, base, start, limit, styles.roles.heading(h.level));
262229 return;
263230 }
264- if (isFenceMarker(rest) or isRule(rest)) {
231+ if (format.fenceRun(rest) != null or format.isRule(rest)) {
265232 addSpan(a, spans, base, start, limit, muted());
266233 return;
267234 }
src/tui/history.zig+1−2
@@ -1,6 +1,5 @@
11 const std = @import("std");
2-const platform = @import("platform.zig");
3-const filesystem = @import("filesystem.zig");
2+const filesystem = @import("../filesystem.zig");
43
54 pub const Store = struct {
65 path: []const u8,
src/tui/render.zig+32−56
@@ -1,6 +1,7 @@
11 const std = @import("std");
22 const styles = @import("styles.zig");
33 const wcwidth = @import("width.zig");
4+const utf8 = @import("../text.zig");
45
56 pub const nextCluster = wcwidth.nextCluster;
67
@@ -22,17 +23,6 @@ pub fn physicalRows(line: []const u8, width: usize) usize {
2223
2324 const Piece = struct { text: []const u8, width: usize, sgr: bool };
2425
25-fn decodeLen(text: []const u8, i: usize) usize {
26- const n = std.unicode.utf8ByteSequenceLength(text[i]) catch return 1;
27- return if (i + n > text.len) 1 else n;
28-}
29-
30-fn decodeCp(text: []const u8, i: usize) u21 {
31- const n = decodeLen(text, i);
32- if (text[i] < 0x80) return text[i];
33- return std.unicode.utf8Decode(text[i .. i + n]) catch text[i];
34-}
35-
3626 fn nextPiece(text: []const u8, i: *usize) ?Piece {
3727 if (i.* >= text.len) return null;
3828 if (isSgrAt(text, i.*)) |n| {
@@ -45,7 +35,7 @@ fn nextPiece(text: []const u8, i: *usize) ?Piece {
4535 i.* += cluster.text.len;
4636 return piece;
4737 }
48- const len = decodeLen(text, i.*);
38+ const len = (utf8.decodeAt(text, i.*) orelse return null).len;
4939 const piece = Piece{ .text = text[i.* .. i.* + len], .width = 1, .sgr = false };
5040 i.* += len;
5141 return piece;
@@ -64,6 +54,26 @@ fn isSgrAt(text: []const u8, i: usize) ?usize {
6454 return null;
6555 }
6656
57+/// Bytes taken by the escape sequence at `i`. An unterminated sequence runs to the
58+/// end of the text, so the caller always makes progress.
59+fn escapeLen(text: []const u8, i: usize) usize {
60+ if (i + 1 >= text.len) return 1;
61+ if (text[i + 1] == '[') {
62+ var j = i + 2;
63+ while (j < text.len and (text[j] < 0x40 or text[j] > 0x7e)) j += 1;
64+ return (if (j < text.len) j + 1 else text.len) - i;
65+ }
66+ if (text[i + 1] == ']') {
67+ var j = i + 2;
68+ while (j < text.len) : (j += 1) {
69+ if (text[j] == 0x07) return j + 1 - i;
70+ if (text[j] == 0x1b and j + 1 < text.len and text[j + 1] == '\\') return j + 2 - i;
71+ }
72+ return text.len - i;
73+ }
74+ return 2;
75+}
76+
6777 pub fn sanitize(a: std.mem.Allocator, text: []const u8) []const u8 {
6878 var clean = true;
6979 for (text) |c| {
@@ -79,20 +89,13 @@ pub fn sanitize(a: std.mem.Allocator, text: []const u8) []const u8 {
7989 while (i < text.len) {
8090 const c = text[i];
8191 if (c == 0x1b) {
92+ // Colors survive; every other escape only ever corrupts the layout.
8293 if (isSgrAt(text, i)) |n| {
8394 out.appendSlice(a, text[i .. i + n]) catch {};
8495 i += n;
85- continue;
96+ } else {
97+ i += escapeLen(text, i);
8698 }
87- if (i + 1 < text.len) {
88- i += 2;
89- if (text[i - 1] == '[') {
90- while (i < text.len and (text[i] < 0x40 or text[i] > 0x7e)) i += 1;
91- if (i < text.len) i += 1;
92- }
93- continue;
94- }
95- i += 1;
9699 continue;
97100 }
98101 if (c < 0x80) {
@@ -104,14 +107,10 @@ pub fn sanitize(a: std.mem.Allocator, text: []const u8) []const u8 {
104107 i += 1;
105108 continue;
106109 }
107- const cp = decodeCp(text, i);
108- if (cp >= 0x80 and cp <= 0x9f) {
109- i += decodeLen(text, i);
110- continue;
111- }
112- const len = decodeLen(text, i);
113- out.appendSlice(a, text[i .. i + len]) catch {};
114- i += len;
110+ const d = utf8.decodeAt(text, i) orelse break;
111+ // C1 controls (0x80..0x9f) are as hazardous as the C0 ones.
112+ if (d.cp > 0x9f) out.appendSlice(a, text[i .. i + d.len]) catch {};
113+ i += d.len;
115114 }
116115 return out.items;
117116 }
@@ -121,34 +120,11 @@ pub fn stripAnsi(a: std.mem.Allocator, text: []const u8) []const u8 {
121120 var out: std.ArrayList(u8) = .empty;
122121 var i: usize = 0;
123122 while (i < text.len) {
124- if (text[i] != 0x1b) {
125- out.append(a, text[i]) catch {};
126- i += 1;
127- continue;
128- }
129- i += 1;
130- if (i >= text.len) break;
131- if (text[i] == '[') {
132- i += 1;
133- while (i < text.len and (text[i] < 0x40 or text[i] > 0x7e)) i += 1;
134- if (i < text.len) i += 1;
135- continue;
136- }
137- if (text[i] == ']') {
138- i += 1;
139- while (i < text.len) {
140- if (text[i] == 0x07) {
141- i += 1;
142- break;
143- }
144- if (text[i] == 0x1b and i + 1 < text.len and text[i + 1] == '\\') {
145- i += 2;
146- break;
147- }
148- i += 1;
149- }
123+ if (text[i] == 0x1b) {
124+ i += escapeLen(text, i);
150125 continue;
151126 }
127+ out.append(a, text[i]) catch {};
152128 i += 1;
153129 }
154130 return out.items;
src/tui/status.zig+3−3
@@ -1,8 +1,8 @@
11 const std = @import("std");
22 const builtin = @import("builtin");
3-const platform = @import("platform.zig");
4-const time = @import("time.zig");
5-const config = @import("config.zig");
3+const platform = @import("../platform.zig");
4+const time = @import("../time.zig");
5+const config = @import("../config.zig");
66
77 /// OSC 7501, the Program Status Protocol. The program reports what it is doing
88 /// so any consumer of the pty can react; well-behaved terminals ignore the
src/tui/stream.zig+2−35
@@ -6,31 +6,6 @@ const text = @import("../text.zig");
66
77 const BodyLine = render.BodyLine;
88
9-fn isFenceOpen(line: []const u8) ?[]const u8 {
10- var i: usize = 0;
11- while (i < line.len and i < 3 and line[i] == ' ') i += 1;
12- if (i >= line.len) return null;
13- const ch = line[i];
14- if (ch != '`' and ch != '~') return null;
15- var j = i;
16- while (j < line.len and line[j] == ch) j += 1;
17- if (j - i < 3) return null;
18- return line[i..j];
19-}
20-
21-fn isFenceClose(line: []const u8, marker: []const u8) bool {
22- var i: usize = 0;
23- while (i < line.len and i < 3 and line[i] == ' ') i += 1;
24- if (i >= line.len or line[i] != marker[0]) return false;
25- var j = i;
26- while (j < line.len and line[j] == marker[0]) j += 1;
27- if (j - i < marker.len) return false;
28- while (j < line.len) : (j += 1) {
29- if (line[j] != ' ' and line[j] != '\t') return false;
30- }
31- return true;
32-}
33-
349 pub const MarkdownStream = struct {
3510 arena: std.heap.ArenaAllocator,
3611 a: std.mem.Allocator = undefined,
@@ -66,7 +41,7 @@ pub const MarkdownStream = struct {
6641
6742 fn commit(self: *MarkdownStream, out_a: std.mem.Allocator, raw: []const u8, out: *std.ArrayList(BodyLine)) void {
6843 if (self.fence) |*f| {
69- if (isFenceClose(raw, f.marker)) {
44+ if (format.fenceClose(raw, f.marker)) {
7045 self.releaseFence(out_a, self.norm.line(self.a, raw), out);
7146 } else {
7247 f.lines.append(self.a, raw) catch {};
@@ -74,7 +49,7 @@ pub const MarkdownStream = struct {
7449 return;
7550 }
7651 const line = self.norm.line(self.a, raw);
77- if (isFenceOpen(line)) |marker| {
52+ if (format.fenceRun(line)) |marker| {
7853 self.releaseProse(out_a, "", out);
7954 var fl: std.ArrayList([]const u8) = .empty;
8055 fl.append(self.a, line) catch {};
@@ -110,14 +85,6 @@ pub const MarkdownStream = struct {
11085 if (closing) |c| out.append(out_a, .{ .text = highlight.highlightMarkdown(out_a, c) }) catch {};
11186 }
11287
113- pub fn pending(self: *MarkdownStream, out_a: std.mem.Allocator) []BodyLine {
114- var out: std.ArrayList(BodyLine) = .empty;
115- const held: []const []const u8 = if (self.fence) |f| f.lines.items else self.prose.items;
116- for (held) |l| out.append(out_a, .{ .text = l }) catch {};
117- if (self.rest.items.len > 0) out.append(out_a, .{ .text = self.rest.items }) catch {};
118- return out.items;
119- }
120-
12188 pub fn flush(self: *MarkdownStream, out_a: std.mem.Allocator) []BodyLine {
12289 var out: std.ArrayList(BodyLine) = .empty;
12390 if (self.fence) |*f| {
src/tui/tui.zig+3−7
@@ -21,8 +21,8 @@ const tool_view = @import("tool_view.zig");
2121 const image_view = @import("image.zig");
2222 const picker_mod = @import("picker.zig");
2323 const screen = @import("screen.zig");
24-const history = @import("../history.zig");
25-const status = @import("../status.zig");
24+const history = @import("history.zig");
25+const status = @import("status.zig");
2626
2727 const SPINNER = "⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐ …
2828 const SPINNER_MS = 120;
@@ -674,7 +674,7 @@ const Tui = struct {
674674 if (commands.completeCommand(self.editor.contents())) |text| {
675675 self.editor.setText(text);
676676 } else {
677- _ = self.editor.completeWord(completePathStep);
677+ _ = self.editor.completeWord(complete.completePath);
678678 }
679679 self.dirty = true;
680680 return;
@@ -1013,10 +1013,6 @@ const Tui = struct {
10131013 }
10141014 };
10151015
1016-fn completePathStep(word: []const u8) ?[]const u8 {
1017- return complete.completePath(word);
1018-}
1019-
10201016 fn inputThread(self: *Tui) void {
10211017 var buf: [4096]u8 = undefined;
10221018 const stdin = std.Io.File.stdin();
src/tui/width.zig+4−11
@@ -1,5 +1,6 @@
11 const std = @import("std");
22 const tables = @import("width_tables.zig");
3+const utf8 = @import("../text.zig");
34
45 pub const Cluster = struct { text: []const u8, width: u8 };
56
@@ -40,14 +41,6 @@ pub fn charWidth(cp: u21) u8 {
4041 return 1;
4142 }
4243
43-fn decodeAt(text: []const u8, i: usize) ?struct { cp: u21, len: usize } {
44- if (i >= text.len) return null;
45- const n = std.unicode.utf8ByteSequenceLength(text[i]) catch return .{ .cp = text[i], .len = 1 };
46- if (i + n > text.len) return .{ .cp = text[i], .len = 1 };
47- const cp = std.unicode.utf8Decode(text[i .. i + n]) catch return .{ .cp = text[i], .len = 1 };
48- return .{ .cp = cp, .len = n };
49-}
50-
5144 fn isExtPict(cp: u21) bool {
5245 return inRanges(&tables.extended_pictographic, cp);
5346 }
@@ -117,7 +110,7 @@ fn clusterWidth(text: []const u8) u8 {
117110 var i: usize = 0;
118111 var first = true;
119112 while (i < text.len) {
120- const d = decodeAt(text, i) orelse break;
113+ const d = utf8.decodeAt(text, i) orelse break;
121114 if (d.cp == 0xfe0f) has_vs16 = true;
122115 if (first) {
123116 base = d.cp;
@@ -131,13 +124,13 @@ fn clusterWidth(text: []const u8) u8 {
131124 }
132125
133126 pub fn nextCluster(text: []const u8, i: usize) ?Cluster {
134- const d = decodeAt(text, i) orelse return null;
127+ const d = utf8.decodeAt(text, i) orelse return null;
135128 var state = State{};
136129 startsWith(&state, d.cp);
137130 var end = i + d.len;
138131 var prev = d.cp;
139132 while (end < text.len) {
140- const n = decodeAt(text, end) orelse break;
133+ const n = utf8.decodeAt(text, end) orelse break;
141134 if (!noBreak(state, prev, n.cp)) break;
142135 extends(&state, n.cp);
143136 prev = n.cp;