summaryrefslogtreecommitdiff
path: root/core/Band.zig
blob: 7d874319891374376e322804eb7beb3cb7227c47 (plain) (blame)
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
//! The band (walk UI, pick-ui SPEC.md §3.6): rows hanging under a pane's
//! tag while it is out of rest, in the tag's tint, pushing its body down:
//! the tag unrolled. Its steps stand side by side, each a column of rows
//! (a level, Help's rows, a doc; later a picker's acts and sources, a
//! prompt's history, the registers), a one-cell rule between them, right
//! of a spine under each of the head's key cells.
//!
//! Derived from the live view's state each time it is asked (`of`), never
//! stored (the coordinator's R2): the layout reads its height (`takes`,
//! Pardes.sync, layout.floorRows), the frame paints it (draw.zig
//! joinBand) as a tag layer of kind `.band`, and the mouse reads its words
//! (`line`): read-only text, which B2 executes and B3 looks at as a tag's.
//!
//! A new kind of step: a function that fills a `Step` (its `rows`, in the
//! frame's arena, as many as it shows, and whether it is a `doc`) from the
//! state that owns it, called from `of` for the tag state it belongs to,
//! with that state's rows in `height`; nothing else changes.
const Band = @This();

const std = @import("std");
const pardes = @import("root.zig");
const bindings = @import("bindings.zig");
const tagline = @import("tagline.zig");
const layout = @import("layout.zig");
const modal = @import("modal.zig");
const panes = @import("panes.zig");
const builtins = @import("builtins.zig");
const TagState = @import("TagState.zig");
const Names = @import("Names.zig");
const Prompt = @import("Prompt.zig");
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const File = panes.File;

/// One row of a step: its text, as B2 and B3 read it, and how it is drawn.
pub const Row = struct {
    text: []const u8,
    /// The rows' cursor: `▶` before it and the selection's tint over it.
    on: bool = false,
    /// Its first `key` bytes are a key: the key ink, bold.
    key: u8 = 0,
    /// Its first `chord` bytes are a chord (Help's `SPC h t`): the key ink
    /// at the text's weight.
    chord: u8 = 0,
    dim: bool = false,
    /// The leaf its group ran last.
    under: bool = false,
    /// The bytes a query matched: the match tint.
    marks: []const u16 = &.{},
    /// Its place in the list its step shows (a level's child, a hit): what
    /// a click on it moves the cursor to.
    index: u16 = 0,
    /// Marked in a picker's list: `•` before it.
    mark: bool = false,
    /// Its first `pre` bytes are a place (`file:line`, `@p3`): the name's
    /// tint; the `faint` bytes after them dimmed (a path's directory).
    pre: u16 = 0,
    faint: u16 = 0,
    /// Said at the row's right end in the dim ink, two cells off its text
    /// at least, and the first to give way (UX D5): `in use`.
    meta: []const u8 = "",
    /// Its bytes `quiet[0]..quiet[1]` in the dim ink: an empty register's
    /// `—`, a value's `⏎`.
    quiet: [2]u16 = .{ 0, 0 },
    /// Bytes that are keys, each in the key ink, bold: a register's verbs.
    keys: []const u16 = &.{},
};

/// A column of rows. A level of more than 9 rows flows into two columns
/// (`two`); a `doc` takes the width the others leave, wrapped to it, and is
/// the first to give way.
pub const Step = struct {
    rows: []const Row = &.{},
    two: bool = false,
    doc: bool = false,
    /// Where it starts and how wide it is, in the band's columns (`place`).
    x: u16 = 0,
    width: u16 = 0,
};

pub const max_steps = 4;
pub const max_spines = 12;
/// The narrowest a step is drawn (SPEC §3.6: box, spines, one 24-cell column).
pub const min_width = 24;
/// The widest a list's rows are laid out (UX D5).
const row_cells = 52;
/// A doc's rows, the fewest a band with one has.
const doc_rows = 4;
/// The body rows a band leaves its pane at least: it gives way first (UX D6).
pub const body_rows = 6;
/// A level's rows past which it flows into two columns.
const one_column = 9;

/// The columns of the head's key cells, in the band's columns: a spine
/// hangs under each.
spines: [max_spines]u16 = undefined,
nspines: u8 = 0,
steps: [max_steps]Step = undefined,
nsteps: u8 = 0,
height: u16 = 0,
/// The band's width at the tagline's pitch.
columns: u16 = 0,
/// The doc step it had no room for (UX D5's give-way): the notice row
/// says its first line (`docLeft`).
left: ?Step = null,

/// The rows the band under pane `id`'s tag takes in the live view, from
/// its state alone: the layout's term, asked before any frame is made.
pub fn takes(p: *Pardes, id: usize) u16 {
    const v = p.view();
    const s = &v.tag_state;
    if (TagState.hostOf(p) != id) return 0;
    switch (s.kind) {
        .rest => {},
        .help => return @max(doc_rows, @max(1, @min(Cursor.shown, s.nhits))),
        .describe => {
            if (!s.found) return 0;
            var children: [bindings.max_children]bindings.Child = undefined;
            return @max(doc_rows, levelRows(@intCast(bindings.level(p, s.scope_root.?, s.scope[0 .. s.scope_n - 1], &children).len)));
        },
        .pick => return @import("Pick.zig").bandRows(p),
        .prompt => return Prompt.takes(p),
        .rename => return 0,
    }
    if (!s.unrolled) return 0;
    const cur = TagState.current(p, v) orelse return 0;
    var children: [bindings.max_children]bindings.Child = undefined;
    const n: u16 = @intCast(bindings.level(p, cur.root, cur.path, &children).len);
    // The registers, one column of eleven at most (registerSteps).
    if (cur.root == .register and cur.path.len == 0) return @max(doc_rows, @min(Cursor.shown, n));
    return @max(doc_rows, levelRows(n));
}

/// A terminal's and a kind's band is drawn over the top rows of its body
/// (UX D6's borrowing, R3: drawn, never written): a transient state never
/// resizes a pty under a program or a kind's view (a PDF's), whose size
/// only the user's resize changes. Their `band_rows` stay 0.
pub fn over(pane: *const Pane) bool {
    return pane.isTerminal() or pane.addon != null;
}

/// The rows pane `id`'s band is drawn on: those it takes from the layout,
/// or over a terminal's or a kind's body, as many of its body rows as the
/// band wants.
pub fn shownRows(p: *Pardes, pane: *const Pane, id: usize) u16 {
    if (pane.band_rows > 0 or !over(pane) or pane.collapsed) return pane.band_rows;
    return @min(takes(p, id), p.view().rects[id].h -| pane.tag_rows);
}

fn levelRows(n: u16) u16 {
    return if (n > one_column) (n + 1) / 2 else n;
}

/// Pane `id`'s band as the live view's state has it, made in `arena`;
/// null when its tag has none.
pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band {
    const rows = takes(p, id);
    if (rows == 0) return null;
    const v = p.view();
    const s = &v.tag_state;
    var band: Band = .{ .height = rows, .columns = layout.tagCapacity(p, p.view().rects[id].w -| pardes.TAG_TEXT_INSET) };
    switch (s.kind) {
        .rest => {},
        .help => {
            try band.helpSteps(p, arena, s);
            try band.place(p, arena, pane, id);
            return band;
        },
        // describe-key's leaf: its level replayed, the leaf on the cursor,
        // and its doc.
        .describe => {
            const root = s.scope_root.?;
            const path = s.scope[0 .. s.scope_n - 1];
            var children: [bindings.max_children]bindings.Child = undefined;
            const level = bindings.level(p, root, path, &children);
            var at: usize = 0;
            for (level, 0..) |c, i| if (c.key == s.scope[s.scope_n - 1]) {
                at = i;
            };
            const node = bindings.nodeAt(root, path);
            band.add(try levelStep(arena, pane, level, at, if (node) |n| s.used[n.group] else 0));
            band.add(try docStep(p, arena, root, path, level[at]));
            try band.place(p, arena, pane, id);
            return band;
        },
        .pick => {
            for (try @import("Pick.zig").steps(p, arena)) |step| band.add(step);
            try band.place(p, arena, pane, id);
            return band;
        },
        .prompt => {
            var steps: [max_steps]Step = undefined;
            for (try Prompt.steps(p, arena, &steps)) |step| band.add(step);
            try band.place(p, arena, pane, id);
            return band;
        },
        .rename => return null,
    }
    const cur = TagState.current(p, v).?;
    if (cur.root == .register) {
        try band.registerSteps(p, arena, pane, cur.path);
        try band.place(p, arena, pane, id);
        return band;
    }
    // The level, its cursor on the child it names, else the leaf its group
    // ran last, else the first; and that child's doc beside it.
    const node = bindings.nodeAt(cur.root, cur.path);
    const used = if (node) |n| s.used[n.group] else 0;
    var children: [bindings.max_children]bindings.Child = undefined;
    const level = bindings.level(p, cur.root, cur.path, &children);
    var at: usize = 0;
    for (level, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) {
        at = i;
    };
    band.add(try levelStep(arena, pane, level, at, used));
    band.add(try docStep(p, arena, cur.root, cur.path, level[at]));
    try band.place(p, arena, pane, id);
    return band;
}

/// Help's rows around the cursor (`SPC t w  Wrap`, the query's bytes in
/// the match tint, the group `view` its meta: UX D5), and the cursor's
/// leaf's doc beside them.
fn helpSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, s: *const TagState) !void {
    if (s.nhits == 0) {
        const none = try arena.alloc(Row, 1);
        none[0] = .{ .text = if (s.field.len == 0) "no keys here" else "no key matches", .dim = true };
        band.add(.{ .rows = none });
        return;
    }
    const w = s.rows.window(s.nhits);
    const rows = try arena.alloc(Row, w.hi - w.lo);
    const q = s.field.text();
    for (rows, w.lo..) |*row, i| {
        const buf = try arena.create([TagState.row_max]u8);
        const leaf = TagState.helpLeaf(p, s.hits[i], buf);
        // Its leaf's `chord · word · group` as the chord (the key ink), two
        // blanks and the word; the group its meta (dim, at the right).
        var parts = std.mem.splitSequence(u8, leaf.row, " · ");
        const chord = parts.first();
        const text = try std.mem.concat(arena, u8, &.{ chord, "  ", parts.next() orelse "" });
        var marks: [Names.max_query * 4]u16 = undefined;
        var nmarks: usize = 0;
        if (std.mem.trim(u8, q, " ").len > 0) {
            const low = try std.ascii.allocLowerString(arena, text);
            if (Names.match(q, text, low, 0, &marks, &nmarks) == null) nmarks = 0;
        }
        row.* = .{ .text = text, .meta = parts.rest(), .on = i == s.rows.at, .chord = @intCast(@min(chord.len, 255)), .marks = try arena.dupe(u16, marks[0..nmarks]), .index = @intCast(i), .dim = bindings.dimmed(p.panes[p.view().active].?, leaf.child) };
    }
    band.add(.{ .rows = rows });
    var buf: [TagState.row_max]u8 = undefined;
    const at = TagState.helpLeaf(p, s.hits[s.rows.at], &buf);
    band.add(try docStep(p, arena, at.root, at.path[0 .. at.path.len - 1], at.child));
}

/// What a register's doc step offers next, its letters keys (UX D11).
const verbs = "p after  P before  R replace  y into";
const verb_keys = blk: {
    var out: [4]u16 = undefined;
    var n: usize = 0;
    for (0..verbs.len) |i| if (i == 0 or (i >= 2 and std.mem.eql(u8, verbs[i - 2 .. i], "  "))) {
        out[n] = i;
        n += 1;
    };
    break :blk out;
};

/// `"` unrolled (SPEC §9): the registers, a row each (its key, what it
/// is, its first line) around the cursor, or under `"a` its verbs; beside
/// them the value of the one on the cursor (or named) in full, as many of
/// its lines as the band has rows, only those read.
fn registerSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *const Pane, path: []const u8) !void {
    const s = &p.view().tag_state;
    var children: [bindings.max_children]bindings.Child = undefined;
    const level = bindings.level(p, .register, path, &children);
    const node = bindings.nodeAt(.register, path);
    const used = if (node) |n| s.used[n.group] else 0;
    var at: usize = 0;
    for (level, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) {
        at = i;
    };
    if (path.len > 0) band.add(try levelStep(arena, pane, level, at, used)) else {
        const w = (Cursor{ .at = @intCast(at) }).window(@intCast(level.len));
        const rows = try arena.alloc(Row, w.hi - w.lo);
        // A row each (UX D11): `key  value`, its name at the right; an
        // empty one's `—` and a newline's `⏎` dim.
        for (rows, w.lo..) |*row, i| {
            const c = level[i];
            const name = for (bindings.register_names) |r| {
                if (r.key == c.key) break r.name;
            } else "named";
            const key = bindings.keyName(c.key);
            const shown = try bindings.registerShown(arena, p.settings.tab, bindings.registerValue(p, c.key));
            const text = try std.fmt.allocPrint(arena, "{s}  {s}", .{ key, shown });
            const quiet = if (std.mem.eql(u8, shown, "—")) key.len + 2 else if (std.mem.endsWith(u8, shown, "⏎")) text.len - "⏎".len else text.len;
            row.* = .{
                .text = text,
                .on = i == at,
                .key = @intCast(key.len),
                .under = c.key == used,
                .index = @intCast(i),
                .meta = name,
                .quiet = .{ @intCast(quiet), @intCast(text.len) },
            };
        }
        band.add(.{ .rows = rows });
    }
    const key = if (path.len > 0) path[0] else level[at].key;
    const name = for (bindings.register_names) |r| {
        if (r.key == key) break r.name;
    } else "named";
    var rows: std.ArrayList(Row) = .empty;
    try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "\"{s} · {s}", .{ bindings.keyName(key), name }), .key = 2 });
    const value = bindings.registerValue(p, key);
    if (value.len == 0) try rows.append(arena, .{ .text = "(empty)", .dim = true });
    // A line is cut at what the band could show of it: a long one is
    // never scanned past that.
    const most = @as(usize, band.columns) * band.height;
    var rest = value;
    while (rest.len > 0 and rows.items.len + 1 < band.height) {
        const look = rest[0..@min(rest.len, most)];
        const end = std.mem.indexOfScalar(u8, look, '\n') orelse {
            try rows.append(arena, .{ .text = rest[0..if (look.len < rest.len) modal.graphemeStart(rest, look.len) else look.len] });
            break;
        };
        try rows.append(arena, .{ .text = look[0..end] });
        rest = rest[end + 1 ..];
    }
    if (path.len == 0) try rows.append(arena, .{ .text = verbs, .dim = true, .keys = &verb_keys });
    band.add(.{ .rows = rows.items, .doc = true });
}

/// A list's cursor and the rows of it a band shows: eleven at most, around
/// the cursor (SPEC §3.6, the prototype's `H.window`). Each view's (a
/// tag state's field): Help's rows, a picker's, a prompt's history.
pub const Cursor = struct {
    at: u16 = 0,

    pub const shown = 11;

    /// Rows [lo, hi) of `n` the band shows.
    pub fn window(c: Cursor, n: u16) struct { lo: u16, hi: u16 } {
        const lo = @min(c.at -| shown / 2, n -| shown);
        return .{ .lo = lo, .hi = @min(n, lo + shown) };
    }

    /// A key that steps a list of `n`: Down, C-j, C-n a row on, Up, C-k,
    /// C-p a row back, PageDown and PageUp ten; true when taken.
    pub fn key(c: *Cursor, k: pardes.Key, n: u16) bool {
        const Key = pardes.Key;
        const plain = !k.ctrl and !k.alt;
        const ctrl = k.ctrl and !k.alt;
        const step: i32 = if (plain and k.cp == Key.down or ctrl and (k.cp == 'j' or k.cp == 'n'))
            1
        else if (plain and k.cp == Key.up or ctrl and (k.cp == 'k' or k.cp == 'p'))
            -1
        else if (plain and k.cp == Key.page_down)
            10
        else if (plain and k.cp == Key.page_up)
            -10
        else
            return false;
        if (n == 0) return true;
        c.at = @intCast(std.math.clamp(@as(i32, c.at) + step, 0, @as(i32, n) - 1));
        return true;
    }
};

fn add(band: *Band, step: Step) void {
    if (band.nsteps == max_steps) return;
    band.steps[band.nsteps] = step;
    band.nsteps += 1;
}

/// A level's children as rows (`k Label`, a group's `label…`), the cursor
/// on child `at`.
pub fn levelStep(arena: std.mem.Allocator, pane: *const Pane, level: []const bindings.Child, at: usize, used: u8) !Step {
    const rows = try arena.alloc(Row, level.len);
    for (level, rows, 0..) |c, *row, i| {
        const key = bindings.keyName(c.key);
        row.* = .{
            .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group or c.more) "…" else "" }),
            .on = i == at,
            .key = @intCast(key.len),
            .dim = bindings.dimmed(pane, c),
            .under = c.key == used,
            .index = @intCast(i),
        };
    }
    return .{ .rows = rows, .two = level.len > one_column };
}

/// What child `c` is: a leaf's word and its whole documentation, then its
/// keys; a group's children, a row each.
pub fn docStep(p: *Pardes, arena: std.mem.Allocator, root: bindings.Root, path: []const u8, c: bindings.Child) !Step {
    var rows: std.ArrayList(Row) = .empty;
    const key = bindings.keyName(c.key);
    try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{s}  {s}{s}", .{ key, c.label, if (c.group) "…" else "" }), .key = @intCast(key.len) });
    if (c.group) {
        const here = try std.mem.concat(arena, u8, &.{ path, &.{c.key} });
        var below: [bindings.max_children]bindings.Child = undefined;
        for (bindings.level(p, root, here, &below)) |g| {
            const k = bindings.keyName(g.key);
            try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{s}  {s}{s}", .{ k, g.label, if (g.group) "…" else "" }), .key = @intCast(k.len) });
        }
        return .{ .rows = rows.items, .doc = true };
    }
    const doc = if (c.node) |n| switch (n.leaf.?) {
        .builtin => |b| builtins.registry.doc(b).text,
        .arg => |a| builtins.registry.doc(pardes.config.leader_args[a].cmd).text,
        .role => bindings.docOf(root, c, try arena.alloc(u8, 160)),
    } else bindings.docOf(root, c, &.{});
    try rows.append(arena, .{ .text = doc });
    // A leaf a language server answers, in a pane with none (SPEC §4.2).
    if (bindings.dimmed(p.panes[p.view().active].?, c)) try rows.append(arena, .{ .text = "needs a language server", .dim = true });
    var buf: [64]u8 = undefined;
    const here = try std.mem.concat(arena, u8, &.{ path, &.{c.key} });
    try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "keys  {s}", .{bindings.chord(root, here, &buf)}) });
    return .{ .rows = rows.items, .doc = true };
}

/// Where each step goes (UX D5): from two cells right of the last spine,
/// a rule's cell between steps with a blank each side of it; a level as wide as its widest row (two
/// columns past nine), a list of rows `row_cells` at most, a doc the width
/// the others leave, wrapped to it, `min_width` at least. Narrower than
/// the steps (the hints already gone from the head), the band gives way:
/// the doc leaves it, then the last step unrolled (a picker's acts) takes
/// the place of the others; one step left is held to the room there is,
/// its rows cut with `…` (Band.cutRow): the spines stay, nothing is clipped
/// off the right edge.
fn place(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !void {
    const tab = p.settings.tab;
    try band.findSpines(p, arena, pane, id);
    const x0: u16 = if (band.nspines > 0) band.spines[band.nspines - 1] + 2 else 0;
    var need: u16 = 0;
    var lists: u8 = 0;
    for (band.steps[0..band.nsteps]) |*step| {
        if (step.doc) continue;
        var widest: usize = 0;
        for (step.rows) |row| widest = @max(widest, File.displayWidth(tab, row.text) + if (row.meta.len > 0) 2 + File.displayWidth(tab, row.meta) else 0);
        const column: u16 = @intCast(@min(widest, row_cells) + 2);
        step.width = if (step.two) 2 * column + 1 else column;
        need += step.width + 3;
        lists += 1;
    }
    // The last list alone where they do not all fit.
    var skip: u8 = if (x0 + need > band.columns and lists > 1) lists - 1 else 0;
    var x = x0;
    var kept: u8 = 0;
    for (band.steps[0..band.nsteps]) |step| {
        var placed = step;
        if (step.doc) {
            const room = band.columns -| x;
            if (room < min_width) {
                band.left = step;
                continue;
            }
            placed.width = room;
            placed.rows = try wrap(arena, tab, step.rows, room -| 1, band.height);
        } else {
            if (skip > 0) {
                skip -= 1;
                continue;
            }
            placed.width = @min(placed.width, @max(band.columns -| x, @min(min_width, band.columns)));
        }
        placed.x = x;
        x +|= placed.width + 3;
        band.steps[kept] = placed;
        kept += 1;
    }
    band.nsteps = kept;
    // The last step, a list, takes what the band has left (UX E3): 52 cells
    // only when a step follows it; its meta at the band's right edge.
    if (kept > 0 and !band.steps[kept - 1].doc and !band.steps[kept - 1].two) {
        const last = &band.steps[kept - 1];
        last.width = @max(last.width, band.columns -| last.x);
    }
}

/// The display columns of the head's key cells: a spine hangs under each,
/// through the tag's rows under them and the band's (UX D5).
fn findSpines(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !void {
    const h = (try TagState.head(p, arena, pane)) orelse return;
    const whole = try tagline.tagText(p, arena, pane);
    const shown = try tagline.wrapTag(p.settings.tab, arena, whole, tagline.tagWidth(p, id));
    const lead = whole.len - h.text.len;
    for (h.spans[0..h.cells]) |span| {
        const at = modal.positionAt(shown.text, shown.fromReal(lead + span.lo));
        if (band.nspines == max_spines) return;
        band.spines[band.nspines] = @intCast(File.rawDisplayCol(p.settings.tab, modal.lineSlice(shown.text, at.row), at.col));
        band.nspines += 1;
    }
}

/// `rows` wrapped at `width` display columns, word by word, `height` rows
/// at most: a doc's paragraphs, a line each in its text (builtins.Doc),
/// each starting a row (a newline drawn in a row was a `�`).
fn wrap(arena: std.mem.Allocator, tab: u16, rows: []const Row, width: u16, max: u16) ![]const Row {
    var out: std.ArrayList(Row) = .empty;
    for (rows) |whole| {
        var paragraphs = std.mem.splitScalar(u8, whole.text, '\n');
        var row = whole;
        while (paragraphs.next()) |text| : (row = .{ .text = "" }) {
            if (out.items.len >= max) break;
            row.text = text;
            if (File.displayWidth(tab, row.text) <= width) {
                try out.append(arena, row);
            } else {
                var rest = row.text;
                while (rest.len > 0 and out.items.len < max) {
                    var cut = File.byteAtDisplay(tab, rest, width);
                    if (cut < rest.len) {
                        if (std.mem.lastIndexOfScalar(u8, rest[0..cut], ' ')) |space| {
                            if (space > 0) cut = space;
                        }
                    }
                    if (cut == 0) cut = modal.nextGrapheme(rest, 0);
                    try out.append(arena, .{ .text = std.mem.trimEnd(u8, rest[0..cut], " ") });
                    rest = std.mem.trimStart(u8, rest[cut..], " ");
                }
            }
        }
        if (out.items.len >= max) break;
    }
    if (out.items.len > max) out.shrinkRetainingCapacity(max);
    return out.items;
}

/// One row of the band as text, and where each step's row starts in it.
pub const Line = struct {
    text: []const u8,
    parts: []const Part,
    pub const Part = struct { col: u16, width: u16, row: Row };
};

/// Row `y`: the spines, then each step's row, padded to its width, a rule
/// between steps.
pub fn line(band: *const Band, arena: std.mem.Allocator, tab: u16, y: u16) !Line {
    var text: std.ArrayList(u8) = .empty;
    var parts: std.ArrayList(Line.Part) = .empty;
    var col: u16 = 0;
    for (band.spines[0..band.nspines]) |spine| {
        while (col < spine) : (col += 1) try text.append(arena, ' ');
        try text.appendSlice(arena, "│");
        col += 1;
    }
    for (band.steps[0..band.nsteps], 0..) |step, i| {
        if (i > 0) {
            while (col + 2 < step.x) : (col += 1) try text.append(arena, ' ');
            try text.appendSlice(arena, "│ ");
            col += 2;
        }
        while (col < step.x) : (col += 1) try text.append(arena, ' ');
        const per = if (step.two) (step.width - 1) / 2 else step.width;
        const shown: u16 = if (step.two) levelRows(@intCast(step.rows.len)) else @intCast(step.rows.len);
        var lane: u16 = 0;
        while (lane < @as(u16, if (step.two) 2 else 1)) : (lane += 1) {
            const k = y + lane * shown;
            const start = step.x + lane * (per + 1);
            while (col < start) : (col += 1) try text.append(arena, ' ');
            if (y >= shown or k >= step.rows.len) continue;
            const row = step.rows[k];
            const lead: []const u8 = if (step.doc) "" else if (row.on) "▶ " else if (row.mark) "• " else "  ";
            try text.appendSlice(arena, lead);
            col += @intCast(File.displayWidth(tab, lead));
            const room = per -| @as(u16, @intCast(File.displayWidth(tab, lead)));
            const fit = try cutRow(arena, tab, row, room);
            try parts.append(arena, .{ .col = col, .width = room, .row = fit });
            const at = col;
            try text.appendSlice(arena, fit.text);
            col += @intCast(File.displayWidth(tab, fit.text));
            // Its meta at the part's right end, when it fits after the
            // whole text: it gives way before the text is cut (UX D5).
            if (metaShown(tab, row, room)) {
                const meta: u16 = @intCast(File.displayWidth(tab, row.meta));
                while (col < at + room - meta) : (col += 1) try text.append(arena, ' ');
                try text.appendSlice(arena, row.meta);
                col += meta;
            }
        }
    }
    return .{ .text = text.items, .parts = parts.items };
}

/// The first line of the doc the live view's band had no room for (UX
/// D5's give-way): its first row and the first line of its text after it
/// (`w  Wrap: Toggles soft wrap`), into `buf`; what the notice row says in
/// place of the path while the band shows. Worked out from the state as
/// the frame's band is, in a room of its own on the stack.
pub fn docLeft(p: *Pardes, buf: []u8) ?[]const u8 {
    // A picker's steps are lists, never a doc: no band made twice a frame.
    if (p.view().tag_state.kind == .pick) return null;
    const id = TagState.hostOf(p) orelse return null;
    const pane = p.panes[id] orelse return null;
    if (takes(p, id) == 0) return null;
    var room: [Pane.prefix_room]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&room);
    const band = (of(p, fba.allocator(), pane, id) catch return null) orelse return null;
    const doc = band.left orelse return null;
    if (doc.rows.len == 0) return null;
    const first = doc.rows[0].text;
    if (doc.rows.len == 1) return std.fmt.bufPrint(buf, "{s}", .{first}) catch null;
    const text = doc.rows[1].text;
    return std.fmt.bufPrint(buf, "{s}: {s}", .{ first, text[0 .. std.mem.indexOfScalar(u8, text, '\n') orelse text.len] }) catch null;
}

/// Whether row `row`'s meta fits `room` cells after its text.
pub fn metaShown(tab: u16, row: Row, room: u16) bool {
    return row.meta.len > 0 and File.displayWidth(tab, row.text) + 2 + File.displayWidth(tab, row.meta) <= room;
}

/// Row `row` held to `room` cells (UX D2): a longer one cut with `…`, a
/// path (its directory faint: Find's rows) from the left
/// (`…core/Store.zig`), anything else from the right; its marks and faint
/// bytes moved with its text.
fn cutRow(arena: std.mem.Allocator, tab: u16, row: Row, room: u16) !Row {
    if (File.displayWidth(tab, row.text) <= room) return row;
    var fit = row;
    var marks: std.ArrayList(u16) = .empty;
    if (row.faint > 0 and row.pre == 0 and room > 1) {
        var from = row.text.len;
        while (from > 0) {
            const before = modal.prevGrapheme(row.text, from);
            if (File.displayWidth(tab, row.text[before..]) > room - 1) break;
            from = before;
        }
        fit.text = try std.mem.concat(arena, u8, &.{ "…", row.text[from..] });
        for (row.marks) |m| if (m >= from) try marks.append(arena, @intCast(m - from + "…".len));
        fit.faint = @intCast(if (row.faint > from) row.faint - from + "…".len else "…".len);
    } else {
        const cut = File.byteAtDisplay(tab, row.text, room -| 1);
        fit.text = try std.mem.concat(arena, u8, &.{ row.text[0..cut], if (room > 0) "…" else "" });
        for (row.marks) |m| if (m < cut) try marks.append(arena, m);
        fit.key = @intCast(@min(row.key, cut));
        fit.pre = @intCast(@min(row.pre, cut));
        fit.faint = @intCast(@min(row.faint, cut -| fit.pre));
    }
    fit.marks = marks.items;
    return fit;
}

/// The word under column `col` of band row `y` of pane `id`, at the
/// tagline's pitch: what B2 executes and B3 looks at.
pub fn wordAt(p: *Pardes, arena: std.mem.Allocator, id: usize, y: u16, col: u16) !?[]const u8 {
    const pane = p.panes[id] orelse return null;
    const band = (try of(p, arena, pane, id)) orelse return null;
    if (y >= band.height) return null;
    const ln = try band.line(arena, p.settings.tab, y);
    const at = File.rawAtDisplay(p.settings.tab, ln.text, col);
    const b = tagline.wordBoundsAtCol(ln.text, at) orelse return null;
    if (b.lo == b.hi) return null;
    return ln.text[b.lo..b.hi];
}

fn bandLayer(p: *Pardes, id: usize) ?*pardes.Layer {
    const layer = &p.surface.tag_layers[pardes.BAND_LAYER];
    return if (layer.rows > 0 and layer.kind == .band and layer.id == id) layer else null;
}

fn layerRow(arena: std.mem.Allocator, layer: *const pardes.Layer, row: usize) ![]const u8 {
    var out: std.ArrayList(u8) = .empty;
    for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try out.appendSlice(arena, cell.grapheme());
    return out.items;
}

test "a narrow band gives way and keeps its spines: the doc goes, the steps start two cells right of the last spine, no row past the band's edge; the band starts on the row under the head, in the rows the tag keeps from rest" {
    const Key = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 44, .rows = 30 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    p.sync();
    const rest = pane.tag_rows;
    try std.testing.expect(rest > 1);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    // Help for SPC l: its key cells `␣ l`, its rows, no room for a doc.
    for ([_]u21{ ' ', 'l', '?' }) |c| p.update(.{ .key = .{ .cp = c } });
    p.sync();
    const band = (try of(p, a, pane, id)).?;
    try std.testing.expectEqual(@as(u8, 2), band.nspines);
    try std.testing.expectEqual(@as(u8, 1), band.nsteps);
    try std.testing.expectEqual(band.spines[1] + 2, band.steps[0].x);
    for (0..band.height) |y| try std.testing.expect(File.displayWidth(p.settings.tab, (try band.line(a, p.settings.tab, @intCast(y))).text) <= band.columns);
    // The band on the row under the head's one, in the row the tag keeps
    // from rest (UX E3): never a blank row between the head and its rows,
    // the body under whichever is lower.
    const s = try p.render(a);
    const r = p.view().rects[id];
    const tag_y = p.tagTop(pane, r);
    try std.testing.expectEqual(@as(u16, 1), pane.tag_rows - pane.band_rows);
    try std.testing.expectEqual(@max(rest, 1 + band.height), pane.tag_rows);
    try std.testing.expectEqual(tag_y + 1, bandLayer(p, id).?.viewport.y);
    for (band.spines[0..band.nspines]) |col| try std.testing.expectEqualStrings("│", s.at(r.x + pardes.TAG_TEXT_INSET + col, tag_y + 1).grapheme());
    try std.testing.expect(std.mem.indexOf(u8, try layerRow(a, bandLayer(p, id).?, 0), "▶") != null);
    p.update(.{ .key = .{ .cp = Key.escape } });
}

test "out of rest with no band, the rows a tag keeps from rest stay blank: a spine hangs only where a band row is" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 44, .rows = 30 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    p.sync();
    const rest = pane.tag_rows;
    try std.testing.expect(rest > 1);
    // A search prompt: a key cell in its head, no band under it.
    p.update(.{ .key = .{ .cp = '/', .text = "/" } });
    p.sync();
    try std.testing.expectEqual(@as(u16, 0), pane.band_rows);
    try std.testing.expectEqual(rest, pane.tag_rows);
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const s = try p.render(frame.allocator());
    const r = p.view().rects[id];
    const tag_y = p.tagTop(pane, r);
    for (1..rest) |row| for (0..r.w) |x| try std.testing.expect(!std.mem.eql(u8, "│", s.at(r.x + @as(u16, @intCast(x)), tag_y + @as(u16, @intCast(row))).grapheme()));
}

test "steps stand apart: one blank, the rule, one blank between a step and the next, its widest row's text never touching the rule (UX D5)" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const tab = p.settings.tab;
    // Help: its rows, the doc beside them.
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = '?' } });
    const band = (try of(p, a, pane, id)).?;
    try std.testing.expect(band.nsteps >= 2);
    for (band.steps[1..band.nsteps]) |step| for (0..band.height) |y| {
        const ln = try band.line(a, tab, @intCast(y));
        const at = File.rawAtDisplay(tab, ln.text, step.x - 3);
        try std.testing.expect(std.mem.startsWith(u8, ln.text[at..], " │ "));
    };
}

test "Help's rows say the chord, two blanks and the word; the group is the row's meta, right-aligned at its step's edge in the dim ink: no ` · ` (UX D5, D4)" {
    const Cells = struct {
        /// The cell `word` starts at, a grapheme a cell.
        fn find(cells: []const pardes.Cell, word: []const u8) ?usize {
            var at: usize = 0;
            while (at + word.len <= cells.len) : (at += 1) {
                for (word, cells[at..][0..word.len]) |c, cell| {
                    if (cell.len != 1 or cell.text[0] != c) break;
                } else return at;
            }
            return null;
        }
    };
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const selected = p.chromeTheme().roles.selectedOn(if (pardes.Trail.reading(p, pane)) .reading_focused else .focused);
    for ([_]u21{ ' ', '?', 'w', 'r', 'a', 'p' }) |c| p.update(.{ .key = .{ .cp = c } });
    const band = (try of(p, a, pane, id)).?;
    const step = band.steps[0];
    var found = false;
    for (step.rows) |row| {
        try std.testing.expect(std.mem.indexOf(u8, row.text, " · ") == null);
        if (!std.mem.eql(u8, row.text, "SPC t w  Wrap")) continue;
        try std.testing.expectEqualStrings("view", row.meta);
        found = true;
    }
    try std.testing.expect(found);
    _ = try p.render(a);
    const layer = bandLayer(p, id).?;
    for (0..layer.rows) |y| {
        const cells = layer.cells[y * layer.cols ..][0..layer.cols];
        if (Cells.find(cells, "SPC t w  Wrap") == null) continue;
        const at = Cells.find(cells, "view").?;
        try std.testing.expectEqual(@as(usize, step.x + step.width - "view".len), at);
        try std.testing.expectEqual(pardes.Color{ .rgb = selected.dim }, cells[at].style.fg);
        break;
    } else return error.TestUnexpectedResult;
}

test "a doc the band has no room for leaves it for the notice row: its first row and the first line of its text, in place of the path" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 44, .rows = 30 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    p.messages.live_len = 0;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    var buf: [pardes.Messages.notice_row_cap]u8 = undefined;
    // Help for SPC l at 44 columns: no room for its doc.
    for ([_]u21{ ' ', 'l', '?' }) |c| p.update(.{ .key = .{ .cp = c } });
    const band = (try of(p, a, pane, id)).?;
    const doc = band.left.?;
    const row = pardes.Messages.noticeRow(p, 60, &buf);
    const left = row.text[0..row.left];
    try std.testing.expect(std.mem.startsWith(u8, left, doc.rows[0].text) and std.mem.indexOf(u8, left, ": ") != null);
    try std.testing.expect(std.mem.indexOf(u8, left, "test.txt") == null);
    // At rest, the path again.
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expect(std.mem.startsWith(u8, pardes.Messages.noticeRow(p, 60, &buf).text, "/test.txt"));
}

test "a row longer than its room is cut with `…`: a path from the left, anything else from the right, its marks and faint bytes moved with it" {
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const path = try cutRow(a, 8, .{ .text = "core/deep/dir/Store.zig", .faint = 14, .marks = &.{ 0, 14, 15 } }, 12);
    try std.testing.expectEqualStrings("…r/Store.zig", path.text);
    try std.testing.expectEqual(@as(u16, 5), path.faint);
    try std.testing.expectEqualSlices(u16, &.{ 5, 6 }, path.marks);
    const other = try cutRow(a, 8, .{ .text = "a.zig:3:1: hello world", .pre = 9, .marks = &.{ 10, 20 } }, 12);
    try std.testing.expectEqualStrings("a.zig:3:1: …", other.text);
    try std.testing.expectEqualSlices(u16, &.{10}, other.marks);
    const fits = try cutRow(a, 8, .{ .text = "short" }, 12);
    try std.testing.expectEqualStrings("short", fits.text);
}

test "SPC Down unrolls the level into a band under the tag's text, the body pushed down and never drawn over; Up on its first row rolls it up" {
    const Key = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("one\ntwo\nthree\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    p.sync();
    const r = p.view().rects[id];
    const text_rows = pane.tag_rows;
    const body_top = p.bodyTop(pane, r);
    _ = try p.render(frame.allocator());
    try std.testing.expect(bandLayer(p, id) == null);
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = Key.down } });
    try std.testing.expect(p.view().tag_state.unrolled);
    // SPC's top has more than nine children: two columns, and a doc.
    try std.testing.expect(pane.band_rows >= doc_rows);
    try std.testing.expectEqual(text_rows + pane.band_rows, pane.tag_rows);
    try std.testing.expectEqual(body_top + pane.band_rows, p.bodyTop(pane, r));
    _ = frame.reset(.retain_capacity);
    const s = try p.render(frame.allocator());
    const layer = bandLayer(p, id).?;
    try std.testing.expectEqual(p.tagTop(pane, r) + text_rows, layer.viewport.y);
    try std.testing.expectEqual(pane.band_rows, layer.viewport.h);
    // The body region starts under the band: nothing is drawn over it.
    const body = s.region(.body, id).?;
    try std.testing.expectEqual(layer.viewport.y + layer.viewport.h, body.rect.y);
    const first = try layerRow(frame.allocator(), layer, 0);
    try std.testing.expect(std.mem.indexOf(u8, first, "│") != null);
    try std.testing.expect(std.mem.indexOf(u8, first, "▶ b buffer…") != null);
    // The grid has the same row, where the layer is.
    var grid: std.ArrayList(u8) = .empty;
    for (s.cells[@as(usize, layer.viewport.y) * s.cols ..][layer.viewport.x..][0..layer.viewport.w]) |cell| try grid.appendSlice(frame.allocator(), cell.grapheme());
    try std.testing.expect(std.mem.indexOf(u8, grid.items, "▶ b buffer…") != null);
    // The head names the level and says how to roll it up.
    const head = try tagline.tagText(p, frame.allocator(), pane);
    try std.testing.expect(std.mem.startsWith(u8, head, "␣ SPC  ") and std.mem.endsWith(u8, head, "  ↑ roll up · ? field · esc"));
    // Down moves the cursor; Up back to the first row, then rolls up.
    p.update(.{ .key = .{ .cp = Key.down } });
    try std.testing.expectEqual(@as(u8, 'c'), p.view().tag_state.hi);
    p.update(.{ .key = .{ .cp = Key.up } });
    try std.testing.expect(p.view().tag_state.unrolled);
    p.update(.{ .key = .{ .cp = Key.up } });
    try std.testing.expect(!p.view().tag_state.unrolled);
    try std.testing.expectEqual(@as(u16, 0), pane.band_rows);
    try std.testing.expectEqual(body_top, p.bodyTop(pane, r));
    // Unrolled, Right enters the cursor's group and Left leaves it.
    p.update(.{ .key = .{ .cp = Key.down } });
    p.update(.{ .key = .{ .cp = Key.right } });
    try std.testing.expectEqualStrings("b", p.view().leader_keys[0..p.view().leader_n]);
    try std.testing.expect(p.view().tag_state.unrolled);
    p.update(.{ .key = .{ .cp = Key.left } });
    try std.testing.expectEqual(@as(u8, 0), p.view().leader_n);
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(@as(u16, 0), pane.band_rows);
    try std.testing.expect(!p.view().tag_state.unrolled);
}

test "a band keeps its pane's body 60 % of the pane, borrowed from its column; where the column has not the rows, the band gives way before the body drops under 6" {
    const Key = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    const top = p.view().active;
    p.newScratchBelow(top);
    const low = p.view().active;
    p.newScratchBelow(low);
    p.view().active = low;
    p.sync();
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = Key.down } });
    const pane = p.panes[low].?;
    const r = p.view().rects[low];
    try std.testing.expect(pane.band_rows >= doc_rows);
    try std.testing.expect(@as(u32, r.h -| pane.tag_rows) * 5 >= @as(u32, r.h) * 3);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // A window of 12 rows: the band shrinks, the body keeps 6.
    p.update(.{ .resize = .{ .cols = 120, .rows = 12 } });
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = Key.down } });
    p.sync();
    const short = p.view().rects[low];
    try std.testing.expect(short.h -| pane.tag_rows >= 6 or pane.band_rows == 0);
    try std.testing.expect(pane.band_rows < Band.takes(p, low));
}

test "a pane whose body would drop below six rows under its band borrows them from its column" {
    const Key = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    const top = p.view().active;
    p.newScratchBelow(top);
    const low = p.view().active;
    p.newScratchBelow(low);
    p.view().active = low;
    p.sync();
    const before = p.view().rects[low].h;
    p.update(.{ .key = .{ .cp = ' ' } });
    p.update(.{ .key = .{ .cp = Key.down } });
    const pane = p.panes[low].?;
    const r = p.view().rects[low];
    try std.testing.expect(r.h > before);
    // Its body six rows at least (UX D6): a column too short for 60 %.
    try std.testing.expect(r.h -| pane.tag_rows >= 6);
    // No pane dims out of rest (UX D9): the others look as at rest.
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const s = try p.render(frame.allocator());
    const other = p.view().rects[top];
    try std.testing.expect(!s.at(other.x + 3, other.y).style.dim);
    try std.testing.expect(!s.at(other.x + 3, other.y + 1).style.dim);
    try std.testing.expect(!s.at(r.x + 3, r.y).style.dim);
    p.update(.{ .key = .{ .cp = Key.escape } });
    try std.testing.expectEqual(before, p.view().rects[low].h);
}

test "the band's words are read-only text: B2 runs one, the tag back at rest" {
    const Key = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    for ([_]u21{ ' ', 't', Key.down }) |c| p.update(.{ .key = .{ .cp = c } });
    const s = try p.render(frame.allocator());
    const layer = bandLayer(p, id).?;
    // Find `Wrap` in the grid's copy of the band.
    const at = found: for (0..layer.rows) |row| {
        const y = layer.viewport.y + row;
        var x: u16 = layer.viewport.x;
        while (x + 4 < layer.viewport.x + layer.viewport.w) : (x += 1) {
            const cells = s.cells[@as(usize, y) * s.cols + x ..][0..4];
            if (std.mem.eql(u8, cells[0].grapheme(), "W") and std.mem.eql(u8, cells[1].grapheme(), "r") and std.mem.eql(u8, cells[2].grapheme(), "a") and std.mem.eql(u8, cells[3].grapheme(), "p"))
                break :found .{ x + 1, @as(u16, @intCast(y)) };
        }
    } else return error.NoWrapInTheBand;
    const wrapped = p.settings.wrap;
    p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = at[0], .row = at[1] } });
    p.update(.{ .mouse = .{ .button = .middle, .kind = .release, .col = at[0], .row = at[1] } });
    try std.testing.expect(p.settings.wrap != wrapped);
    try std.testing.expect(p.view().prefix == .none and !p.view().tag_state.unrolled);
}

test "a doc's paragraphs are rows of their own: no newline in a band's row" {
    const Key = pardes.Key;
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    // SPC b b is Panes, whose documentation has three paragraphs.
    for ([_]u21{ ' ', 'b', Key.down }) |c| p.update(.{ .key = .{ .cp = c } });
    const band = (try of(p, a, p.panes[id].?, id)).?;
    var docs: usize = 0;
    for (band.steps[0..band.nsteps]) |step| for (step.rows) |row| {
        try std.testing.expect(std.mem.indexOfScalar(u8, row.text, '\n') == null);
        if (step.doc) docs += 1;
    };
    try std.testing.expect(docs > 2);
}

test "a band is drawn in the theme's roles (UX D4): spines in the rule ink, a chord in the key ink, a matched letter bold in the match ink on its row's own ground, the cursor row's too; an LSP leaf with no server in the dim ink, never faint, its doc saying why" {
    const Key = pardes.Key;
    const Cells = struct {
        /// The cell `word` starts at, a grapheme a cell.
        fn find(cells: []const pardes.Cell, word: []const u8) ?usize {
            var at: usize = 0;
            while (at + word.len <= cells.len) : (at += 1) {
                for (word, cells[at..][0..word.len]) |c, cell| {
                    if (cell.len != 1 or cell.text[0] != c) break;
                } else return at;
            }
            return null;
        }
    };
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const id = p.view().active;
    var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer frame.deinit();
    const a = frame.allocator();
    const roles = &p.chromeTheme().roles;
    const inks = roles.on(if (pardes.Trail.reading(p, pane)) .reading_focused else .focused);
    const selected = roles.selectedOn(if (pardes.Trail.reading(p, pane)) .reading_focused else .focused);
    // Help with `wrap` typed: `▶ SPC t w · Wrap · view` on the cursor row.
    for ([_]u21{ ' ', '?', 'w', 'r', 'a', 'p' }) |c| p.update(.{ .key = .{ .cp = c } });
    _ = try p.render(a);
    var layer = bandLayer(p, id).?;
    var spines: usize = 0;
    var cursor_row: ?usize = null;
    for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| {
        try std.testing.expect(!cell.style.dim);
        if (std.mem.eql(u8, cell.grapheme(), "│")) {
            try std.testing.expectEqual(pardes.Color{ .rgb = inks.rule }, cell.style.fg);
            spines += 1;
        }
        if (std.mem.eql(u8, cell.grapheme(), "▶")) {
            cursor_row = row;
            // The cursor's `▶` in the key ink on the selection, which
            // covers its lead too (UX D4, D5).
            try std.testing.expectEqual(pardes.Color{ .rgb = roles.key }, cell.style.fg);
            try std.testing.expectEqual(pardes.Color{ .rgb = selected.ground }, cell.style.bg);
        }
    };
    try std.testing.expect(spines > 0);
    const on = layer.cells[cursor_row.? * layer.cols ..][0..layer.cols];
    const s_cell = on[Cells.find(on, "SPC t w").?];
    try std.testing.expectEqual(pardes.Color{ .rgb = roles.key }, s_cell.style.fg);
    try std.testing.expect(!s_cell.style.bold);
    var matched: usize = 0;
    for (on) |cell| if (std.meta.eql(cell.style.fg, pardes.Color{ .rgb = roles.match })) {
        try std.testing.expect(cell.style.bold);
        try std.testing.expectEqual(pardes.Color{ .rgb = selected.ground }, cell.style.bg);
        matched += 1;
    };
    try std.testing.expect(matched >= 4);
    p.update(.{ .key = .{ .cp = Key.escape } });
    // SPC l unrolled in a text file no server speaks for: its leaves dim.
    for ([_]u21{ ' ', 'l', Key.down }) |c| p.update(.{ .key = .{ .cp = c } });
    _ = try p.render(a);
    layer = bandLayer(p, id).?;
    var dimmed: usize = 0;
    var why = false;
    for (0..layer.rows) |row| {
        const cells = layer.cells[row * layer.cols ..][0..layer.cols];
        if (Cells.find(cells, "needs a language server") != null) why = true;
        const cell = cells[Cells.find(cells, "Hover") orelse continue];
        try std.testing.expect(!cell.style.dim);
        try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cell.style.fg);
        dimmed += 1;
    }
    try std.testing.expect(dimmed > 0 and why);
}