xonecas.io
79113
Ma

mini-coding-agent / files

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

9.1 KB
1const std = @import("std");
2const styles = @import("styles.zig");
3const format = @import("format.zig");
4
5const Span = struct {
6    start: u32,
7    end: u32,
8    style: styles.Style,
9};
10
11const Event = struct { at: u32, open: bool, span: usize, order: usize };
12
13fn eventLess(_: void, x: Event, y: Event) bool {
14    if (x.at != y.at) return x.at < y.at;
15    if (x.open != y.open) return !x.open and y.open;
16    return x.order < y.order;
17}
18
19fn paint(a: std.mem.Allocator, text: []const u8, spans: []const Span, base: styles.Style) []u8 {
20    var events: std.ArrayList(Event) = .empty;
21    for (spans, 0..) |span, i| {
22        if (span.end <= span.start or span.start >= text.len) continue;
23        events.append(a, .{ .at = span.start, .open = true, .span = i, .order = events.items.len }) catch {};
24        events.append(a, .{ .at = @min(span.end, @as(u32, @intCast(text.len))), .open = false, .span = i, .order = events.items.len }) catch {};
25    }
26    std.mem.sort(Event, events.items, {}, eventLess);
27
28    var out: std.ArrayList(u8) = .empty;
29    var active: std.ArrayList(usize) = .empty;
30    var plain = true;
31    var at: u32 = 0;
32
33    for (events.items) |event| {
34        emit(a, &out, &active, spans, text, event.at, &at, &plain, base);
35        if (event.open) {
36            active.append(a, event.span) catch {};
37        } else {
38            for (active.items, 0..) |idx, k| {
39                if (idx == event.span) {
40                    _ = active.orderedRemove(k);
41                    break;
42                }
43            }
44        }
45    }
46    emit(a, &out, &active, spans, text, @intCast(text.len), &at, &plain, base);
47    if (!plain) out.appendSlice(a, styles.sgrOn(a, .{}, base)) catch {};
48    return out.items;
49}
50
51fn emit(a: std.mem.Allocator, out: *std.ArrayList(u8), active: *std.ArrayList(usize), spans: []const Span, text: []const u8, end: u32, at: *u32, plain: *bool, base: styles.Style) void {
52    if (end <= at.*) return;
53    const reset = styles.sgrOn(a, .{}, base);
54    const style: ?styles.Style = if (active.items.len == 0) null else spans[active.items[active.items.len - 1]].style;
55    if (style) |s| {
56        const sgr = styles.sgrOn(a, s, base);
57        out.appendSlice(a, sgr) catch {};
58        plain.* = false;
59        const chunk = text[at.*..end];
60        for (chunk) |c| {
61            out.append(a, c) catch {};
62            if (c == '\n') out.appendSlice(a, sgr) catch {};
63        }
64    } else {
65        if (!plain.*) out.appendSlice(a, reset) catch {};
66        plain.* = true;
67        out.appendSlice(a, text[at.*..end]) catch {};
68    }
69    at.* = end;
70}
71
72fn muted() styles.Style {
73    return styles.roles.comment;
74}
75
76fn isAlnum(c: u8) bool {
77    return std.ascii.isAlphanumeric(c) or c == '_';
78}
79
80fn runLength(line: []const u8, at: usize, c: u8) usize {
81    var n: usize = 0;
82    while (at + n < line.len and line[at + n] == c) n += 1;
83    return n;
84}
85
86fn codeSpanEnd(line: []const u8, at: usize, limit: usize) ?usize {
87    const n = runLength(line, at, '`');
88    var i = at + n;
89    while (i < limit) : (i += 1) {
90        if (line[i] == '`' and runLength(line, i, '`') >= n) return i + n;
91    }
92    return null;
93}
94
95fn closeRun(line: []const u8, open_at: usize, marker: u8, count: usize, limit: usize) ?usize {
96    var i = open_at + count;
97    while (i + count <= limit) : (i += 1) {
98        if (line[i] == '\\') {
99            i += 1;
100            continue;
101        }
102        if (line[i] == '`') {
103            i = (codeSpanEnd(line, i, limit) orelse i + runLength(line, i, '`')) - 1;
104            continue;
105        }
106        if (line[i] != marker) continue;
107        if (line[i - 1] == ' ' or line[i - 1] == '\t') continue;
108        const run = runLength(line, i, marker);
109        if (run < count) continue;
110        if (marker == '_' and i + run < limit and isAlnum(line[i + run])) continue;
111        return i;
112    }
113    return null;
114}
115
116fn emphasis(count: usize) styles.Style {
117    return switch (count) {
118        1 => .{ .italic = true },
119        2 => .{ .bold = true },
120        else => .{ .bold = true, .italic = true },
121    };
122}
123
124fn addSpan(a: std.mem.Allocator, spans: *std.ArrayList(Span), base: u32, start: usize, end: usize, style: styles.Style) void {
125    if (end <= start) return;
126    spans.append(a, .{ .start = base + @as(u32, @intCast(start)), .end = base + @as(u32, @intCast(end)), .style = style }) catch {};
127}
128
129fn scanInline(a: std.mem.Allocator, line: []const u8, base: u32, start: usize, limit: usize, spans: *std.ArrayList(Span)) void {
130    var i = start;
131    while (i < limit) {
132        const c = line[i];
133        if (c == '\\' and i + 1 < limit) {
134            i += 2;
135            continue;
136        }
137        if (c == '`') {
138            const n = runLength(line, i, '`');
139            const end = codeSpanEnd(line, i, limit) orelse {
140                i += n;
141                continue;
142            };
143            addSpan(a, spans, base, i, end, styles.roles.inline_code);
144            i = end;
145            continue;
146        }
147        if (c == '*' or c == '_') {
148            const n = runLength(line, i, c);
149            const count: usize = @min(n, 3);
150            const content = i + count;
151            if (content >= limit or line[content] == ' ' or line[content] == '\t' or
152                (c == '_' and i > start and isAlnum(line[i - 1])))
153            {
154                i += n;
155                continue;
156            }
157            if (closeRun(line, i, c, count, limit)) |close| {
158                addSpan(a, spans, base, i, close + count, emphasis(count));
159                scanInline(a, line, base, content, close, spans);
160                i = close + count;
161            } else {
162                i += n;
163            }
164            continue;
165        }
166        if (c == '[') {
167            if (format.closeBracket(line[0..limit], i)) |close| {
168                if (close + 1 < limit and line[close + 1] == '(') {
169                    if (format.linkEnd(line[0..limit], close + 1)) |end| {
170                        addSpan(a, spans, base, i, close + 1, styles.roles.link);
171                        addSpan(a, spans, base, close + 1, end + 1, styles.roles.uri);
172                        i = end + 1;
173                        continue;
174                    }
175                }
176            }
177            i += 1;
178            continue;
179        }
180        i += 1;
181    }
182}
183
184fn leadingSpaces(line: []const u8) usize {
185    var i: usize = 0;
186    while (i < line.len and i < 3 and line[i] == ' ') i += 1;
187    return i;
188}
189
190fn blockMarker(line: []const u8) ?usize {
191    var at: usize = 0;
192    while (at < line.len and (line[at] == ' ' or line[at] == '\t')) at += 1;
193    if (at >= line.len) return null;
194    const c = line[at];
195    if (c == '>' or c == '-' or c == '*' or c == '+') {
196        if (at + 1 >= line.len or line[at + 1] == ' ' or line[at + 1] == '\t') return at + 1;
197        return null;
198    }
199    var n = at;
200    while (n < line.len and std.ascii.isDigit(line[n])) n += 1;
201    if (n == at or n >= line.len) return null;
202    if ((line[n] == '.' or line[n] == ')') and n + 1 < line.len and (line[n + 1] == ' ' or line[n + 1] == '\t')) return n + 1;
203    return null;
204}
205
206fn markdownLine(a: std.mem.Allocator, line: []const u8, base: u32, spans: *std.ArrayList(Span)) void {
207    const limit = line.len;
208    if (format.fenceRun(line) != null or format.isRule(line[leadingSpaces(line)..])) {
209        addSpan(a, spans, base, 0, limit, muted());
210        return;
211    }
212    var start: usize = 0;
213    while (blockMarker(line[start..])) |after| {
214        addSpan(a, spans, base, start, start + after, muted());
215        start += after;
216    }
217    const rest = line[start..];
218    if (format.heading(rest[leadingSpaces(rest)..])) |h| {
219        addSpan(a, spans, base, start, limit, styles.roles.heading(h.level));
220        return;
221    }
222    if (format.fenceRun(rest) != null or format.isRule(rest)) {
223        addSpan(a, spans, base, start, limit, muted());
224        return;
225    }
226    scanInline(a, line, base, start, limit, spans);
227}
228
229pub fn highlightMarkdown(a: std.mem.Allocator, text: []const u8) []const u8 {
230    var spans: std.ArrayList(Span) = .empty;
231    var it = std.mem.splitScalar(u8, text, '\n');
232    var base: u32 = 0;
233    while (it.next()) |line| {
234        markdownLine(a, line, base, &spans);
235        base += @intCast(line.len + 1);
236    }
237    return paint(a, text, spans.items, .{});
238}
239
240pub fn highlightCode(a: std.mem.Allocator, text: []const u8) []const u8 {
241    const end = if (text.len > 0 and text[text.len - 1] == '\n') text.len - 1 else text.len;
242    const spans = [_]Span{.{ .start = 0, .end = @intCast(end), .style = styles.roles.code }};
243    return paint(a, text, &spans, .{});
244}
245
246pub const DiffKind = enum { hunk, add, del, ctx, note };
247
248fn isFileHeader(line: []const u8) bool {
249    return std.mem.startsWith(u8, line, "--- ") or std.mem.startsWith(u8, line, "+++ ");
250}
251
252pub fn diffKind(line: []const u8, in_hunk: bool) DiffKind {
253    if (std.mem.startsWith(u8, line, "@@")) return .hunk;
254    if (std.mem.startsWith(u8, line, "\\")) return .note;
255    if (in_hunk) {
256        if (line.len > 0 and line[0] == '+') return .add;
257        if (line.len > 0 and line[0] == '-') return .del;
258        return .ctx;
259    }
260    if (isFileHeader(line)) return .note;
261    if (line.len > 0 and line[0] == '+') return .add;
262    if (line.len > 0 and line[0] == '-') return .del;
263    return .note;
264}