summaryrefslogtreecommitdiff
path: root/core/Band.zig
blob: 7f9cfc7bd83a51f60275fc91a7d0a902cef8389e (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
//! 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,
    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,
};

/// 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;
/// A doc's rows, the fewest a band with one has.
const doc_rows = 4;
/// 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 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 => return 0,
        .prompt => return Prompt.takes(p),
    }
    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);
    return @max(doc_rows, levelRows(n));
}

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 => return null,
        .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;
        },
    }
    const cur = TagState.current(p, v).?;
    // 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 (`chord · word · group`, the query's bytes in the match
/// tint) around the cursor, 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);
        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, leaf.row);
            _ = Names.match(q, leaf.row, low, 0, &marks, &nmarks);
        }
        row.* = .{ .text = leaf.row, .on = i == s.rows.at, .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));
}

/// 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) "…" 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 });
    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: right of the spines, a rule's cell between steps;
/// a doc takes what is left, wrapped to it. Narrow, the doc goes first,
/// then the spines (the steps start at the band's left 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);
    var x: u16 = if (band.nspines > 0) band.spines[band.nspines - 1] + 2 else 0;
    var need: u16 = 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));
        const column: u16 = @intCast(@min(widest + 2, std.math.maxInt(u16) / 4));
        step.width = if (step.two) 2 * column + 1 else column;
        need += step.width + 2;
    }
    if (x + need > band.columns) {
        band.nspines = 0;
        x = 0;
    }
    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) continue;
            placed.width = room;
            placed.rows = try wrap(arena, tab, step.rows, room -| 1, band.height);
        }
        placed.x = x;
        x +|= placed.width + 2;
        band.steps[kept] = placed;
        kept += 1;
    }
    band.nsteps = kept;
}

/// The display columns of the head's key cells, when they are all on the
/// tag's last row (the spines hang from there).
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;
    const last = shown.rows() -| 1;
    for (h.spans[0..h.cells]) |span| {
        const at = modal.positionAt(shown.text, shown.fromReal(lead + span.lo));
        if (at.row != last or band.nspines == max_spines) {
            band.nspines = 0;
            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.
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) |row| {
        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 "  ";
            try text.appendSlice(arena, lead);
            col += @intCast(File.displayWidth(tab, lead));
            try parts.append(arena, .{ .col = col, .width = per -| @as(u16, @intCast(File.displayWidth(tab, lead))), .row = row });
            const room = per -| @as(u16, @intCast(File.displayWidth(tab, lead)));
            const cut = File.byteAtDisplay(tab, row.text, room);
            try text.appendSlice(arena, row.text[0..cut]);
            col += @intCast(File.displayWidth(tab, row.text[0..cut]));
        }
    }
    return .{ .text = text.items, .parts = parts.items };
}

/// 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_BASE + id];
    return if (layer.rows > 0 and layer.kind == .band) 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 "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.
    try std.testing.expect(std.mem.endsWith(u8, try tagline.tagText(p, frame.allocator(), pane), " ␣ SPC   ↑ 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 pane whose body would drop below four 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);
    try std.testing.expect(r.h -| pane.tag_rows >= 4);
    // The other panes dim; the one out of rest does not.
    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(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);
}