1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
|
//! A markdown file's pipe tables (GFM), laid out in their own rows. Every
//! byte of a table stays in its row as the text it is: B1, B2, B3 and the
//! chords work on it as on any text, and nothing is drawn over it. What
//! changes is the width some bytes take. A cell narrower than its column
//! is given the cells it lacks as virtual width, a *pad*, before one of its
//! bytes (the `|` that ends it, or for a right-aligned column the first
//! byte after the `|` that starts it), so every row's `|` of a column falls
//! on the same screen column whatever the source spacing. A pad is to the
//! byte it stands before what a tab's extra cells are to the tab: drawn as
//! blanks, every one of them maps back to that byte (a click there puts
//! the caret before it), and the caret before that byte is drawn after the
//! pad, against its glyph.
//!
//! The pads are the only mapping. File.zig's pane-aware column functions
//! (`displayOffset`, `displayEndOffset`, `byteAtRowDisplay`) and the row
//! walks that draw a body (`fillBody`, `recolorSyntax`) add them, so the
//! caret, every selection, a click and a Look map between a cell's x and
//! its byte as they map a tab's. The look itself (`paint`: the `|` as rules,
//! the delimiter row as one, the header bold) restyles cells that are
//! there; it moves nothing.
//!
//! Which lines are tables is found by lines, as tree-sitter-markdown's
//! scanner finds a `pipe_table` (its PIPE_TABLE_START: a header row's cells
//! counted by its pipes, a delimiter row of `:?-+:?` cells, the same count),
//! once per revision of the text, over the whole text: the highlighter
//! parses only the lines around the view, which start mid-table as soon as
//! a long one is scrolled, and fenced code is known only from the top. The
//! grammar is the oracle in a test ("tables are the pipe_tables tree-sitter
//! finds").
const std = @import("std");
const panes = @import("panes.zig");
const pardes = @import("pardes.zig");
const colors = @import("colors.zig");
const modal = @import("modal.zig");
const Surface = @import("surface.zig").Surface;
const Cell = @import("surface.zig").Cell;
const Color = @import("surface.zig").Color;
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const File = panes.File;
const Tables = @This();
pub const Align = enum(u2) { left, right, center };
pub const Table = struct {
/// The header row's line; the delimiter row is the next.
first: u32,
/// One past the last row's line.
end: u32,
/// Where its columns' widths and alignments start in `widths`/`aligns`.
col0: u32,
/// Columns: the most cells any row ends with a `|`.
cols: u16,
/// The widest indentation before a leading `|`, in cells.
lead: u16,
/// The widest row laid out, in cells: a table wider than a wrapping
/// pane is shown as its source (`File.rowPads`).
width: u32,
};
/// `cells` of virtual width before the byte at `at` of its line.
pub const Pad = struct { at: u32, cells: u16 };
/// Columns past this many are not aligned (their pipes take no pad).
pub const max_cols = 64;
/// A centred column pads both sides of a cell, and a leading `|` its indent.
pub const max_pads = 2 * max_cols + 1;
/// The text these tables are of: its revision, where it is and how long.
revision: ?u32 = null,
content: usize = 0,
len: usize = 0,
list: std.ArrayList(Table) = .empty,
widths: std.ArrayList(u16) = .empty,
aligns: std.ArrayList(Align) = .empty,
pub fn deinit(t: *Tables, gpa: std.mem.Allocator) void {
t.list.deinit(gpa);
t.widths.deinit(gpa);
t.aligns.deinit(gpa);
t.* = .{};
}
/// Whether these tables are of `f`'s text as it is now.
pub fn current(t: *const Tables, f: *const File.State) bool {
return t.revision == f.revision and t.content == @intFromPtr(f.content.ptr) and t.len == f.content.len;
}
/// The table `line` is a row of, if any.
pub fn find(t: *const Tables, line: usize) ?*const Table {
const items = t.list.items;
var lo: usize = 0;
var hi: usize = items.len;
while (lo < hi) {
const mid = (lo + hi) / 2;
if (items[mid].end <= line) lo = mid + 1 else hi = mid;
}
if (lo < items.len and items[lo].first <= line) return &items[lo];
return null;
}
/// Find the tables of `f`'s text again unless they are of it already. Only
/// a markdown file has any; on no memory there are none (the text is shown
/// as it is).
pub fn ensure(t: *Tables, gpa: std.mem.Allocator, f: *const File.State) void {
if (t.current(f)) return;
t.revision = f.revision;
t.content = @intFromPtr(f.content.ptr);
t.len = f.content.len;
t.list.clearRetainingCapacity();
if (f.output != null or f.mini != null or !isMarkdown(f.path)) return;
scan(t, gpa, f.content) catch {
t.list.clearRetainingCapacity();
t.widths.clearRetainingCapacity();
t.aligns.clearRetainingCapacity();
};
}
pub fn isMarkdown(path: []const u8) bool {
return std.ascii.endsWithIgnoreCase(path, ".md") or std.ascii.endsWithIgnoreCase(path, ".markdown");
}
/// One line of the text: its bytes and its number.
const Line = struct { text: []const u8, start: usize, n: u32 };
fn lineAt(content: []const u8, start: usize, n: u32) ?Line {
if (start > content.len) return null;
const end = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len;
const text = content[start..end];
return .{ .text = if (text.len > 0 and text[text.len - 1] == '\r') text[0 .. text.len - 1] else text, .start = start, .n = n };
}
fn nextLine(content: []const u8, l: Line) ?Line {
const nl = std.mem.indexOfScalarPos(u8, content, l.start, '\n') orelse return null;
return lineAt(content, nl + 1, l.n + 1);
}
fn indentOf(text: []const u8) usize {
var i: usize = 0;
while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1;
return i;
}
fn blank(text: []const u8) bool {
return indentOf(text) == text.len;
}
/// A fence's opener (```` ``` ```` or `~~~`, three or more, up to three
/// spaces in): its character and length.
const Fence = struct { ch: u8, len: usize };
fn fenceOf(text: []const u8) ?Fence {
const in = indentOf(text);
if (in > 3 or in >= text.len) return null;
const ch = text[in];
if (ch != '`' and ch != '~') return null;
var n: usize = 0;
while (in + n < text.len and text[in + n] == ch) n += 1;
if (n < 3) return null;
// A backtick fence's info string has no backtick (CommonMark 4.5).
if (ch == '`' and std.mem.indexOfScalar(u8, text[in + n ..], '`') != null) return null;
return .{ .ch = ch, .len = n };
}
fn closes(text: []const u8, open: Fence) bool {
const f = fenceOf(text) orelse return false;
return f.ch == open.ch and f.len >= open.len and blank(text[indentOf(text) + f.len ..]);
}
/// A line that ends a table's rows by starting a block of its own (what
/// the grammar's paragraph_interrupt_symbols are): a heading, a fence, a
/// quote, a list item, a thematic break, HTML.
fn interrupts(text: []const u8) bool {
const in = indentOf(text);
if (in > 3 or in >= text.len) return false;
const rest = text[in..];
if (fenceOf(text) != null) return true;
switch (rest[0]) {
'#', '>', '<' => return true,
'-', '*', '+' => {
if (rest.len == 1 or rest[1] == ' ' or rest[1] == '\t') return true;
// A thematic break: three or more of one of -*_ and spaces.
var n: usize = 0;
for (rest) |b| {
if (b == rest[0]) n += 1 else if (b != ' ' and b != '\t') return false;
}
return n >= 3;
},
'0'...'9' => {
var i: usize = 0;
while (i < rest.len and i < 9 and std.ascii.isDigit(rest[i])) i += 1;
return i < rest.len and (rest[i] == '.' or rest[i] == ')') and (i + 1 == rest.len or rest[i + 1] == ' ');
},
else => return false,
}
}
/// A row's unescaped pipes, in order, and whether the row starts with one
/// (after its indentation) and ends with one (before trailing blanks).
const Pipes = struct {
at: [max_cols + 2]u32 = undefined,
n: usize = 0,
/// Pipes past `at`'s room: counted, not kept.
more: usize = 0,
leading: bool = false,
trailing: bool = false,
fn of(text: []const u8) Pipes {
var p: Pipes = .{};
const in = indentOf(text);
p.leading = in < text.len and text[in] == '|';
var last_ink: usize = text.len;
var i: usize = 0;
while (i < text.len) : (i += 1) {
const b = text[i];
if (b == '\\' and i + 1 < text.len and std.ascii.isPrint(text[i + 1]) and !std.ascii.isAlphanumeric(text[i + 1]) and text[i + 1] != ' ') {
last_ink = i + 1;
i += 1;
continue;
}
if (b == '|') {
if (p.n < p.at.len) {
p.at[p.n] = @intCast(i);
p.n += 1;
} else p.more += 1;
}
if (b != ' ' and b != '\t') last_ink = i;
}
p.trailing = p.n > 0 and last_ink == p.at[p.n - 1] and p.more == 0;
return p;
}
/// The cells the grammar counts: the pipes after a leading one, plus
/// the last cell when no pipe ends the row.
fn cells(p: *const Pipes) usize {
const pipes = p.n + p.more - @intFromBool(p.leading);
return pipes + @intFromBool(!p.trailing);
}
/// The pipe that ends cell `k` (the pipes after a leading one).
fn end(p: *const Pipes, k: usize) ?usize {
const i = k + @intFromBool(p.leading);
return if (i < p.n) p.at[i] else null;
}
/// Where cell `k` starts: after the pipe before it, or after the
/// indentation when it is the first and no pipe leads.
fn start(p: *const Pipes, k: usize) usize {
if (k == 0 and !p.leading) return 0;
return p.at[k - @intFromBool(!p.leading)] + 1;
}
};
/// A delimiter row's cells (`:?-+:?` between pipes), or null if `text` is
/// none: as the scanner reads one after a header.
fn delimiterCells(text: []const u8, out: *[max_cols]Align) ?usize {
var i = indentOf(text);
if (i > 3) return null;
var cells: usize = 0;
var pipes: usize = 0;
if (i < text.len and text[i] == '|') {
i += 1;
pipes += 1;
}
while (true) {
while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1;
if (i >= text.len) break;
if (text[i] == '|') {
cells += 1;
pipes += 1;
i += 1;
continue;
}
var left = false;
if (text[i] == ':') {
left = true;
i += 1;
if (i >= text.len or text[i] != '-') return null;
}
var dashes: usize = 0;
while (i < text.len and text[i] == '-') : (i += 1) dashes += 1;
if (dashes == 0) return null;
var right = false;
if (i < text.len and text[i] == ':') {
right = true;
i += 1;
}
if (cells < max_cols) out[cells] = if (left and right) .center else if (right) .right else .left;
cells += 1;
while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1;
if (i >= text.len) break;
if (text[i] != '|') return null;
pipes += 1;
i += 1;
}
if (pipes == 0) return null;
return cells;
}
/// The display width of a cell's bytes; ASCII is a cell a byte.
fn widthOf(text: []const u8) usize {
for (text) |b| if (b < 0x20 or b >= 0x7f) return File.displayWidth(text);
return text.len;
}
/// Find the tables of `content`, in place of the ones there were.
pub fn scan(t: *Tables, gpa: std.mem.Allocator, content: []const u8) !void {
t.list.clearRetainingCapacity();
t.widths.clearRetainingCapacity();
t.aligns.clearRetainingCapacity();
var fence: ?Fence = null;
var prev_blank = true;
var line = lineAt(content, 0, 0);
while (line) |l| {
const following = nextLine(content, l);
if (fence) |open| {
if (closes(l.text, open)) fence = null;
prev_blank = fence == null;
line = following;
continue;
}
if (fenceOf(l.text)) |open| {
fence = open;
prev_blank = false;
line = following;
continue;
}
const is_blank = blank(l.text);
var aligns: [max_cols]Align = undefined;
// A header starts a block: after a blank line, a heading or a fence
// (the grammar tries PIPE_TABLE_START where a paragraph could start).
if (!is_blank and prev_blank and indentOf(l.text) <= 3 and std.mem.indexOfScalar(u8, l.text, '|') != null) {
if (following) |delimiter| if (delimiterCells(delimiter.text, &aligns)) |count| {
const header = Pipes.of(l.text);
// A header's one pipe may not be its leading one alone,
// unless one ends it too (`| a |`, not `| a`).
const lone = header.n + header.more == @intFromBool(header.leading) and !(header.leading and header.trailing);
if (!lone and header.cells() == count) {
const last = try t.add(gpa, content, l, delimiter, aligns[0..@min(count, max_cols)]);
line = nextLine(content, last);
prev_blank = false;
continue;
}
};
}
// A heading line ends a block too: a header may follow it.
prev_blank = is_blank or std.mem.startsWith(u8, l.text[@min(indentOf(l.text), l.text.len)..], "#");
line = following;
}
}
/// Take the table whose header is `header`: its rows, its columns' widths
/// and its width. Returns its last row's line.
fn add(t: *Tables, gpa: std.mem.Allocator, content: []const u8, header: Line, delimiter: Line, aligns: []const Align) !Line {
var last = delimiter;
while (nextLine(content, last)) |row| {
if (blank(row.text) or interrupts(row.text)) break;
last = row;
}
const col0: u32 = @intCast(t.widths.items.len);
var table: Table = .{ .first = header.n, .end = last.n + 1, .col0 = col0, .cols = 0, .lead = 0, .width = 0 };
// Widths: each column's widest cell, the cell's bytes up to the pipe
// that ends it; a row's last cell with no pipe after it aligns nothing.
var row: ?Line = header;
while (row) |r| : (row = if (r.n == last.n) null else nextLine(content, r)) {
const pipes = Pipes.of(r.text);
if (pipes.leading) table.lead = @max(table.lead, @as(u16, @intCast(@min(widthOf(r.text[0..pipes.at[0]]), std.math.maxInt(u16)))));
var k: usize = 0;
while (k < max_cols) : (k += 1) {
const stop = pipes.end(k) orelse break;
const w: u16 = @intCast(@min(widthOf(r.text[pipes.start(k)..stop]), std.math.maxInt(u16)));
if (k >= table.cols) {
try t.widths.append(gpa, w);
try t.aligns.append(gpa, if (k < aligns.len) aligns[k] else .left);
table.cols += 1;
} else t.widths.items[col0 + k] = @max(t.widths.items[col0 + k], w);
}
}
// The width: each row laid out, its source width and its pads.
row = header;
var buf: [max_pads]Pad = undefined;
while (row) |r| : (row = if (r.n == last.n) null else nextLine(content, r)) {
var width = widthOf(r.text);
for (t.padsOf(&table, r.text, &buf)) |pad| width += pad.cells;
table.width = @max(table.width, @as(u32, @intCast(@min(width, std.math.maxInt(u32)))));
}
try t.list.append(gpa, table);
return last;
}
/// The pads of one of `table`'s rows, by byte, in order. No pad is ever at
/// byte 0: a row is drawn from its first byte, so there is no cell before
/// it to give.
pub fn padsOf(t: *const Tables, table: *const Table, text: []const u8, out: *[max_pads]Pad) []Pad {
const pipes = Pipes.of(text);
var n: usize = 0;
if (pipes.leading and pipes.at[0] > 0) {
const w = widthOf(text[0..pipes.at[0]]);
if (w < table.lead) {
out[n] = .{ .at = pipes.at[0], .cells = @intCast(table.lead - w) };
n += 1;
}
}
var k: usize = 0;
while (k < table.cols) : (k += 1) {
const stop = pipes.end(k) orelse break;
const from = pipes.start(k);
const w = widthOf(text[from..stop]);
const want = t.widths.items[table.col0 + k];
if (w >= want) continue;
const missing: u16 = @intCast(want - w);
// The first cell with no leading pipe starts at byte 0: it pads at
// its end, whatever its alignment.
const how: Align = if (from == 0) .left else t.aligns.items[table.col0 + k];
const before: u16 = switch (how) {
.left => 0,
.right => missing,
.center => missing / 2,
};
// An empty cell's start is its pipe: one pad there.
if (before > 0 and from < stop) {
out[n] = .{ .at = @intCast(from), .cells = before };
n += 1;
}
const after = if (from < stop) missing - before else missing;
if (after > 0) {
out[n] = .{ .at = @intCast(stop), .cells = after };
n += 1;
}
}
return out[0..n];
}
/// The cells of virtual width between byte `from` (excluded: its pad is
/// before the row's first shown byte) and byte `to` (included: its pad is
/// before its glyph), negative when `to` is before `from`.
pub fn between(pads: []const Pad, from: usize, to: usize) i32 {
const lo = @min(from, to);
const hi = @max(from, to);
var sum: i32 = 0;
for (pads) |pad| {
if (pad.at > hi) break;
if (pad.at > lo) sum += pad.cells;
}
return if (to >= from) sum else -sum;
}
/// The byte at display column `col` of a row shown from byte `from`, its
/// pads counted: a pad's cells are its byte's, as a tab's are the tab's.
/// Past the end, a virtual column a cell (File.rawAtDisplay).
pub fn byteAt(text: []const u8, pads: []const Pad, from_raw: usize, col: usize) usize {
if (from_raw >= text.len) return from_raw +| col;
var at = modal.graphemeStart(text, from_raw);
var k: usize = 0;
while (k < pads.len and pads[k].at <= at) k += 1;
var used: usize = 0;
while (at < text.len) {
if (k < pads.len and pads[k].at == at) {
used += pads[k].cells;
k += 1;
if (col < used) return at;
}
const end = modal.nextGrapheme(text, at);
used += File.graphemeDisplayWidth(text[at..end]);
if (col < used) return at;
at = end;
}
return text.len + (col - used);
}
/// What a table's `|` and its delimiter row are drawn as: light box-drawing
/// rules, each one cell, as the glyph of the byte that is there.
const rule_v = "\u{2502}";
const rule_h = "\u{2500}";
const rule_cross = "\u{253c}";
const rule_left = "\u{251c}";
const rule_right = "\u{2524}";
fn glyph(cell: *Cell, g: []const u8) void {
cell.default = false;
@memcpy(cell.text[0..g.len], g);
cell.len = @intCast(g.len);
}
/// A pane's table rows drawn as tables: every unescaped `|` a rule, the
/// delimiter row one rule across (its dashes, its blanks and its pads, its
/// `:` kept in the rule's colour, since they say the alignment), the header
/// row bold on the tag's ground, as compact context rows are. Only glyphs
/// and colours change, on the cells the row has: where each byte is and how
/// wide is fillBody's, so nothing is drawn over anything, B1 on a rule is
/// B1 on its `|`, and a selection's tint lies over the rules as over text.
pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void {
const f = if (pane.file) |*file| file else return;
if (f.tables.list.items.len == 0) return;
const th = p.theme();
const tint = p.settings.colors;
const rule_fg: Color = .{ .rgb = th.border orelse th.lineno };
const head_bg: Color = .{ .rgb = th.tag_bg };
const prefix: usize = File.gutterWidth(pane);
const body_y = p.bodyTop(pane, r);
var vr: u16 = 0;
while (vr < body_h) : (vr += 1) {
const w = pane.wrapAt(vr);
const table = File.rowTable(pane, w.line) orelse continue;
const text = File.sourceLine(pane, w.line);
var buf: [max_pads]Pad = undefined;
const pads = f.tables.padsOf(table, text, &buf);
const pipes = Pipes.of(text);
const delimiter = w.line == table.first + 1;
const header = w.line == table.first;
const y = body_y + vr;
// The row's walk, as fillBody lays it out from its first shown byte.
var at = modal.graphemeStart(text, @min(@as(usize, @intCast(@max(0, w.at))), text.len));
var col: usize = prefix + @as(usize, @intCast(w.pad));
var k: usize = 0;
while (k < pads.len and pads[k].at <= at) k += 1;
var q: usize = 0;
while (q < pipes.n and pipes.at[q] < at) q += 1;
while (at < text.len and col < tw) {
if (k < pads.len and pads[k].at == at) {
for (0..pads[k].cells) |i| {
if (col + i >= tw) break;
const cell = s.at(tx + @as(u16, @intCast(col + i)), y);
if (delimiter) {
glyph(cell, rule_h);
if (tint) cell.style.fg = rule_fg;
}
if (header and tint) cell.style.bg = head_bg;
}
col += pads[k].cells;
k += 1;
if (col >= tw) break;
}
const end = modal.nextGrapheme(text, at);
const cells = File.graphemeDisplayWidth(text[at..end]);
const cell = s.at(tx + @as(u16, @intCast(col)), y);
const pipe = q < pipes.n and pipes.at[q] == at;
if (pipe) {
q += 1;
glyph(cell, if (!delimiter)
rule_v
else if (q == 1 and pipes.leading)
rule_left
else if (q == pipes.n and pipes.trailing)
rule_right
else
rule_cross);
if (tint) cell.style.fg = rule_fg;
cell.style.bold = false;
} else if (delimiter) {
if (text[at] == '-' or text[at] == ' ') glyph(cell, rule_h);
if (tint) cell.style.fg = rule_fg;
} else if (header) {
cell.default = false;
cell.style.bold = true;
}
if (header and tint) for (0..cells) |i| {
if (col + i < tw) s.at(tx + @as(u16, @intCast(col + i)), y).style.bg = head_bg;
};
col += cells;
at = end;
}
}
}
// ---- tests ----
const testing = std.testing;
const config = @import("config.zig");
const Key = pardes.Key;
const sample =
"# Fruit\n" ++
"\n" ++
"| name | qty | note |\n" ++
"|:-----|----:|:----:|\n" ++
"| apple | 3 | red |\n" ++
"| kiwi | 12 | small and fuzzy |\n" ++
"| fig || |\n" ++
"\n" ++
"after\n";
/// A pane on `content` as a markdown file, drawn once.
fn testPane(p: *Pardes, content: []const u8, frame: std.mem.Allocator) !*Pane {
const pane = try p.setTestFile(content);
p.gpa.free(pane.file.?.path);
pane.file.?.path = try p.gpa.dupe(u8, "/notes.md");
_ = try p.render(frame);
return pane;
}
test "tables: a pipe table's columns, alignments and pads, by line" {
var t: Tables = .{};
defer t.deinit(testing.allocator);
try t.scan(testing.allocator, sample);
try testing.expectEqual(@as(usize, 1), t.list.items.len);
const table = t.list.items[0];
try testing.expectEqual(@as(u32, 2), table.first);
try testing.expectEqual(@as(u32, 7), table.end);
try testing.expectEqualSlices(u16, &.{ 7, 5, 17 }, t.widths.items);
try testing.expectEqualSlices(Align, &.{ .left, .right, .center }, t.aligns.items);
// `| fig || |`: the first cell short by 2 (left: before its `|`), the
// empty second by 5 (one pad at its pipe), the third by 16 (centred).
var buf: [max_pads]Pad = undefined;
const fig = "| fig || |";
try testing.expectEqualSlices(Pad, &.{
.{ .at = 6, .cells = 2 }, .{ .at = 7, .cells = 5 }, .{ .at = 8, .cells = 8 }, .{ .at = 9, .cells = 8 },
}, t.padsOf(&table, fig, &buf));
// `| apple | 3 | red |`: right-aligned 3 pads before its first byte.
try testing.expectEqualSlices(Pad, &.{
.{ .at = 9, .cells = 2 }, .{ .at = 13, .cells = 6 }, .{ .at = 18, .cells = 6 },
}, t.padsOf(&table, "| apple | 3 | red |", &buf));
// Every row laid out is one width: the table's.
try testing.expectEqual(@as(u32, 1 + 7 + 1 + 5 + 1 + 17 + 1), table.width);
// Not tables: a fence's rows, counts that differ, a delimiter alone.
for ([_][]const u8{
"```\n| a | b |\n|---|---|\n```\n",
"| a | b |\n|---|\n",
"|---|---|\n",
"| a\n|---\n",
}) |text| {
try t.scan(testing.allocator, text);
try testing.expectEqual(@as(usize, 0), t.list.items.len);
}
}
test "tables: every byte's cell maps back to it, and every pad cell to the byte after it" {
var t: Tables = .{};
defer t.deinit(testing.allocator);
try t.scan(testing.allocator, sample);
const table = &t.list.items[0];
var lines = std.mem.splitScalar(u8, sample, '\n');
var n: usize = 0;
while (lines.next()) |text| : (n += 1) {
if (n < table.first or n >= table.end) continue;
var buf: [max_pads]Pad = undefined;
const pads = t.padsOf(table, text, &buf);
var col: usize = 0;
for (text, 0..) |_, b| {
// The pad before b: each of its cells is b's.
const start = File.displayWidth(text[0..b]) + @as(usize, @intCast(between(pads, 0, b)));
while (col < start) : (col += 1) try testing.expectEqual(b, byteAt(text, pads, 0, col));
try testing.expectEqual(b, byteAt(text, pads, 0, col));
col += 1;
}
// Past the end, a virtual column a cell.
try testing.expectEqual(text.len + 2, byteAt(text, pads, 0, col + 2));
// From a scrolled start, the pads before it are not counted.
try testing.expectEqual(@as(usize, 2), byteAt(text, pads, 2, 0));
}
}
test "tables: a markdown table is drawn aligned, its bytes in order, the caret and a click on each byte's cell" {
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
var frame = std.heap.ArenaAllocator.init(testing.allocator);
defer frame.deinit();
const pane = try testPane(p, sample, frame.allocator());
const r = p.rects[0];
const text_x = r.x + config.GUTTER + File.gutterWidth(pane);
const body_y = p.bodyTop(pane, r);
// The k-th pipe of every row on one screen column.
var pipe_x: [4]?u16 = @splat(null);
for (2..7) |line| {
const text = File.sourceLine(pane, @intCast(line));
var k: usize = 0;
for (text, 0..) |b, i| {
const x = text_x + @as(u16, @intCast(File.displayOffset(pane, @intCast(line), 0, @intCast(i))));
const cell = p.surface.at(x, body_y + @as(u16, @intCast(line)));
if (b == '|') {
if (pipe_x[k]) |want| try testing.expectEqual(want, x) else pipe_x[k] = x;
try testing.expect(!std.mem.eql(u8, cell.grapheme(), " "));
k += 1;
} else if (line != 3) try testing.expectEqualStrings(text[i .. i + 1], cell.grapheme());
}
}
try testing.expectEqual(@as(u16, 1 + 7 + 1 + 5 + 1 + 17), pipe_x[3].? - text_x);
// The look: each `|` a rule; the delimiter row one rule across, its
// `:` kept; the header bold. The bytes under them are the source's.
const rule_y = body_y + 3;
var x = text_x;
while (x <= pipe_x[3].?) : (x += 1) {
const g = p.surface.at(x, rule_y).grapheme();
try testing.expect(std.mem.eql(u8, g, rule_h) or std.mem.eql(u8, g, rule_cross) or
std.mem.eql(u8, g, rule_left) or std.mem.eql(u8, g, rule_right) or std.mem.eql(u8, g, ":"));
}
try testing.expectEqualStrings(rule_left, p.surface.at(pipe_x[0].?, rule_y).grapheme());
try testing.expectEqualStrings(rule_cross, p.surface.at(pipe_x[1].?, rule_y).grapheme());
try testing.expectEqualStrings(rule_right, p.surface.at(pipe_x[3].?, rule_y).grapheme());
try testing.expectEqualStrings(rule_v, p.surface.at(pipe_x[2].?, body_y + 4).grapheme());
try testing.expect(p.surface.at(text_x + 2, body_y + 2).style.bold);
try testing.expect(!p.surface.at(text_x + 2, body_y + 4).style.bold);
try testing.expectEqualStrings("| name | qty | note |", File.sourceLine(pane, 2));
// B1 on any cell of `| fig || |`: the caret on the byte the cell is
// (a pad's cells are the byte after them), drawn where that byte is.
const fig: i32 = 6;
const text = File.sourceLine(pane, fig);
const y = body_y + 6;
var col: u16 = 0;
while (col < pipe_x[3].? - text_x + 1) : (col += 1) {
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + col, .row = y } });
p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + col, .row = y } });
const want = File.byteAtRowDisplay(pane, fig, 0, col);
try testing.expectEqual(fig, pane.body.cur_row);
try testing.expectEqual(want, pane.body.cur_col);
try testing.expect(want < text.len);
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
const caret = p.surface.cursor orelse return error.NoCaret;
try testing.expectEqual(text_x + @as(u16, @intCast(File.displayOffset(pane, fig, 0, want))), caret.x);
// The caret is on the cell clicked, or on the glyph after its pad.
try testing.expect(caret.x >= text_x + col);
}
// A pad cell: the empty second cell's five, all the `|` after them.
const empty_x = pipe_x[1].? - text_x + 1;
for (0..5) |i| try testing.expectEqual(@as(i32, 7), File.byteAtRowDisplay(pane, fig, 0, @intCast(empty_x + i)));
}
test "tables: typing in a cell re-aligns the table live, and j/k keep the column shown" {
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer p.deinit();
var frame = std.heap.ArenaAllocator.init(testing.allocator);
defer frame.deinit();
const pane = try testPane(p, sample, frame.allocator());
// On `3` in the apple row: insert before it.
pane.body.cur_row = 4;
pane.body.cur_col = 10;
p.update(.{ .key = .{ .cp = 'i', .text = "i" } });
for ("123456789") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } });
_ = frame.reset(.retain_capacity);
_ = try p.render(frame.allocator());
try testing.expectEqualStrings("| apple | 1234567893 | red |", File.sourceLine(pane, 4));
// The qty column is now 12 wide in every row.
for (2..7) |line| {
const text = File.sourceLine(pane, @intCast(line));
var k: usize = 0;
for (text, 0..) |b, i| {
if (b != '|') continue;
k += 1;
if (k == 3) try testing.expectEqual(@as(i32, 1 + 7 + 1 + 12), File.displayOffset(pane, @intCast(line), 0, @intCast(i)));
}
}
// k from the kiwi row's `and` keeps its screen column: the apple
// row's centred `red` under it.
p.update(.{ .key = .{ .cp = Key.escape } });
pane.body.cur_row = 5;
pane.body.cur_col = @intCast(std.mem.indexOf(u8, File.sourceLine(pane, 5), "and").?);
pane.body.vsel.active = false;
pane.body.sticky_col = -1;
const shown = File.displayOffset(pane, 5, 0, pane.body.cur_col);
p.update(.{ .key = .{ .cp = 'k', .text = "k" } });
try testing.expectEqual(@as(i32, 4), pane.body.cur_row);
try testing.expectEqual(shown, File.displayOffset(pane, 4, 0, pane.body.cur_col));
}
|