summaryrefslogtreecommitdiff
path: root/core/Trail.zig
blob: cb5dedf82d7c0c00450e5a52e98309514d40b69c (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
//! A pane's walk (pick-ui SPEC §6): the places a reading pane stepped
//! through, written as words in its tag before its path, and whether it
//! is held. A held pane (edited, kept, or not a file) never walks: a jump
//! from it steps its one reader, a reading pane below it whose trail
//! starts with it (`‹@p3`). A reading pane steps in place.
//!
//! The steps are one array, oldest first: `cur` is where the pane is (its
//! place as it was at its last step: the caret is the truth between
//! steps), the steps before it the back steps, the ones after it the
//! forward steps a step back left, drawn dimmed after the path.
const std = @import("std");
const pardes = @import("root.zig");
const Kind = @import("Kind.zig");
const config = @import("config.zig");
const layout = @import("layout.zig");
const panes = @import("panes.zig");
const look = @import("look.zig");
const Pardes = pardes.Pardes;
const Pane = panes.Pane;
const Spot = look.Spot;

const Trail = @This();

/// The steps a trail keeps; past it the oldest go, the owner kept first.
pub const max_steps = 16;
/// The bytes of a step's path or word. A jump to a longer path is no step:
/// it opens a pane as `Jumps new-pane` does (look.zig open).
pub const max_text = 256;
/// The newest back steps written whole; older ones fold to `·` (§6.3).
pub const shown_steps = 3;

/// `cur` held to the steps there are (walk.zig `.place`).
pub const replica = .{ .len = .{.{ "steps", "n" }}, .place = .{.{ "cur", "lastCur" }} };

steps: [max_steps]Step = undefined,
n: u8 = 0,
cur: u8 = 0,
/// Kept, or edited since it was shown: it no longer walks (§6.5).
held: bool = false,

/// `cur` is at most `n`: a held pane's (keep, a search's or a recipe's
/// word alone) has no current place, past its steps.
pub fn lastCur(t: *const Trail) usize {
    return t.n;
}

/// One step of a walk, as its word says it (§2 "trail word").
pub const Step = union(enum) {
    /// A place the pane was at: `rank.zig:14`.
    place: Place,
    /// The held pane this is the reader of, by its serial: `‹@p3`, always
    /// the first step.
    owner: u32,
    /// A list the pane came through (`Find pick 3/6 •2`, §5.6): its word
    /// and the pickers' index for it. Made by the pickers (not yet).
    list: Word,
    /// A search made in the pane (`/dirty/ 3/7`, §7.3). Made by the
    /// prompts (not yet).
    search: Word,
    /// A chain of selection prompts as an Edit line (§7.5). Made by the
    /// prompts (not yet).
    recipe: Word,
};
pub const Place = struct { path: Kind.Buf(max_text) = .{}, line: u32 = 0, col: u32 = 0 };
pub const Word = struct { text: Kind.Buf(max_text) = .{}, index: u32 = 0 };

/// A file the walk can show: a text on its path, not an output, a
/// listing, a pager, a query or a kind (§2: what is not a file is held).
pub fn isFile(pane: *const Pane) bool {
    const f = pane.file orelse return false;
    return f.output == null and f.listing == null and !f.pager and f.mini == null and pane.query == null and pane.addon == null;
}

/// A pane that walks: a file not held, in a session whose jumps walk.
pub fn reading(p: *const Pardes, pane: *const Pane) bool {
    return p.settings.jumps == .walk and isFile(pane) and !pane.trail.held;
}

/// The reading pane that is held pane `owner`'s reader, if it has one.
pub fn readerOf(p: *const Pardes, owner: *const Pane) ?usize {
    for (p.panes, 0..) |slot, id| {
        const r = slot orelse continue;
        if (r == owner or !isFile(r) or r.trail.held or r.trail.n == 0) continue;
        if (r.trail.steps[0] == .owner and r.trail.steps[0].owner == owner.serial) return id;
    }
    return null;
}

/// A new reader's trail: its owner, then where it opened.
pub fn reader(owner: u32, path: []const u8, at: Spot) Trail {
    var t: Trail = .{};
    push(&t, .{ .owner = owner });
    if (placeOf(path, at.line, at.col)) |s| push(&t, s);
    t.cur = t.n - 1;
    return t;
}

/// A place as a step, null when its path does not fit one.
fn placeOf(path: []const u8, line: usize, col: usize) ?Step {
    if (path.len > max_text) return null;
    var at: Place = .{ .line = std.math.lossyCast(u32, line), .col = std.math.lossyCast(u32, col) };
    at.path.set(path);
    return .{ .place = at };
}

/// Where `pane` is now, as a step.
fn here(pane: *const Pane) ?Step {
    const f = pane.file orelse return null;
    return placeOf(f.path, @as(usize, @intCast(@max(0, pane.body.cur_row))) + 1, @as(usize, @intCast(@max(0, pane.body.cur_col))) + 1);
}

fn samePlace(s: Step, path: []const u8, line: usize) bool {
    return s == .place and s.place.line == line and std.mem.eql(u8, s.place.path.slice(), path);
}

/// `s` as the newest step, the oldest that is not the owner dropped when
/// the trail is full.
fn push(t: *Trail, s: Step) void {
    if (t.n == max_steps) {
        const first: usize = @intFromBool(t.steps[0] == .owner);
        std.mem.copyForwards(Step, t.steps[first .. max_steps - 1], t.steps[first + 1 ..]);
        t.n -= 1;
        t.cur -|= 1;
    }
    t.steps[t.n] = s;
    t.n += 1;
}

/// Step reading pane `id` to `path` at `at` (§6.2): a place already on its
/// trail is gone back or forward to, never held twice; anything else is a
/// new step, which drops the forward steps. The pane's slot after it: a
/// step to another file is a new pane in its place (`replace`).
pub fn step(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize {
    const pane = p.panes[id].?;
    const t = &pane.trail;
    // Where it is already: no step.
    if (here(pane)) |was| if (samePlace(was, path, at.line)) return show(p, id, path, at);
    for (t.steps[0..t.cur], 0..) |s, i| if (samePlace(s, path, at.line)) return go(p, id, @intCast(i));
    if (t.n > t.cur + 1) for (t.steps[t.cur + 1 .. t.n], t.cur + 1..) |s, j| if (samePlace(s, path, at.line)) return go(p, id, @intCast(j));
    const to = placeOf(path, at.line, at.col) orelse return error.NameTooLong;
    // Where it was: the current step's place, or a first one.
    if (here(pane)) |was| {
        if (t.n > t.cur) {
            t.n = t.cur + 1;
            t.steps[t.cur] = was;
        } else push(t, was);
    } else t.n = t.cur;
    push(t, to);
    t.cur = t.n - 1;
    return show(p, id, path, at);
}

/// Go to step `i` of reading pane `id`'s trail, back or forward (§6.4):
/// where it is now becomes the step it leaves, the ones between stay.
pub fn go(p: *Pardes, id: usize, i: u8) !usize {
    const pane = p.panes[id].?;
    const t = &pane.trail;
    if (i >= t.n or t.steps[i] != .place) return id;
    const s = t.steps[i];
    if (t.n > t.cur) if (here(pane)) |was| {
        t.steps[t.cur] = was;
    };
    t.cur = i;
    return show(p, id, s.place.path.slice(), .{ .line = s.place.line, .col = s.place.col });
}

/// Pane `id` showing `path` at `at`, the keyboard on it: its caret moved
/// in the file it shows, or a new pane on `path` in its place, its walk
/// with it. A line past the new file's end is a miss that changes nothing.
fn show(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize {
    const pane = p.panes[id].?;
    if (pane.file) |f| if (std.mem.eql(u8, f.path, path)) {
        look.clearNavigationSelection(p, pane);
        look.focusPaneLine(p, id, at, .center);
        return id;
    };
    const free = p.freeSlot() orelse return error.NoPaneSlots;
    const nt = try panes.File.open(p, free, path, at.line);
    // Refused: closed at the step's end, never placed (Pardes.unplaced).
    errdefer {
        p.unplaced.set(free);
        nt.vweight = 0;
    }
    if (at.line > panes.File.nlines(p.gpa, &nt.file.?)) return error.LineMissing;
    nt.trail = pane.trail;
    // Before the layout gives its place away: its file is told closed
    // while it is still in its slot.
    try panes.deinitPane(p, pane);
    layout.replacePane(p, id, free);
    p.panes[id] = null;
    layout.compute(p);
    look.focusPaneLine(p, free, at, .keep);
    // Its line half the body's rows down, as a look's new pane has it.
    const rows = @max(1, p.view().rects[free].h -| pardes.BOX_H);
    panes.File.setTop(nt, panes.File.walkRows(p.settings.tab, nt, .{ .line = nt.file.?.scroll }, -@as(i64, rows / 2)).to);
    return free;
}

/// `s`, a search's or a recipe's word, the pane's one of its kind (§7.3,
/// §7.5): the one it had goes, and it is the newest back step.
pub fn setWord(t: *Trail, s: Step) void {
    var w: u8 = 0;
    for (t.steps[0..t.n], 0..) |old, i| {
        if (std.meta.activeTag(old) == std.meta.activeTag(s)) {
            if (i < t.cur) t.cur -= 1;
            continue;
        }
        t.steps[w] = old;
        w += 1;
    }
    t.n = w;
    if (t.n == max_steps) {
        const first: usize = @intFromBool(t.steps[0] == .owner);
        std.mem.copyForwards(Step, t.steps[first .. max_steps - 1], t.steps[first + 1 ..]);
        t.n -= 1;
        t.cur -|= 1;
    }
    std.mem.copyBackwards(Step, t.steps[t.cur + 1 .. t.n + 1], t.steps[t.cur..t.n]);
    t.steps[t.cur] = s;
    t.n += 1;
    t.cur += 1;
}

/// Pane `id` held (§6.5): Keep, or an edit. It no longer walks, so the
/// walk leaves its trail (places, lists, its owner, forward steps); words
/// about its own text (a search, a recipe) stay. The next jump from its
/// old owner makes a new reader.
pub fn keep(pane: *Pane) void {
    const t = &pane.trail;
    if (t.held) return;
    t.held = true;
    var w: u8 = 0;
    for (t.steps[0..t.cur]) |s| if (s == .search or s == .recipe) {
        t.steps[w] = s;
        w += 1;
    };
    t.n = w;
    t.cur = w;
}

/// An edit of file `f`: the panes showing it are held from now on (§6.5).
pub fn edited(p: *Pardes, f: *const panes.File.State) void {
    for (p.panes) |slot| {
        const pane = slot orelse continue;
        if (pane.trail.held) continue;
        const shown = if (pane.file) |*pf| pf else continue;
        if (shown == f or (f.twin != 0 and shown.twin == f.twin)) keep(pane);
    }
}


/// Back (`delta` < 0) or forward one place in reading pane `id`'s walk,
/// as Ctrl-o and Ctrl-i go first (pick-ui SPEC §6.4): true when it had
/// one that way, false to leave the step to the jump list (Jump.jumpBy).
pub fn walkBy(p: *Pardes, id: usize, delta: i32) bool {
    const pane = p.panes[id] orelse return false;
    if (!reading(p, pane)) return false;
    const t = &pane.trail;
    var i: usize = t.cur;
    while (if (delta < 0) i > 0 else i + 1 < t.n) {
        i = if (delta < 0) i - 1 else i + 1;
        if (t.steps[i] != .place) continue;
        _ = go(p, id, @intCast(i)) catch |err| p.reportError(.at(id), "walk", err);
        return true;
    }
    return false;
}

// ---- the words ----

pub const Part = enum { back, forward };

/// Step `i`'s word: `‹@p3`, `rank.zig:14`, a list's, search's or recipe's
/// own text; `·` when it is folded.
fn wordOf(t: *const Trail, i: usize, buf: *[max_text + 16]u8) []const u8 {
    const s = &t.steps[i];
    if (s.* != .owner and i < t.cur and t.cur - i > shown_steps) return "·";
    // The step itself, not a copy: a word's text is the step's own bytes.
    return switch (s.*) {
        .owner => |serial| std.fmt.bufPrint(buf, "‹" ++ config.pane_addr ++ "{d}", .{serial}) catch unreachable, // a u32 fits
        .place => |at| std.fmt.bufPrint(buf, "{s}:{d}", .{ std.Io.Dir.path.basename(at.path.slice()), at.line }) catch unreachable, // a basename and a u32 fit
        .list, .search, .recipe => |*w| w.text.slice(),
    };
}

const sep = " › ";

/// The steps a part writes.
fn range(t: *const Trail, part: Part) [2]usize {
    return switch (part) {
        .back => .{ 0, t.cur },
        .forward => .{ @min(t.n, t.cur + 1), t.n },
    };
}

/// The back steps' words, each with the separator after it (before the
/// path), or the forward steps', each with one before it (after the path).
pub fn write(t: *const Trail, part: Part, w: *std.Io.Writer) std.Io.Writer.Error!void {
    var buf: [max_text + 16]u8 = undefined;
    const r = range(t, part);
    for (r[0]..r[1]) |i| switch (part) {
        .back => try w.print("{s}" ++ sep, .{wordOf(t, i, &buf)}),
        .forward => try w.print(sep ++ "{s}", .{wordOf(t, i, &buf)}),
    };
}

/// The bytes `write` writes for `part`.
pub fn bytes(t: *const Trail, part: Part) usize {
    var buf: [max_text + 16]u8 = undefined;
    var n: usize = 0;
    const r = range(t, part);
    for (r[0]..r[1]) |i| n += wordOf(t, i, &buf).len + sep.len;
    return n;
}

/// Where back step `i`'s word is in what `write` writes for the back steps.
pub fn spanOf(t: *const Trail, i: usize) [2]usize {
    var buf: [max_text + 16]u8 = undefined;
    var x: usize = 0;
    for (0..i) |j| x += wordOf(t, j, &buf).len + sep.len;
    return .{ x, x + wordOf(t, i, &buf).len };
}

/// The step whose word in `part` is at byte `off` of what `write` wrote
/// for it, null on a separator or past them.
pub fn stepAt(t: *const Trail, part: Part, off: usize) ?u8 {
    var buf: [max_text + 16]u8 = undefined;
    var x: usize = 0;
    const r = range(t, part);
    for (r[0]..r[1]) |i| {
        if (part == .forward) x += sep.len;
        const n = wordOf(t, i, &buf).len;
        if (off >= x and off < x + n) return @intCast(i);
        x += n;
        if (part == .back) x += sep.len;
    }
    return null;
}

/// Look on step `i` of pane `id`'s trail (§6.3): a place is gone back or
/// forward to, the owner focused, a search lit again, a recipe's
/// selections put back (Prompt.zig); a list is the pickers' (not yet: said).
pub fn lookStep(p: *Pardes, id: usize, i: u8) void {
    const pane = p.panes[id] orelse return;
    switch (pane.trail.steps[i]) {
        .place => _ = go(p, id, i) catch |err| p.reportError(.at(id), "walk", err),
        .owner => |serial| if (p.paneBySerial(serial)) |owner| {
            p.view().active = owner;
        } else p.reportFailure(id, "walk: its owner is closed"),
        .search => pardes.Prompt.lookWord(p, id),
        .recipe => pardes.Prompt.lookRecipe(p, id),
        .list => p.setMessage(.at(id), "walk: a list is not walked yet"),
    }
}

/// Exec on step `i` (§6.3): a place and the owner as Look; a list runs its
/// source again, a search searches again, a recipe replays (not yet).
pub fn execStep(p: *Pardes, id: usize, i: u8) void {
    const pane = p.panes[id] orelse return;
    switch (pane.trail.steps[i]) {
        .place, .owner => lookStep(p, id, i),
        .search => pardes.Prompt.execWord(p, id),
        .recipe => pardes.Prompt.execRecipe(p, id),
        .list => p.setMessage(.at(id), "walk: a list is not run again yet"),
    }
}

fn typeKeys(p: *Pardes, keys: []const u8) void {
    for (keys) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } });
}

fn tagOf(p: *Pardes, pane: *Pane) ![]const u8 {
    return pardes.tagline.tagText(p, p.scratch.allocator(), pane);
}

/// The ground of the cell under the first cell of pane `id`'s tag text.
fn tagGroundOf(p: *Pardes, arena: *std.heap.ArenaAllocator, id: usize) !pardes.Color {
    p.sync();
    _ = arena.reset(.retain_capacity);
    const s = try p.render(arena.allocator());
    const r = p.view().rects[id];
    return s.at(r.x + pardes.TAG_TEXT_INSET, p.tagTop(p.panes[id].?, r)).style.bg;
}

test "a file's pane is reading, its tag in the reading tint with Keep after its path; typed into, it is held, and Jumps new-pane reads none" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    p.settings.jumps = .walk;
    const pane = try p.setTestFile("alpha\nbeta\n");
    try std.testing.expect(reading(p, pane));
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), "/test.txt Keep "));
    try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().tag_reading_bg }, try tagGroundOf(p, &arena, 0));
    // Under Jumps new-pane nothing reads: the tag as it always was.
    p.settings.jumps = .@"new-pane";
    try std.testing.expect(!reading(p, pane));
    try std.testing.expectEqualStrings("/test.txt Save Term Collapse Follow Del", try tagOf(p, pane));
    try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().tag_active_bg }, try tagGroundOf(p, &arena, 0));
    p.settings.jumps = .walk;
    // Typed into: held from now on, though Undo takes the text back.
    typeKeys(p, "ix");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    typeKeys(p, "u");
    try std.testing.expectEqualStrings("alpha\nbeta\n", pane.file.?.content);
    try std.testing.expect(!reading(p, pane));
    try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, pane), "Keep") == null);
    try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().tag_active_bg }, try tagGroundOf(p, &arena, 0));
}

test "Keep holds a reading pane; a scratch and a listing are never reading" {
    const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 });
    defer p.deinit();
    p.settings.jumps = .walk;
    const pane = try p.setTestFile("alpha\n");
    pardes.exec.runBuiltin(p, .Keep, 0, "Keep", null);
    try std.testing.expect(!reading(p, pane));
    try std.testing.expect(pane.trail.held);
    pardes.exec.runBuiltin(p, .New, 0, "New", null);
    const scratch = p.panes[p.view().active].?;
    try std.testing.expect(scratch != pane and scratch.file != null and !reading(p, scratch));
    var dir = std.testing.tmpDir(.{});
    defer dir.cleanup();
    var buf: [4096]u8 = undefined;
    const len = try dir.dir.realPath(std.testing.io, &buf);
    pardes.look.lookAt(p, 0, buf[0..len]);
    const listing = p.panes[p.view().active].?;
    try std.testing.expect(listing.file.?.listing != null and !reading(p, listing));
}

/// A session over three files of 100 lines in a directory of its own,
/// search.zig, rank.zig and place.zig; search.zig open and edited (held)
/// in pane `held`, under the session's first pane.
const Fixture = struct {
    p: *Pardes,
    tmp: std.testing.TmpDir,
    dir_buf: [4096]u8 = undefined,
    dir: []const u8 = "",
    held: usize = 0,

    fn init(f: *Fixture, rows: u16) !void {
        f.tmp = std.testing.tmpDir(.{});
        errdefer f.tmp.cleanup();
        var text: [100 * 9]u8 = undefined;
        var w: std.Io.Writer = .fixed(&text);
        for (1..101) |n| try w.print("line {d}\n", .{n});
        for ([_][]const u8{ "search.zig", "rank.zig", "place.zig" }) |name|
            try f.tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = w.buffered() });
        f.dir = f.dir_buf[0..try f.tmp.dir.realPath(std.testing.io, &f.dir_buf)];
        f.p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = rows });
        errdefer f.p.deinit();
        _ = try f.p.setTestFile("scratch\n");
        f.p.settings.jumps = .@"new-pane";
        f.look(0, "search.zig", 88);
        f.p.settings.jumps = .walk;
        f.held = f.p.view().active;
        typeKeys(f.p, "ix");
        f.p.update(.{ .key = .{ .cp = pardes.Key.escape } });
        f.p.sync();
    }

    fn deinit(f: *Fixture) void {
        f.p.deinit();
        f.tmp.cleanup();
    }

    /// A Look from pane `id` at `name:line` in the fixture's directory.
    fn look(f: *Fixture, id: usize, name: []const u8, line: usize) void {
        var buf: [4096 + 64]u8 = undefined;
        pardes.look.lookAt(f.p, id, std.fmt.bufPrint(&buf, "{s}/{s}:{d}", .{ f.dir, name, line }) catch unreachable);
        f.p.sync();
    }

    fn active(f: *Fixture) *Pane {
        return f.p.panes[f.p.view().active].?;
    }

    /// The active pane's file's name and line, as `rank.zig:12`.
    fn at(f: *Fixture, buf: []u8) []const u8 {
        const pane = f.active();
        return std.fmt.bufPrint(buf, "{s}:{d}", .{ std.Io.Dir.path.basename(pane.file.?.path), pane.body.cur_row + 1 }) catch unreachable;
    }
};

test "a jump from a held pane steps its reader, made under it with half its rows; the reader walks in place, and a place on its trail is gone back to, never held twice" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(60);
    defer f.deinit();
    const held = f.p.panes[f.held].?;
    try std.testing.expect(!reading(f.p, held));
    const before = f.p.view().rects[f.held];
    var buf: [64]u8 = undefined;
    // g d on rank: its reader, under it, half its rows.
    f.look(f.held, "rank.zig", 12);
    const r1 = f.p.view().active;
    try std.testing.expect(r1 != f.held);
    try std.testing.expectEqualStrings("rank.zig:12", f.at(&buf));
    try std.testing.expectEqual(held.serial, f.active().trail.steps[0].owner);
    const col = layout.findPane(f.p, f.held).?;
    try std.testing.expectEqual(col.col, layout.findPane(f.p, r1).?.col);
    try std.testing.expectEqual(col.idx + 1, layout.findPane(f.p, r1).?.idx);
    try std.testing.expect(f.p.view().rects[f.held].h <= before.h / 2 + 1);
    // Look at place.zig:8 in the reader, from line 14: the reader walks.
    typeKeys(f.p, "2j");
    f.look(r1, "place.zig", 8);
    const r2 = f.p.view().active;
    try std.testing.expect(f.p.panes[r1] == null or r2 == r1);
    try std.testing.expectEqualStrings("place.zig:8", f.at(&buf));
    try std.testing.expectEqual(layout.findPane(f.p, f.held).?.idx + 1, layout.findPane(f.p, r2).?.idx);
    // g d on Span, from line 9: one more step in the same file.
    typeKeys(f.p, "j");
    f.look(r2, "place.zig", 40);
    try std.testing.expectEqual(r2, f.p.view().active);
    try std.testing.expectEqualStrings("place.zig:40", f.at(&buf));
    const t = &f.active().trail;
    try std.testing.expectEqual(@as(u8, 4), t.n);
    try std.testing.expectEqual(@as(u8, 3), t.cur);
    try std.testing.expectEqual(@as(u32, 14), t.steps[1].place.line);
    try std.testing.expectEqual(@as(u32, 9), t.steps[2].place.line);
    // The next jump from the held pane lands in the same reader.
    f.look(f.held, "rank.zig", 30);
    const r3 = f.p.view().active;
    try std.testing.expectEqualStrings("rank.zig:30", f.at(&buf));
    try std.testing.expectEqual(held.serial, f.active().trail.steps[0].owner);
    var readers: usize = 0;
    for (f.p.panes) |slot| if (slot) |pane| {
        readers += @intFromBool(pane.trail.n > 0 and pane.trail.steps[0] == .owner);
    };
    try std.testing.expectEqual(@as(usize, 1), readers);
    // A Look at a place on its trail goes back to it: nothing pushed.
    f.look(r3, "rank.zig", 14);
    try std.testing.expectEqualStrings("rank.zig:14", f.at(&buf));
    try std.testing.expectEqual(@as(u8, 1), f.active().trail.cur);
    try std.testing.expectEqual(@as(u8, 5), f.active().trail.n);
}

test "a Look from inside the reader at a file its held pane shows focuses the held pane and replaces nothing" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(60);
    defer f.deinit();
    f.look(f.held, "rank.zig", 12);
    const reader_id = f.p.view().active;
    const reader_pane = f.active();
    f.look(reader_id, "search.zig", 89);
    try std.testing.expectEqual(f.held, f.p.view().active);
    try std.testing.expectEqual(@as(i32, 88), f.active().body.cur_row);
    try std.testing.expectEqual(reader_pane, f.p.panes[reader_id].?);
    try std.testing.expectEqualStrings("rank.zig", std.Io.Dir.path.basename(reader_pane.file.?.path));
}

test "the reader of a held pane too short to halve goes to the bottom of the next column, of the previous one from the last" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(24);
    defer f.deinit();
    const col = layout.findPane(f.p, f.held).?.col;
    try std.testing.expect(f.p.view().rects[f.held].h / 2 < f.p.panes[f.held].?.tag_rows + layout.reader_keeps);
    try std.testing.expect(layout.insertColumn(f.p, col, false) != null);
    f.look(f.held, "rank.zig", 12);
    const reader_id = f.p.view().active;
    try std.testing.expectEqual(col + 1, layout.findPane(f.p, reader_id).?.col);
}

/// Where `word` starts in pane `id`'s tag, on the screen.
fn tagCell(p: *Pardes, id: usize, word: []const u8) ![2]u16 {
    const pane = p.panes[id].?;
    const tag = try tagOf(p, pane);
    const i = std.mem.indexOf(u8, tag, word) orelse return error.NotInTag;
    const r = p.view().rects[id];
    return .{ r.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(p.settings.tab, tag[0..i]))), p.tagTop(pane, r) };
}

/// A click with `button` on `word` in pane `id`'s tag: a press and a
/// release on its first cell.
fn clickTag(p: *Pardes, id: usize, word: []const u8, button: pardes.Mouse.Button) !void {
    const at = try tagCell(p, id, word);
    for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| p.update(.{ .mouse = .{ .button = button, .kind = kind, .col = at[0], .row = at[1] } });
    p.sync();
}

test "the session of pick-ui §6.7: four jumps across three files, back by a click on a trail word, the later steps kept dimmed after the path, forward again, Keep, and a new reader on the next jump" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(60);
    defer f.deinit();
    const p = f.p;
    const owner = p.panes[f.held].?.serial;
    var buf: [4096 + 128]u8 = undefined;
    var at: [64]u8 = undefined;
    // 1 · g d on rank from the held pane: its reader, made below it.
    f.look(f.held, "rank.zig", 12);
    // 2 · Look at Place.of from line 14 of rank.zig: the reader walks.
    typeKeys(p, "2j");
    f.look(p.view().active, "place.zig", 8);
    // 3 · g d on Span from line 9: one more step in the same file.
    typeKeys(p, "j");
    f.look(p.view().active, "place.zig", 40);
    var r = p.view().active;
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › rank.zig:14 › place.zig:9 › {s}/place.zig Keep ", .{ owner, f.dir })));
    // 4 · a click on rank.zig:14: back, the later steps after the path,
    // dimmed.
    try clickTag(p, r, "rank.zig:14", .left);
    r = p.view().active;
    try std.testing.expectEqualStrings("rank.zig:14", f.at(&at));
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › {s}/rank.zig › place.zig:9 › place.zig:40 Keep ", .{ owner, f.dir })));
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    const s = try p.render(arena.allocator());
    const dim = try tagCell(p, r, "place.zig:40");
    try std.testing.expectEqual(pardes.Color{ .rgb = p.chromeTheme().lineno }, s.at(dim[0], dim[1]).style.fg);
    // A click on a forward step goes forward to it.
    try clickTag(p, r, "place.zig:9", .left);
    r = p.view().active;
    try std.testing.expectEqualStrings("place.zig:9", f.at(&at));
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › rank.zig:14 › {s}/place.zig › place.zig:40 Keep ", .{ owner, f.dir })));
    // Exec (B2) on the owner's word: the owner has the keyboard.
    try clickTag(p, r, "‹@p", .middle);
    try std.testing.expectEqual(f.held, p.view().active);
    // A new step from the reader drops the forward steps.
    f.look(r, "rank.zig", 50);
    r = p.view().active;
    try std.testing.expectEqual(p.panes[r].?.trail.cur + 1, p.panes[r].?.trail.n);
    // 5 · Keep: the walk leaves its tag; the next jump from the owner
    // makes a new reader.
    pardes.exec.runBuiltin(p, .Keep, r, "Keep", null);
    p.sync();
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "{s}/rank.zig Save", .{f.dir})));
    f.look(f.held, "place.zig", 20);
    const fresh = p.view().active;
    try std.testing.expect(fresh != r and fresh != f.held and p.panes[r] != null);
    try std.testing.expectEqual(owner, p.panes[fresh].?.trail.steps[0].owner);
}

test "a trail keeps its newest three back steps whole, older ones fold to ·, and a click on a · goes back to its step" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(60);
    defer f.deinit();
    const p = f.p;
    const owner = p.panes[f.held].?.serial;
    for ([_]usize{ 10, 20, 30, 40, 50 }) |line| f.look(f.held, "rank.zig", line);
    const r = p.view().active;
    var buf: [4096 + 128]u8 = undefined;
    var at: [64]u8 = undefined;
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "‹@p{d} › · › rank.zig:20 › rank.zig:30 › rank.zig:40 › {s}/rank.zig Keep ", .{ owner, f.dir })));
    try clickTag(p, r, "·", .right);
    try std.testing.expectEqualStrings("rank.zig:10", f.at(&at));
}

test "Ctrl-o goes back one place in a reader's walk and Ctrl-i forward again; past its first place, or from a held pane, the jump list's" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(60);
    defer f.deinit();
    const p = f.p;
    var at: [64]u8 = undefined;
    f.look(f.held, "rank.zig", 12);
    f.look(p.view().active, "place.zig", 8);
    f.look(p.view().active, "place.zig", 40);
    const back: pardes.Key = .{ .cp = 'o', .ctrl = true };
    const ahead: pardes.Key = .{ .cp = 'i', .ctrl = true };
    p.update(.{ .key = back });
    p.sync();
    try std.testing.expectEqualStrings("place.zig:8", f.at(&at));
    p.update(.{ .key = back });
    p.sync();
    try std.testing.expectEqualStrings("rank.zig:12", f.at(&at));
    p.update(.{ .key = ahead });
    p.sync();
    try std.testing.expectEqualStrings("place.zig:8", f.at(&at));
    p.update(.{ .key = back });
    p.sync();
    try std.testing.expectEqualStrings("rank.zig:12", f.at(&at));
    // The owner's word is no place: past the first, the jump list's.
    try std.testing.expect(!walkBy(p, p.view().active, -1));
    try std.testing.expect(!walkBy(p, f.held, -1));
}

test "closing a held pane closes its reader; a kept reader stays; typed into, a reader is held and its walk leaves its tag" {
    var f: Fixture = .{ .p = undefined, .tmp = undefined };
    try f.init(60);
    defer f.deinit();
    const p = f.p;
    const owner = p.panes[f.held].?.serial;
    var buf: [4096 + 128]u8 = undefined;
    f.look(f.held, "rank.zig", 12);
    f.look(p.view().active, "place.zig", 8);
    const r = p.view().active;
    // Typed into: held, its walk gone from its tag, kept when its owner goes.
    typeKeys(p, "ix");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    p.sync();
    try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, p.panes[r].?), try std.fmt.bufPrint(&buf, "{s}/place.zig Save", .{f.dir})));
    try std.testing.expectEqual(@as(u8, 0), p.panes[r].?.trail.n);
    // The next jump from its old owner makes a new reader.
    f.look(f.held, "rank.zig", 30);
    const fresh = p.view().active;
    try std.testing.expect(fresh != r);
    try std.testing.expectEqual(owner, p.panes[fresh].?.trail.steps[0].owner);
    // Del of the owner: its reader goes with it; the edited one stays.
    const fresh_serial = p.panes[fresh].?.serial;
    try p.removePane(f.held, null);
    p.sync();
    try std.testing.expect(p.paneBySerial(fresh_serial) == null);
    try std.testing.expect(p.panes[r] != null);
}