xonecas.io
79113
Ma

mini-coding-agent / files

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

12.4 KB
1const std = @import("std");
2const render = @import("render.zig");
3
4pub const Normalizer = struct {
5    ordered_indent: ?usize = null,
6    ordered_next: usize = 1,
7
8    pub fn reset(self: *Normalizer) void {
9        self.ordered_indent = null;
10        self.ordered_next = 1;
11    }
12
13    pub fn line(self: *Normalizer, a: std.mem.Allocator, raw: []const u8) []const u8 {
14        const text = std.mem.trimEnd(u8, raw, " \t\r");
15        const ind = indentOf(text);
16        var rest = text[ind.end..];
17        if (fenceRun(rest)) |fence_run| return self.fence(a, ind.cols, rest, fence_run);
18        if (isRule(rest)) {
19            self.reset();
20            return std.fmt.allocPrint(a, "{s}---", .{spaces(a, ind.cols)}) catch "---";
21        }
22        var out: std.ArrayList(u8) = .empty;
23        out.appendSlice(a, spaces(a, ind.cols)) catch {};
24        while (rest.len > 0 and rest[0] == '>') {
25            out.appendSlice(a, "> ") catch {};
26            rest = std.mem.trimStart(u8, rest[1..], " \t");
27        }
28        return self.body(a, &out, ind.cols, rest);
29    }
30
31    fn body(self: *Normalizer, a: std.mem.Allocator, out: *std.ArrayList(u8), indent: usize, rest: []const u8) []const u8 {
32        if (heading(rest)) |h| {
33            self.reset();
34            out.appendNTimes(a, '#', h.level) catch {};
35            if (h.text.len > 0) {
36                out.append(a, ' ') catch {};
37                out.appendSlice(a, h.text) catch {};
38            }
39            return out.items;
40        }
41        if (marker(rest)) |m| switch (m) {
42            .bullet => {
43                self.ordered_indent = null;
44                out.appendSlice(a, "- ") catch {};
45                out.appendSlice(a, std.mem.trimStart(u8, rest[1..], " \t")) catch {};
46            },
47            .ordered => |o| {
48                const num = if (self.ordered_indent == indent) self.ordered_next else o.num;
49                self.ordered_indent = indent;
50                self.ordered_next = num + 1;
51                out.appendSlice(a, std.fmt.allocPrint(a, "{d}.", .{num}) catch "-") catch {};
52                out.append(a, ' ') catch {};
53                out.appendSlice(a, std.mem.trimStart(u8, rest[o.at..], " \t")) catch {};
54            },
55        } else {
56            self.ordered_indent = null;
57            out.appendSlice(a, rest) catch {};
58        }
59        return trimmed(out);
60    }
61
62    fn fence(self: *Normalizer, a: std.mem.Allocator, indent: usize, rest: []const u8, run: []const u8) []const u8 {
63        self.reset();
64        var out: std.ArrayList(u8) = .empty;
65        out.appendSlice(a, spaces(a, indent)) catch {};
66        out.appendSlice(a, run) catch {};
67        out.appendSlice(a, std.mem.trim(u8, rest[run.len..], " \t")) catch {};
68        return out.items;
69    }
70};
71
72fn spaces(a: std.mem.Allocator, n: usize) []const u8 {
73    const out = a.alloc(u8, n) catch return "";
74    @memset(out, ' ');
75    return out;
76}
77
78fn trimmed(out: *std.ArrayList(u8)) []const u8 {
79    while (out.items.len > 0 and (out.items[out.items.len - 1] == ' ' or out.items[out.items.len - 1] == '\t'))
80        out.items.len -= 1;
81    return out.items;
82}
83
84const Indent = struct { end: usize, cols: usize };
85
86fn indentOf(text: []const u8) Indent {
87    var end: usize = 0;
88    var cols: usize = 0;
89    while (end < text.len and (text[end] == ' ' or text[end] == '\t')) : (end += 1)
90        cols += if (text[end] == '\t') 2 else 1;
91    return .{ .end = end, .cols = cols & ~@as(usize, 1) };
92}
93
94pub fn fenceRun(line: []const u8) ?[]const u8 {
95    var i: usize = 0;
96    while (i < line.len and i < 3 and line[i] == ' ') i += 1;
97    if (i >= line.len) return null;
98    const c = line[i];
99    if (c != '`' and c != '~') return null;
100    var n: usize = 0;
101    while (i + n < line.len and line[i + n] == c) n += 1;
102    return if (n >= 3) line[i .. i + n] else null;
103}
104
105pub fn fenceClose(line: []const u8, opener: []const u8) bool {
106    var i: usize = 0;
107    while (i < line.len and i < 3 and line[i] == ' ') i += 1;
108    if (i >= line.len or line[i] != opener[0]) return false;
109    var n: usize = 0;
110    while (i + n < line.len and line[i + n] == opener[0]) n += 1;
111    if (n < opener.len) return false;
112    return std.mem.trim(u8, line[i + n ..], " \t").len == 0;
113}
114
115pub fn isRule(rest: []const u8) bool {
116    if (rest.len == 0) return false;
117    const c = rest[0];
118    if (c != '-' and c != '*' and c != '_') return false;
119    var marks: usize = 0;
120    for (rest) |ch| {
121        if (ch == c) {
122            marks += 1;
123        } else if (ch != ' ' and ch != '\t') {
124            return false;
125        }
126    }
127    return marks >= 3;
128}
129
130const Heading = struct { level: usize, text: []const u8 };
131
132pub fn heading(rest: []const u8) ?Heading {
133    var n: usize = 0;
134    while (n < rest.len and rest[n] == '#') n += 1;
135    if (n == 0 or n > 6) return null;
136    if (n < rest.len and rest[n] != ' ' and rest[n] != '\t') return null;
137    var text = std.mem.trimStart(u8, rest[n..], " \t");
138    var end = text.len;
139    while (end > 0 and text[end - 1] == '#') end -= 1;
140    if (end < text.len and (end == 0 or text[end - 1] == ' ' or text[end - 1] == '\t'))
141        text = std.mem.trimEnd(u8, text[0..end], " \t");
142    return .{ .level = n, .text = text };
143}
144
145const Marker = union(enum) {
146    bullet,
147    ordered: struct { num: usize, at: usize },
148};
149
150fn marker(rest: []const u8) ?Marker {
151    if (rest.len == 0) return null;
152    const c = rest[0];
153    if (c == '-' or c == '*' or c == '+')
154        return if (rest.len == 1 or rest[1] == ' ' or rest[1] == '\t') .bullet else null;
155    var at: usize = 0;
156    while (at < rest.len and std.ascii.isDigit(rest[at])) at += 1;
157    if (at == 0 or at >= rest.len) return null;
158    if (rest[at] != '.' and rest[at] != ')') return null;
159    if (at + 1 < rest.len and rest[at + 1] != ' ' and rest[at + 1] != '\t') return null;
160    return .{ .ordered = .{ .num = std.fmt.parseInt(usize, rest[0..at], 10) catch 1, .at = at + 1 } };
161}
162
163const Align = enum { none, left, center, right };
164
165fn alignOf(cell: []const u8) Align {
166    const left = cell.len > 0 and cell[0] == ':';
167    const right = cell.len > 1 and cell[cell.len - 1] == ':';
168    if (left and right) return .center;
169    if (left) return .left;
170    if (right) return .right;
171    return .none;
172}
173
174fn splitCells(a: std.mem.Allocator, line: []const u8) []const []const u8 {
175    const trimmed_line = std.mem.trim(u8, line, " \t\r");
176    var cells: std.ArrayList([]const u8) = .empty;
177    var start: usize = 0;
178    var i: usize = 0;
179    while (i < trimmed_line.len) : (i += 1) {
180        if (trimmed_line[i] == '\\' and i + 1 < trimmed_line.len) {
181            i += 1;
182            continue;
183        }
184        if (trimmed_line[i] == '|') {
185            cells.append(a, std.mem.trim(u8, trimmed_line[start..i], " \t")) catch {};
186            start = i + 1;
187        }
188    }
189    cells.append(a, std.mem.trim(u8, trimmed_line[start..], " \t")) catch {};
190    if (trimmed_line.len > 0 and trimmed_line[0] == '|' and cells.items.len > 0) _ = cells.orderedRemove(0);
191    if (trimmed_line.len > 1 and trimmed_line[trimmed_line.len - 1] == '|' and cells.items.len > 0) _ = cells.pop();
192    return cells.items;
193}
194
195pub fn closeBracket(text: []const u8, open: usize) ?usize {
196    var i = open + 1;
197    while (i < text.len) : (i += 1) {
198        if (text[i] == '\\') {
199            i += 1;
200            continue;
201        }
202        if (text[i] == ']') return i;
203    }
204    return null;
205}
206
207pub fn linkEnd(text: []const u8, open: usize) ?usize {
208    var depth: usize = 0;
209    var i = open;
210    while (i < text.len) : (i += 1) {
211        if (text[i] == '\\') {
212            i += 1;
213            continue;
214        }
215        if (text[i] != '(' and text[i] != ')') continue;
216        if (text[i] == ')') {
217            depth -= 1;
218            if (depth == 0) return i;
219        } else {
220            depth += 1;
221        }
222    }
223    return null;
224}
225
226fn delimiterRow(a: std.mem.Allocator, line: []const u8) ?[]const Align {
227    if (std.mem.indexOfScalar(u8, line, '-') == null) return null;
228    const cells = splitCells(a, line);
229    if (cells.len == 0) return null;
230    const aligns = a.alloc(Align, cells.len) catch return null;
231    for (cells, 0..) |cell, k| {
232        var body = cell;
233        if (body.len > 0 and body[0] == ':') body = body[1..];
234        if (body.len > 0 and body[body.len - 1] == ':') body = body[0 .. body.len - 1];
235        if (body.len == 0) return null;
236        for (body) |c| {
237            if (c != '-') return null;
238        }
239        aligns[k] = alignOf(cell);
240    }
241    return aligns;
242}
243
244fn tableCandidate(line: []const u8) bool {
245    const trimmed_line = std.mem.trim(u8, line, " \t\r");
246    if (trimmed_line.len == 0) return false;
247    if (trimmed_line[0] == '>' or trimmed_line[0] == '-' or trimmed_line[0] == '*' or trimmed_line[0] == '+') return false;
248    return std.mem.indexOfScalar(u8, trimmed_line, '|') != null;
249}
250
251fn rowCells(line: []const u8) bool {
252    const trimmed_line = std.mem.trim(u8, line, " \t\r");
253    return trimmed_line.len > 0 and std.mem.indexOfScalar(u8, trimmed_line, '|') != null;
254}
255
256fn emitRow(a: std.mem.Allocator, block: *std.ArrayList(u8), indent: []const u8, cells: []const []const u8, named: usize, widths: []const usize, aligns: []const Align, delimiter: bool) void {
257    block.appendSlice(a, indent) catch {};
258    block.append(a, '|') catch {};
259    for (0..named) |k| {
260        const cell = if (k < cells.len) cells[k] else "";
261        const alignment = aligns[k];
262        block.append(a, ' ') catch {};
263        if (delimiter) {
264            block.append(a, if (alignment == .left or alignment == .center) ':' else '-') catch {};
265            block.appendNTimes(a, '-', widths[k] - 2) catch {};
266            block.append(a, if (alignment == .right or alignment == .center) ':' else '-') catch {};
267        } else {
268            const pad = widths[k] - render.displayWidth(cell);
269            const before: usize = switch (alignment) {
270                .right => pad,
271                .center => pad / 2,
272                else => 0,
273            };
274            block.appendNTimes(a, ' ', before) catch {};
275            block.appendSlice(a, cell) catch {};
276            block.appendNTimes(a, ' ', pad - before) catch {};
277        }
278        block.appendSlice(a, " |") catch {};
279    }
280}
281
282fn leadingText(line: []const u8) []const u8 {
283    var i: usize = 0;
284    while (i < line.len and (line[i] == ' ' or line[i] == '\t')) i += 1;
285    return line[0..i];
286}
287
288fn formatTable(a: std.mem.Allocator, header: []const u8, aligns: []const Align, body: []const []const u8, trailing: bool) ?[]const u8 {
289    const indent = leadingText(header);
290    const named = aligns.len;
291    const rows = a.alloc([]const []const u8, body.len + 1) catch return null;
292    rows[0] = splitCells(a, header);
293    if (rows[0].len != named) return null;
294    for (body, 0..) |line, i| {
295        const cells = splitCells(a, line);
296        if (cells.len > named) return null;
297        rows[i + 1] = cells;
298    }
299
300    const widths = a.alloc(usize, named) catch return null;
301    @memset(widths, 3);
302    for (rows) |cells| {
303        for (cells, 0..) |cell, k| widths[k] = @max(widths[k], render.displayWidth(cell));
304    }
305
306    var block: std.ArrayList(u8) = .empty;
307    for (rows, 0..) |cells, r| {
308        if (r > 0) block.append(a, '\n') catch {};
309        emitRow(a, &block, indent, cells, named, widths, aligns, false);
310        if (r == 0) {
311            block.append(a, '\n') catch {};
312            emitRow(a, &block, indent, &.{}, named, widths, aligns, true);
313        }
314    }
315    if (trailing) block.append(a, '\n') catch {};
316    return block.items;
317}
318
319pub fn formatTables(a: std.mem.Allocator, text: []const u8) []const u8 {
320    var lines: std.ArrayList([]const u8) = .empty;
321    var it = std.mem.splitScalar(u8, text, '\n');
322    while (it.next()) |line| lines.append(a, line) catch {};
323
324    var out: std.ArrayList(u8) = .empty;
325    var i: usize = 0;
326    while (i < lines.items.len) {
327        const line = lines.items[i];
328        if (i + 1 < lines.items.len and tableCandidate(line)) {
329            if (delimiterRow(a, lines.items[i + 1])) |aligns| {
330                var end = i + 2;
331                while (end < lines.items.len and rowCells(lines.items[end])) end += 1;
332                const block = formatTable(a, line, aligns, lines.items[i + 2 .. end], end < lines.items.len);
333                if (block) |b| {
334                    out.appendSlice(a, b) catch {};
335                    i = end;
336                    continue;
337                }
338            }
339        }
340        out.appendSlice(a, line) catch {};
341        out.append(a, '\n') catch {};
342        i += 1;
343    }
344    if (out.items.len > 0 and text.len > 0 and text[text.len - 1] != '\n' and out.items[out.items.len - 1] == '\n')
345        out.items.len -= 1;
346    return out.items;
347}