summaryrefslogtreecommitdiff
path: root/core/tagline.zig
blob: eedc25bcbf7a45be5dd55e134b580dabf5c504b2 (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
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
//! The tags (acme's tag half of wind.c): a pane's computed prefix and its
//! default and saved tails, going into a tag and out again, the path drafted
//! as a new name, and the column and workspace tags above the panes.
const pardes = @import("root.zig");
const std = @import("std");
const modal = @import("modal.zig");
const ctlfs = @import("ninep/tree.zig");
const panes = @import("panes.zig");
const edit = @import("edit.zig");
const exec = @import("exec.zig");
const config = @import("config.zig");
const Layer = @import("Layer.zig");
const layout = @import("layout.zig");
const TagState = @import("TagState.zig");
const Messages = @import("Messages.zig");
const Pane = panes.Pane;
const Text = panes.Text;
const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
const Pardes = pardes.Pardes;

/// The words a pane of each kind had in its tag before UX K' (its own
/// text until edited then): what `kindTail` says.
pub const pane_tail = " " ++ config.pane_builtins_str;
pub const file_pane_tail = " " ++ config.file_pane_builtins_str;
fn withFileCommands(comptime tail: []const u8, comptime words: []const u8) []const u8 {
    std.debug.assert(std.mem.endsWith(u8, tail, " Del"));
    return tail[0 .. tail.len - " Del".len] ++ " " ++ words ++ " Del";
}
pub const context_pane_tail = withFileCommands(file_pane_tail, "TreeContext");
pub const locations_pane_tail = withFileCommands(file_pane_tail, "LocationsConfig");
/// Language commands precede the final Del, like other file-pane commands.
pub const lsp_pane_tail = withFileCommands(file_pane_tail, config.lsp_pane_builtins_str);
pub const lsp_context_pane_tail = withFileCommands(context_pane_tail, config.lsp_pane_builtins_str);
pub const pager_pane_tail = " " ++ config.pager_pane_builtins_str;
pub const diff_pane_tail = " " ++ config.diff_pane_builtins_str;
pub const pager_diff_pane_tail = " " ++ config.pager_diff_pane_builtins_str;
pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str, "LocationsConfig");
pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str;
pub const command_pane_tail = " " ++ config.command_pane_builtins_str;
pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str;
/// A query pane's while its rows are made (Query.zig), and once Enter froze
/// them into text a Save keeps; Undock leaves it where it stands.
pub const query_live_tail = " Del";
pub const query_frozen_tail = " Save Undock Del";
/// ...and while its Grep waits at 2000 lines for More (Stream.zig).
pub const query_capped_tail = " More Del";

/// A file's computed words (UX K'3) by which of `Diff`, `Filter`, `Save`,
/// `Undo` and `Redo` act now (bit 0 to 4), each after a blank, `Del` last.
const file_words = words: {
    const names = [_][]const u8{ "Diff", "Filter", "Save", "Undo", "Redo" };
    var table: [1 << names.len][]const u8 = undefined;
    for (&table, 0..) |*words, bits| {
        words.* = "";
        for (names, 0..) |name, i| if (bits >> i & 1 == 1) {
            words.* = words.* ++ " " ++ name;
        };
        words.* = words.* ++ " Del";
    }
    break :words table;
};

/// A pane's computed words at rest (UX K'3): the words that act now, each
/// after a blank, read-only and made again from its state, as its path is.
/// The tag's own text (the user's) follows them.
pub fn computedWords(pane: *const Pane) []const u8 {
    // A kind's: its addon's words, then Del (Kind.reopen).
    if (pane.addon) |k| if (k.tail.len > 0) return k.tail.slice();
    if (pane.query) |q| return if (q.frozen) query_frozen_tail else if (q.capped) query_capped_tail else query_live_tail;
    if (pane.file) |*f| return fileWords(pane, f);
    if (pane.command != null) return if (pane.command_done) " Del" else " Kill Del";
    return " Del";
}

/// The computed words a pane's tag shows, in and out of rest (UX DESIGN
/// M1): its own (`computedWords`); while a picker previews another file in
/// its body, its own file's, set aside under the preview (`named`); none
/// in a pane made for the picker, whose tag is its owner's word alone.
pub fn tagWords(p: *const Pardes, pane: *const Pane) []const u8 {
    const pk = pardes.Pick.landingOf(p, pane) orelse return computedWords(pane);
    if (pk.made) return "";
    return fileWords(pane, named(p, pane) orelse return computedWords(pane));
}

/// The file pane `pane`'s tag names: its own, the one a picker's preview
/// set aside in its body included (UX DESIGN M3: the tag says what Esc
/// gives back and where Enter lands, never the preview); none in a pane
/// made for the picker.
pub fn named(p: *const Pardes, pane: *const Pane) ?*const panes.File.State {
    if (pardes.Pick.landingOf(p, pane)) |pk| {
        if (pk.made) return null;
        if (pk.aside) |*own| return own;
    }
    return if (pane.file) |*f| f else null;
}

/// A file's computed words (UX K'3), file `f` its own.
fn fileWords(pane: *const Pane, f: *const panes.File.State) []const u8 {
    if (f.output) |out| if (out.from == .preview) return query_live_tail;
    if (f.listing != null) return " Get Del";
    const j = &f.history.journal;
    var bits = fileBits(pane, f);
    if (!unsaved(f)) bits &= ~@as(usize, 4);
    // A step back with something in it: insert mode's mark is a step
    // of none until a key types (Text.Journal.mark keeps one such, on
    // top), and Undo would act on nothing.
    if (j.done == 0 or (j.done == 1 and j.steps.items[0].n == 0)) bits &= ~@as(usize, 8);
    if (j.done == j.steps.items.len) bits &= ~@as(usize, 16);
    return file_words[bits];
}

/// The computed words pane `pane` can come to show (K'3: Save, Undo and
/// Redo come and go with its edits, a query's as it freezes): what a
/// placement leaves its tag the rows for (layout.minRows), so an edit
/// never takes a row its column did not give. A reading pane's are its
/// own (its first edit holds it): its walk folds to the rows it has with
/// them (`folded`).
pub fn widestWords(p: *const Pardes, pane: *const Pane) []const u8 {
    if (pardes.Trail.reading(p, pane)) return tagWords(p, pane);
    if (pane.query != null) return query_frozen_tail;
    if (pane.file) |*f| if (f.listing == null and (if (f.output) |out| out.from != .preview else true))
        return file_words[fileBits(pane, f)];
    return computedWords(pane);
}

/// A file's computed words that its kind can show (file_words' bits):
/// Diff for a diff (a .patch, a +Pager holding one, the Diff view),
/// Filter for a pager, Save where it saves (never a +New's, K'3: SPC f s
/// asks it a path), Undo and Redo.
fn fileBits(pane: *const Pane, f: *const panes.File.State) usize {
    const diff = if (f.pager) f.pager_diff else pane.colorAlgo() == .diff or
        (if (f.output) |out| std.meta.eql(out.from, panes.Output.Origin{ .cmd = .Diff }) else false);
    const scratch = if (f.output) |out| std.meta.eql(out.from, panes.Output.Origin{ .cmd = .New }) else false;
    const saves = panes.Output.fileTraits(f.output).saves and !scratch;
    return @as(usize, @intFromBool(diff)) | @as(usize, @intFromBool(f.pager)) << 1 | @as(usize, @intFromBool(saves)) << 2 | 8 | 16;
}
/// A file with changes it has not saved.
pub fn dirty(pane: *const panes.Pane) bool {
    return if (pane.file) |*f| unsaved(f) else false;
}

/// Whether file `f` has changes it has not saved (`dirty`, `fileWords`).
fn unsaved(f: *const panes.File.State) bool {
    return panes.Output.fileTraits(f.output).saves and (f.revision != f.saved_revision or f.disk_gone);
}
/// What a column's tag said before UX K', its own text then: a dump's own
/// text equal to it is dropped (dump.dropOldTags), and a column's exec
/// still takes its words (ninep/cols.zig paneWord).
pub const column_tag_default = "New Term Find Grep Joincol Delcol";

/// A header's computed words (UX K'2), read-only, made again from the
/// session's state as a pane tag's are: the window's, then `Restore
/// <path>` once a dump exists; a column's, with Joincol and Delcol where
/// there is a second column for them.
pub fn headerWords(p: *Pardes, what: Text.What) []const u8 {
    if (what == .column) return if (p.view().ncol > 1) config.columns_words_str else config.column_words_str;
    const d = p.last_dump orelse return config.window_words_str;
    return std.fmt.allocPrint(p.scratch.allocator(), "{s} Restore {s}", .{ config.window_words_str, d }) catch config.window_words_str;
}

/// A header as it is shown, read and edited: its computed words, a blank,
/// then the user's text (UX K'1), everything typed into it, as a pane
/// tag's own text follows its prefix.
pub fn headerText(p: *Pardes, t: *const Text) ![]u8 {
    const own: []const u8 = t.own orelse "";
    return std.mem.concat(p.scratch.allocator(), u8, &.{ headerWords(p, t.what), " ", own });
}

/// The window's tag -- render and click dispatch must agree on this exact
/// string.
pub fn topbar(p: *Pardes) []const u8 {
    return headerText(p, &p.global_tag) catch config.window_words_str;
}

pub fn columnTag(p: *Pardes, c: usize) []const u8 {
    return headerText(p, &p.view().col_tags[c]) catch config.column_words_str;
}

/// A header's width in glyphs as headerText makes it, made of nothing.
fn headerWidth(p: *const Pardes, t: *const Text) usize {
    const tab = p.settings.tab;
    const own = if (t.own) |text| panes.File.displayWidth(tab, text) else 0;
    const column: []const u8 = if (p.view().ncol > 1) config.columns_words_str else config.column_words_str;
    if (t.what == .column) return column.len + 1 + own;
    const restore = if (p.last_dump) |d| " Restore ".len + panes.File.displayWidth(tab, d) else 0;
    return config.window_words_str.len + restore + 1 + own;
}

/// The window row's two sides (UX K'2), in cells from the window's left:
/// column 0's tag from the inset, `column` cells (its text and its caret's
/// cell; none but while layout.columnInWindowRow), and the window's tag
/// from `words` to the right edge, its last cell the caret's, a server's
/// progress after its text while one runs and the row has room for it
/// (draw.zig). Draw, the mouse, workspaceBlank and a pixel shell's grid
/// read it.
pub const WindowRow = struct { column: u16, words: u16 };
pub fn windowRow(p: *const Pardes) WindowRow {
    const v = p.view();
    const inset = @min(TAG_TEXT_INSET, v.screen_w);
    const column = if (layout.columnInWindowRow(p)) @min(cellsFor(p, headerWidth(p, &v.col_tags[0]) + 1), v.screen_w - inset) else 0;
    var glyphs = headerWidth(p, &p.global_tag) + 1;
    // The progress where the row has room for it beside the column's
    // words; else it is not drawn (draw.zig), and moves nothing.
    if (sessionProgress(p)) |said| {
        const with = glyphs + 2 + progressWidth(p, said);
        if (cellsFor(p, with) <= v.screen_w -| (inset + column)) glyphs = with;
    }
    return .{ .column = column, .words = @max(v.screen_w -| cellsFor(p, glyphs), inset + column) };
}

/// A server's progress that is no pane's, the session's: shown at the
/// window tag's end while it runs.
pub fn sessionProgress(p: *const Pardes) ?*const Messages.Said {
    for (p.messages.live[0..p.messages.live_len]) |*said| if (said.kind == .progress and said.pane == 0) return said;
    return null;
}

/// The width of a server's progress as the window's tag shows it: its
/// glyph, a blank and its words.
pub fn progressWidth(p: *const Pardes, said: *const Messages.Said) usize {
    return panes.File.displayWidth(p.settings.tab, Messages.Kind.progress.glyph()) + 1 + panes.File.displayWidth(p.settings.tab, said.words());
}

/// The grid cells `glyphs` tagline glyphs take: layout.tagCapacity's
/// inverse.
fn cellsFor(p: *const Pardes, glyphs: usize) u16 {
    const m = p.view().row_metrics;
    const body: usize = @max(1, m.body_w);
    const tag: usize = @max(1, m.tagline_w);
    return @intCast(@min(std.math.maxInt(u16), (glyphs * tag + body - 1) / body));
}

/// The header with the keyboard, when one has it.
pub fn focusedHeader(p: *Pardes) ?*Text {
    const v = p.view();
    if (v.header == null) return null;
    if (p.headerColumn()) |c| return if (c < v.ncol) &v.col_tags[c] else null;
    return &p.global_tag;
}

pub fn revealHeader(p: *Pardes) void {
    const v = p.view();
    const t = focusedHeader(p) orelse {
        v.header_scroll = 0;
        v.header_top = 0;
        return;
    };
    const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(v.active), "tag", err);
    const cur: usize = @intCast(@max(0, t.cur_row));
    // Column 0's tag in the window row (UX K'2) has that row and its side.
    const in_row = p.headerColumn() != null and layout.columnInWindowRow(p);
    const rows: usize = if (p.headerColumn() != null and !in_row) layout.columnBarHeight(p) else p.topBarHeight();
    if (cur < v.header_top) v.header_top = cur;
    if (rows > 0 and cur >= v.header_top + rows) v.header_top = cur + 1 - rows;
    const line = modal.lineSlice(text, cur);
    const sides = windowRow(p);
    const width = layout.tagCapacity(p, if (p.headerColumn()) |c| (if (in_row) sides.column else v.col_w[c] -| TAG_TEXT_INSET) else v.screen_w -| sides.words);
    const col = panes.File.rawDisplayCol(p.settings.tab, line, @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len));
    if (col < v.header_scroll) v.header_scroll = col;
    if (col >= v.header_scroll + width) v.header_scroll = col -| (width -| 1);
    var raw = panes.File.rawAtDisplay(p.settings.tab, line, v.header_scroll);
    v.header_scroll = panes.File.rawDisplayCol(p.settings.tab, line, raw);
    if (width > 0 and col >= v.header_scroll + width) {
        raw = modal.nextGrapheme(line, raw);
        v.header_scroll = panes.File.rawDisplayCol(p.settings.tab, line, raw);
    }
}

/// A terminal's directory as its tag shows it: one line, as /index shows
/// it (a newline `\n`), never a raw newline breaking the tag.
fn shownDir(arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
    const dir = pane.cwdSlice();
    if (std.mem.indexOfAny(u8, dir, "\n\\\x7f") == null and for (dir) |c| {
        if (c < ' ') break false;
    } else true) return dir;
    const out = try arena.alloc(u8, dir.len * 4 + 4);
    return pardes.ctlfs.events.shown(dir, out);
}

/// The computed start of a pane's tag -- its path, a PDF's page, a
/// terminal's directory -- without its computed words (restPrefix): the
/// same in every state (UX DESIGN M1). It is never stored, and never
/// edited.
pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
    // A pane a picker previews in names itself, never the preview (UX
    // DESIGN M3): its own file, or where it was made for the picker, which
    // has no rest, its owner's word alone.
    const landing = pardes.Pick.landingOf(p, pane);
    if (landing) |pk| if (pk.made) return std.fmt.allocPrint(arena, "‹" ++ config.pane_addr ++ "{d} ›", .{pk.owner});
    // What is drawn: with no graphics, glyph art whatever `Petscii` says.
    if (pane.addon != null and landing == null) return pardes.Kind.prefix(p, arena, pane);
    // A command pane: its directory, the line it runs, and how that went.
    // Its first line only, cut to 48 bytes at a character's start: a tag's
    // first row is where the prefix ends, and a line that ran over to a
    // second (acme runs a multi-line selection as one command) would move
    // it (body_layer.zig tagTintRange).
    if (pane.command) |line| {
        const first = line[0 .. std.mem.indexOfAny(u8, line, "\r\n") orelse line.len];
        var cut = @min(first.len, 48);
        while (cut < first.len and cut > 0 and first[cut] & 0xC0 == 0x80) cut -= 1;
        const shown = first[0..cut];
        const more = if (shown.len < line.len) "..." else "";
        var idbuf: [48]u8 = undefined;
        const id = exec.replId(&idbuf, pane);
        const gap = if (id.len > 0) " " else "";
        if (!pane.command_done) return std.fmt.allocPrint(arena, "{s} ({s}{s}) running{s}{s}", .{ (try shownDir(arena, pane)), shown, more, gap, id });
        if (pane.command_status) |n| return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit {d}{s}{s}", .{ (try shownDir(arena, pane)), shown, more, n, gap, id });
        return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit ?{s}{s}", .{ (try shownDir(arena, pane)), shown, more, gap, id });
    }
    // A bound REPL says what it is bound as, beside its Term word, while its
    // program runs: a command REPL whose command exited says no id.
    if (pane.repl != null and !(pane.command != null and pane.command_done)) {
        var idbuf: [48]u8 = undefined;
        return std.fmt.allocPrint(arena, "{s} {s}", .{ (try shownDir(arena, pane)), exec.replId(&idbuf, pane) });
    }
    // A query pane: its name and where it is among its hits, `+Search
    // 3/27` (Query.zig): its owner is right above it.
    if (pane.query) |q| if (pane.file) |f| if (pane.prompt != .name) return panes.Query.tagPrefix(q, arena, f.path);
    // Unsaved text shows on the grip, as acme's modbutton does, not as a
    // mark in the text: the prefix is the name alone, and Keep after it
    // while a jump would step it (Trail.zig).
    if (named(p, pane)) |f| {
        const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path;
        const keep = pardes.Trail.reading(p, pane);
        if (pane.trail.n == 0 and !keep) return name;
        // Its walk's back steps before the name, its forward steps after
        // it (Trail.zig), in the room `bytes` measures them; a name its
        // tag has not the rows for cut from the left (`folded`).
        const keep_word = if (keep) " Keep" else "";
        const fold = folded(p, pane);
        const dots = if (fold.cut > 0) "…" else "";
        const room = try arena.alloc(u8, pane.trail.bytes(.back, fold.whole) + dots.len + name.len - fold.cut + pane.trail.bytes(.forward, fold.whole) + keep_word.len);
        var w: std.Io.Writer = .fixed(room);
        pane.trail.write(.back, fold.whole, &w) catch return error.OutOfMemory;
        w.writeAll(dots) catch return error.OutOfMemory;
        w.writeAll(name[fold.cut..]) catch return error.OutOfMemory;
        pane.trail.write(.forward, fold.whole, &w) catch return error.OutOfMemory;
        w.writeAll(keep_word) catch return error.OutOfMemory;
        return w.buffered();
    }
    // A terminal showing kitty graphics says how it draws them, as an image
    // pane does, and so does one drawing them as glyph art by choice.
    if (pane.terminal != null) {
        const chosen = pane.term_petscii;
        const on = chosen or !p.view().frontend.native_images;
        if (chosen or pardes.Term.hasImages(pane.terminal))
            return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" });
    }
    return (try shownDir(arena, pane));
}

/// Where a file's name starts in its tag: after its walk's back steps.
pub fn nameAt(p: *const Pardes, pane: *const Pane) usize {
    return if (pane.file != null and pane.trail.n > 0) pane.trail.bytes(.back, folded(p, pane).whole) else 0;
}

/// How a file's tag at rest writes its walk and its name (UX D8, D2).
pub const Fold = struct {
    /// The newest back steps written whole; older ones fold into `+N`.
    whole: usize = pardes.Trail.shown_steps,
    /// The bytes its name drops from its left, a `…` in their place.
    cut: usize = 0,
    /// Its tag, its name whole, wants more rows than its pane has over
    /// `layout.min_body_rows`: Trail.lift grows it while its column has a
    /// row to give.
    squeezed: bool = false,
};

/// The back steps a file's tag writes whole at rest (UX D8): the newest
/// three (Trail.shown_steps), fewer, down to the newest alone, while its
/// walk would make the tag take more rows than it takes with none: the
/// walk never adds a row to a tag at rest (as far as the newest alone
/// lets it). A pane that walked (a step besides its owner and where it
/// is) whose tag still wants more rows than the pane has over
/// `layout.min_body_rows` keeps its newest step alone and cuts its path
/// from the left to fit them, its basename always whole (UX D2; the
/// coordinator's ruling on seeds 109 and 162: a step never refuses and
/// never takes a row its column cannot give). Rows are counted in cells,
/// as a tag at rest wraps (UX E4, P1's reading 9).
pub fn folded(p: *const Pardes, pane: *const Pane) Fold {
    const t = &pane.trail;
    const f = named(p, pane) orelse return .{};
    if (t.n == 0) return .{};
    const id = panes.paneIdOf(p, pane) orelse return .{};
    const tab = p.settings.tab;
    const width = tagWidth(p, id);
    const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path;
    const keep = pardes.Trail.reading(p, pane);
    const tail = curTail(pane);
    // Its computed words and the blank before its own text (restPrefix).
    const words = panes.File.displayWidth(tab, tagWords(p, pane)) + 1;
    const bare = panes.File.displayWidth(tab, name) + @as(usize, if (keep) " Keep".len else 0) + words + panes.File.displayWidth(tab, tail);
    var whole: usize = pardes.Trail.shown_steps;
    while (whole > 1 and rowsOf(bare + walkCells(t, whole, tab), width) > rowsOf(bare, width)) whole -= 1;
    const r = p.view().rects[id];
    const walked = t.n > @as(usize, @intFromBool(t.steps[0] == .owner)) + 1;
    // A pane not laid out has no rows to cut to: one never laid out, or
    // one the layout has given its width and not yet its height (the band
    // host's floor, layout.floorRows, wraps its tag at rest then).
    if (!keep or !walked or pane.prompt == .name or pane.collapsed or !pane.tag_expanded or r.w == 0 or r.h == 0) return .{ .whole = whole };
    // Its first line: the prefix, its computed words and their blank, the
    // own text's first line; and the rows its others take.
    const first = std.mem.indexOfScalar(u8, tail, '\n') orelse tail.len;
    var below: usize = 0;
    if (first < tail.len) {
        var lines = std.mem.splitScalar(u8, tail[first + 1 ..], '\n');
        while (lines.next()) |line| below += rowsOf(panes.File.displayWidth(tab, line), width);
    }
    const rest = " Keep".len + words + panes.File.displayWidth(tab, tail[0..first]);
    const path = panes.File.displayWidth(tab, name);
    const rows = r.h -| layout.min_body_rows;
    if (@min(rowsOf(walkCells(t, whole, tab) + path + rest, width) + below, pardes.MAX_TAG_ROWS) <= rows) return .{ .whole = whole };
    // The newest step alone, then as much of the path's end as fits, after
    // a `…` cell; where its basename does not fit beside the newest step
    // (a column too narrow for its tag's words), that step folds into the
    // `+N` too.
    const room = (rows -| below) * width;
    const base = if (std.mem.lastIndexOfScalar(u8, name, '/')) |slash| slash + 1 else 0;
    var shown: usize = 1;
    while (true) : (shown -= 1) {
        const used = walkCells(t, shown, tab) + rest;
        if (used + path <= room) return .{ .whole = shown, .squeezed = true };
        const drop = used + path + 1 - room;
        var cut: usize = 0;
        var cells: usize = 0;
        while (cut < base and cells < drop) {
            const next = modal.nextGrapheme(name, cut);
            cells += panes.File.displayWidth(tab, name[cut..next]);
            cut = next;
        }
        if (shown == 0 or cells >= drop) return .{ .whole = shown, .cut = @min(cut, base), .squeezed = true };
    }
}

/// The cells a walk's words take at rest with its newest `whole` back
/// steps whole.
fn walkCells(t: *const pardes.Trail, whole: usize, tab: u16) usize {
    var room: [pardes.Trail.max_steps * (pardes.Trail.max_text + 32)]u8 = undefined;
    var w: std.Io.Writer = .fixed(&room);
    t.write(.back, whole, &w) catch {};
    t.write(.forward, whole, &w) catch {};
    return panes.File.displayWidth(tab, w.buffered());
}

fn rowsOf(cells: usize, width: usize) usize {
    return @max(1, (cells + width - 1) / width);
}

/// The bytes of a file's tag its walk's forward steps take, after its name.
pub fn forwardSpan(p: *const Pardes, pane: *const Pane) [2]usize {
    const f = named(p, pane) orelse return .{ 0, 0 };
    if (pane.trail.n == 0) return .{ 0, 0 };
    const fold = folded(p, pane);
    const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path;
    const dots: usize = if (fold.cut > 0) "…".len else 0;
    const lo = pane.trail.bytes(.back, fold.whole) + dots + name.len - fold.cut;
    return .{ lo, lo + pane.trail.bytes(.forward, fold.whole) };
}

/// The step of pane `pane`'s walk whose word is at byte `at` of its tag's
/// text, if one is there.
pub fn trailAt(p: *const Pardes, pane: *const Pane, at: usize) ?u8 {
    if (pane.trail.n == 0 or pane.file == null) return null;
    const whole = folded(p, pane).whole;
    const ahead = forwardSpan(p, pane);
    if (at < nameAt(p, pane)) return pane.trail.stepAt(.back, whole, at);
    if (at >= ahead[0] and at < ahead[1]) return pane.trail.stepAt(.forward, whole, at - ahead[0]);
    return null;
}

/// A click at shown row `row`, display column `col` of pane `id`'s tag on
/// a word of its walk: that step's Look, or with `run` its Exec
/// (Trail.zig, pick-ui SPEC §6.3). True when it was on one.
pub fn trailClick(p: *Pardes, id: usize, row: usize, col: usize, run: bool) bool {
    const pane = p.panes[id] orelse return false;
    const at = tagOffsetAt(p, pane, row, col) orelse return false;
    if (at.row != 0) return false;
    const i = trailAt(p, pane, at.col) orelse return false;
    if (run) pardes.Trail.execStep(p, id, i) else pardes.Trail.lookStep(p, id, i);
    return true;
}

pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 {
    return prefixIn(p, p.scratch.allocator(), pane);
}

/// The prefix as the tag shows it, built in `arena`: a question follows
/// the path, in place of the computed words.
pub fn prefixIn(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 {
    if (TagState.asks(p, pane)) return arena.dupe(u8, try pathPrefix(p, arena, pane));
    return restPrefix(p, arena, pane);
}

/// The prefix as the tag has it at rest, whatever its state: its path,
/// its computed words (UX K'1) and a blank, read-only, which its own text
/// follows: what its cursor and selections are offsets after (Core.sync's
/// `tag_lead`), what an edit must leave as it is (edit.zig), and the rows
/// it takes at rest (layout.wantedTagRows). The blank is the prefix's:
/// with the own text's first word against `Del`, Look and Exec would see
/// one word.
pub fn restPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 {
    return prefixWith(p, arena, pane, tagWords(p, pane));
}

/// The prefix at rest with computed words `words` (restPrefix's own, or
/// the widest its pane can come to show, widestWords).
pub fn prefixWith(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane, words: []const u8) ![]u8 {
    return std.mem.concat(arena, u8, &.{ try pathPrefix(p, arena, pane), words, " " });
}

/// The tag's own text: the user's (UX K'1), everything typed into the tag
/// after its computed words, kept as typed; until then a terminal's word
/// for its shell, none for the rest.
pub fn curTail(pane: *const Pane) []const u8 {
    return pane.tag.own orelse defaultTail(pane);
}

/// A tag's own text until it is edited: a terminal's word for its shell,
/// `Term` until the shell says its name, then `Term+<shell>`
/// (Core.acknowledgeShell; a click opens another of it), as before UX
/// K'; none for the rest.
pub fn defaultTail(pane: *const Pane) []const u8 {
    if (!pane.isTerminal() or pane.command != null) return "";
    return if (pane.shell_tail_len > 0) pane.shell_tail[0..pane.shell_tail_len] else "Term";
}

/// The words a pane of its kind had in its tag before UX K', its own text
/// until edited then: an own text a dump restores equal to it is dropped
/// (dump.zig dropOldTags).
pub fn kindTail(pane: *const Pane) []const u8 {
    // A kind's: its words (Kind.reopen).
    if (pane.addon) |k| return k.tail.slice();
    if (pane.query != null) return computedWords(pane);
    if (pane.file) |file| if (file.output) |out| if (out.from == .preview) return query_live_tail;
    if (pane.file) |file| if (file.listing != null) return dir_pane_tail;
    if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail;
    if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail;
    if (pane.file) |file| if (file.output) |out| {
        if (std.meta.eql(out.from, panes.Output.Origin{ .cmd = .Diff })) return diff_view_tail;
        if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail;
    };
    const speaks = if (pane.file) |file| file.output == null and file.mini == null and pardes.lsp.speaks(file.path) else false;
    if (panes.File.supportsContext(pane)) return if (speaks) lsp_context_pane_tail else context_pane_tail;
    if (pane.file != null) return if (speaks) lsp_pane_tail else file_pane_tail;
    if (pane.command != null) return command_pane_tail;
    if (pane.isTerminal()) return terminal_pane_tail;
    return pane_tail;
}

/// What the tag shows after its prefix: its own text, or while a question
/// waits on it the question (TagState.asking), computed and read-only, the
/// own text untouched under it. Out of rest the same: the head hangs under
/// the tag (UX DESIGN M1).
pub fn shownTail(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 {
    if (try TagState.asking(p, arena, pane)) |h| return h.text;
    return curTail(pane);
}

/// The tag as it is shown, read and pointed at: its computed prefix and
/// what follows it (shownTail).
pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 {
    return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), try shownTail(p, arena, pane) });
}

/// Give the keyboard to the tag in normal mode (`:`), its cursor where
/// the tag last had it. The first time there is nothing to remember, and
/// it starts on the user's text (UX K'1), after the computed words: what
/// is typed goes there.
pub fn enterTag(p: *Pardes, pane: *Pane) void {
    const t = &pane.tag;
    const whole = tagText(p, p.scratch.allocator(), pane) catch |err| return p.reportError(.at(p.view().active), "tag", err);
    if (!t.cur_pinned) {
        const tail = curTail(pane);
        const at = whole.len - std.mem.trimStart(u8, tail, " ").len;
        const cursor = modal.positionAt(whole, @min(at, whole.len));
        t.cur_row = @intCast(cursor.row);
        t.cur_col = @intCast(cursor.col);
        t.cur_pinned = true;
    }
    takeKeyboard(t, whole);
    t.sticky_col = -1;
    pane.focus = .tag;
}

/// A tag or a header taking the keyboard in normal mode: its cursor where
/// it was, pulled back inside `text` (it may have changed since: a 9P
/// write, a rename), and nothing selected or pending. It is the cursor that
/// is remembered, not a selection.
fn takeKeyboard(t: *Text, text: []const u8) void {
    const rows = modal.cursorLineCount(text);
    t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1));
    const line = modal.lineSlice(text, @intCast(t.cur_row));
    t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col))))));
    t.cur_pinned = true;
    t.vsel.active = false;
    t.nsel = 0;
    t.select = false;
    t.restore_cursor = false;
    t.mode = .normal;
    t.normal.clear();
}

/// A pane's tag as it is shown: its lines, each wrapped onto more rows at
/// the tag's width as acme's frame wraps a tag at its right edge (plan9port
/// acme wind.c:140, wintaglines, counts the frame's lines). `soft` are the
/// offsets in `text` of the newlines the wrapping put in.
pub const Shown = struct {
    text: []u8,
    soft: []const usize,

    /// The tag's own offset of a shown one.
    pub fn toReal(s: Shown, off: usize) usize {
        var n: usize = 0;
        for (s.soft) |b| {
            if (b < off) n += 1 else break;
        }
        return off - n;
    }

    /// The shown offset of the tag's own one.
    pub fn fromReal(s: Shown, real: usize) usize {
        var off = real;
        for (s.soft) |b| {
            if (b <= off) off += 1 else break;
        }
        return off;
    }

    pub fn rows(s: Shown) usize {
        return modal.cursorLineCount(s.text);
    }
};

/// `whole` wrapped at `width` display columns.
pub fn wrapTag(tab: u16, arena: std.mem.Allocator, whole: []const u8, width: usize) !Shown {
    var out: std.ArrayList(u8) = .empty;
    var soft: std.ArrayList(usize) = .empty;
    const w = @max(1, width);
    var lines = std.mem.splitScalar(u8, whole, '\n');
    var first = true;
    while (lines.next()) |line| {
        if (!first) try out.append(arena, '\n');
        first = false;
        var rest = line;
        // The grapheme at column w, if the row runs past it: a row's
        // measure, never the whole rest's (this runs on every step).
        while (true) {
            var cut = panes.File.byteAtDisplay(tab, rest, w);
            if (cut >= rest.len) break;
            if (cut == 0) cut = modal.nextGrapheme(rest, 0);
            try out.appendSlice(arena, rest[0..cut]);
            try soft.append(arena, out.items.len);
            try out.append(arena, '\n');
            rest = rest[cut..];
        }
        try out.appendSlice(arena, rest);
    }
    return .{ .text = out.items, .soft = soft.items };
}

/// The tag's width for wrapping: all its columns. A row the text fills
/// exactly stays one row, as acme's frame wraps a box only when it is wider
/// than what is left (libframe frutil.c _frcklinewrap), and the caret past
/// its end sits at the edge (frptofchar.c clamps it to r.max.x).
pub fn tagWidth(p: *const Pardes, id: usize) usize {
    return @max(1, @as(usize, layout.tagCapacity(p, p.view().rects[id].w -| TAG_TEXT_INSET)));
}

pub fn shownTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !Shown {
    const whole = try tagText(p, arena, pane);
    const id = panes.paneIdOf(p, pane) orelse return .{ .text = whole, .soft = &.{} };
    return wrapTag(p.settings.tab, arena, whole, tagWidth(p, id));
}

/// Where display column `col` of the tag's shown row `row` puts its
/// cursor: the tag as shown, prefix and all, wrapped rows included.
pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Cursor {
    const arena = p.scratch.allocator();
    const shown = shownTag(p, arena, pane) catch return null;
    const whole = tagText(p, arena, pane) catch return null;
    const at = row + pane.tag_top;
    const line = modal.lineSlice(shown.text, at);
    const off = modal.lineStartOffset(shown.text, at) + modal.graphemeStart(line, panes.File.rawAtDisplay(p.settings.tab, line, col));
    return modal.positionAt(whole, @min(shown.toReal(off), whole.len));
}

/// The display column in the name a click drafts at display column `col`
/// of the tag's shown row `row`: on a saving file's path, after its walk's
/// words; null off it.
pub fn onName(p: *const Pardes, pane: *Pane, row: usize, col: usize) ?usize {
    const tab = p.settings.tab;
    if (row + pane.tag_top != 0) return null;
    const f = pane.file orelse return null;
    if (!panes.Output.fileTraits(f.output).saves) return null;
    const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path;
    var room: [pardes.Trail.max_steps * (pardes.Trail.max_text + 32)]u8 = undefined;
    var w: std.Io.Writer = .fixed(&room);
    const fold = folded(p, pane);
    pane.trail.write(.back, fold.whole, &w) catch return null;
    const lead = panes.File.displayWidth(tab, w.buffered());
    // A name cut from its left (`folded`) shows a `…` cell, then its end:
    // the `…` is where its end starts.
    const dots: usize = @intFromBool(fold.cut > 0);
    if (col < lead or col >= lead + dots + panes.File.displayWidth(tab, name[fold.cut..])) return null;
    return panes.File.displayWidth(tab, name[0..fold.cut]) + ((col - lead) -| dots);
}

/// A key typed into a saving file's path, with the tag's cursor there,
/// drafts a new name as a click on it does: the path is computed, so it is
/// never the tag's own text to edit, but a buffer's name can be drafted.
/// True when it did.
pub fn typedIntoName(p: *Pardes, pane: *Pane, key: pardes.Key) bool {
    const f = pane.file orelse return false;
    if (!panes.Output.fileTraits(f.output).saves or pane.tag.cur_row != 0) return false;
    // The name starts after its walk's words.
    const col: usize = @intCast(@max(0, pane.tag.cur_col));
    if (col < nameAt(p, pane)) return false;
    // In a name cut from its left (`folded`), its end after the `…`.
    const cut = folded(p, pane).cut;
    const dots: usize = if (cut > 0) "…".len else 0;
    const at = cut + ((col - nameAt(p, pane)) -| dots);
    const back = key.cp == pardes.Key.backspace or pardes.hit(key, config.insert_backspace_alias);
    const forward = key.cp == pardes.Key.delete or pardes.hit(key, config.insert_delete_alias);
    const typed = key.text.len > 0 and !key.ctrl and !key.alt;
    const inside = if (back) at > 0 and at <= f.path.len else if (forward or typed) at < f.path.len else false;
    if (!inside) return false;
    draftName(p, pane, panes.File.displayWidth(p.settings.tab, f.path[0..at]));
    edit.handleInsert(p.editor(), &pane.input, key);
    return true;
}

/// Start a name draft for a file that can take one, its caret at display
/// column `col` of the path. Nothing changes until it is typed into.
pub fn draftName(p: *Pardes, pane: *Pane, col: usize) void {
    const f = pane.file orelse return;
    if (!panes.Output.fileTraits(f.output).saves) return;
    const name = p.gpa.dupe(u8, f.path) catch |err| return p.reportError(.at(p.view().active), "name", err);
    pane.closePrompt();
    pane.prompt = .name;
    pane.prompt_view = p.live;
    pane.input = .{ .what = .input, .own = name, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(@min(name.len, panes.File.rawAtDisplay(p.settings.tab, name, col))) };
}

/// Commit a drafted buffer name, never a disk rename or write. Keep the
/// draft visible on failure so the user can correct it or cancel with Esc.
pub fn commitTagName(p: *Pardes, pane: *Pane) bool {
    if (pane.prompt != .name) return true;
    const id = panes.paneIdOf(p, pane) orelse return false;
    const name = pane.input.own orelse "";
    if (name.len == 0 or name[name.len - 1] == '/' or !std.unicode.utf8ValidateSlice(name)) {
        p.reportError(.at(id), "name", error.InvalidName);
        return false;
    }
    for (name) |byte| if (byte < ' ') {
        p.reportError(.at(id), "name", error.InvalidName);
        return false;
    };
    var home_buf: [4096]u8 = undefined;
    const full = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), p.expandHome(name, &home_buf) }) catch |err| {
        p.reportError(.at(id), "name", err);
        return false;
    };
    ctlfs.pane.nameBuffer(p, id, full, true) catch |err| {
        p.reportError(.at(id), "name", err);
        return false;
    };
    pane.closePrompt();
    return true;
}

pub fn exitHeader(p: *Pardes) void {
    const v = p.view();
    v.header = null;
    v.header_drag = false;
    v.header_scroll = 0;
    v.header_top = 0;
}

/// Give the keyboard to a column's tag, or the workspace's for null, in
/// normal mode, its cursor where that header last had it; the first time
/// on the user's text, after the computed words (UX K'1), as enterTag.
pub fn enterHeader(p: *Pardes, column: ?usize) void {
    exitHeader(p);
    if (p.panes[p.view().active]) |pane| pane.focus = .body;
    p.view().header = if (column) |c| .{ .column = c } else .workspace;
    if (column) |c| p.setActiveColumn(c);
    const t = focusedHeader(p) orelse return exitHeader(p);
    if (!t.cur_pinned) {
        t.cur_row = 0;
        t.cur_col = @intCast(headerWords(p, t.what).len + 1);
    }
    takeKeyboard(t, edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(p.view().active), "tag", err));
}

/// The span a header's selection covers on line `row` of its text, in
/// that line's bytes: up to the caret while typing, and over the
/// cursor's own cell too in normal mode, where a cursor is a cell.
pub fn headerSelection(t: *const Text, text: []const u8, row: usize) ?struct { lo: usize, hi: usize } {
    if (!t.vsel.active) return null;
    const anchor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) });
    const cursor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
    const lo = @min(anchor, cursor);
    const hi = if (t.mode == .insert) @max(anchor, cursor) else modal.nextGrapheme(text, @max(anchor, cursor));
    const start = modal.lineStartOffset(text, row);
    const end = modal.lineEndOffset(text, row);
    if (hi <= start or lo >= end) return null;
    return .{ .lo = @max(lo, start) - start, .hi = @min(hi, end) - start };
}

/// Whether the window row is blank at cell (col, row): its inset, the
/// cells between its two sides (UX K'2), or past the window's text with
/// two cells kept free for the caret (a B1 there still types at the end of
/// the tag). A pixel shell lets the window be dragged by such a cell, as a
/// browser by the space beside its tabs: blank is no text, so no button of
/// acme's is taken from any. A column's tag and a pane's are not: their
/// blank is where B1 types.
pub fn workspaceBlank(p: *Pardes, col: u16, row: u16, tag_hit: ?pardes.TagHit) bool {
    const v = p.view();
    if (row >= p.topBarHeight() or col >= v.screen_w) return false;
    if (col < TAG_TEXT_INSET) return true;
    const sides = windowRow(p);
    if (col < TAG_TEXT_INSET + sides.column) return false;
    if (col < sides.words) return true;
    const text = topbar(p);
    const scroll: usize = if (v.header != null and p.headerColumn() == null) v.header_scroll else 0;
    const at = @as(usize, Layer.columnAt(p, .workspace, 0, tag_hit, false, 0) orelse (col - sides.words)) + scroll;
    return at >= panes.File.displayWidth(p.settings.tab, modal.lineSlice(text, 0)) + 2;
}

/// Column and workspace tags are one line, as acme's: a newline typed,
/// pasted or restored from a dump into one becomes a space, the caret and
/// the selection kept on the same characters.
pub fn flattenHeaders(p: *Pardes) void {
    for (p.view().col_tags[0..p.view().ncol]) |*t| flatten(p, t);
    flatten(p, &p.global_tag);
}

fn flatten(p: *Pardes, t: *Text) void {
    const own = t.own orelse return;
    if (std.mem.indexOfScalar(u8, own, '\n') == null) return;
    // The caret and the anchor are in the text as shown, words and all.
    const shown = headerText(p, t) catch return;
    const cur = modal.offsetAt(shown, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) });
    const anchor = modal.offsetAt(shown, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) });
    std.mem.replaceScalar(u8, own, '\n', ' ');
    t.cur_row = 0;
    t.cur_col = @intCast(cur);
    t.vsel.row = 0;
    t.vsel.col = @intCast(anchor);
    t.nsel = 0;
}

const WordBounds = struct { lo: usize, hi: usize };

/// The space-delimited word covering `col` in `str` (a header's click and
/// hover), null on a space or past the end.
pub fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds {
    if (col >= str.len or str[col] == ' ') return null;
    var lo: usize = col;
    while (lo > 0 and str[lo - 1] != ' ') lo -= 1;
    var hi: usize = col;
    while (hi < str.len and str[hi] != ' ') hi += 1;
    return .{ .lo = lo, .hi = hi };
}

test "the window row is blank at its inset and between its two sides, and nowhere else (UX K'2)" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 12, .tty_only = true });
    defer p.deinit();
    p.sync();
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    _ = try p.render(arena.allocator());
    const sides = windowRow(p);
    try std.testing.expect(sides.column > 0 and TAG_TEXT_INSET + sides.column < sides.words);
    for (0..TAG_TEXT_INSET) |c| try std.testing.expect(workspaceBlank(p, @intCast(c), 0, null));
    // The column's words and their caret's cell are not; the cells between
    // the two sides are; the window's words and their caret's cell are not.
    for (TAG_TEXT_INSET..TAG_TEXT_INSET + sides.column) |c| try std.testing.expect(!workspaceBlank(p, @intCast(c), 0, null));
    for (TAG_TEXT_INSET + sides.column..sides.words) |c| try std.testing.expect(workspaceBlank(p, @intCast(c), 0, null));
    for (sides.words..80) |c| try std.testing.expect(!workspaceBlank(p, @intCast(c), 0, null));
    // Below the window row: a column's tag, a pane: never.
    for (1..12) |r| try std.testing.expect(!workspaceBlank(p, 79, @intCast(r), null));
    // Hidden, there is none.
    p.settings.workspace_tag = false;
    try std.testing.expect(!workspaceBlank(p, 79, 0, null));
}

test "a column or workspace tag is one line: a newline in it is a space" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 12, .tty_only = true });
    defer p.deinit();
    p.view().col_tags[0].own = try p.gpa.dupe(u8, "New\nSnarf");
    p.view().col_tags[0].cur_row = 1;
    p.view().col_tags[0].cur_col = 2;
    p.global_tag.own = try p.gpa.dupe(u8, "Newcol\nExit");
    p.sync();
    try std.testing.expectEqualStrings("New Term New Snarf", columnTag(p, 0));
    try std.testing.expectEqualStrings("Newcol Exit", p.global_tag.own.?);
    // The caret on the same character, `a` of Snarf.
    try std.testing.expectEqual(@as(i32, 0), p.view().col_tags[0].cur_row);
    try std.testing.expectEqual(@as(i32, "New Term New Sn".len), p.view().col_tags[0].cur_col);
    try std.testing.expectEqual(pardes.COLBAR_H, layout.columnBarHeight(p));
    try std.testing.expectEqual(pardes.TOPBAR_H, p.topBarHeight());
}

test "a pane tag wraps a long line onto rows, and offsets map both ways" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const shown = try wrapTag(config.tab_width, arena_state.allocator(), "/a/b.txt Del Snarf Undo Put\nMore", 10);
    try std.testing.expectEqualStrings("/a/b.txt D\nel Snarf U\nndo Put\nMore", shown.text);
    try std.testing.expectEqual(@as(usize, 4), shown.rows());
    try std.testing.expectEqual(@as(usize, 10), shown.toReal(11)); // the 'e' of Del
    try std.testing.expectEqual(@as(usize, 11), shown.fromReal(10));
}

/// What pane `pane`'s tag says after its path: its computed words, the
/// blank before its own text, and that text.
fn afterPath(p: *Pardes, pane: *Pane) ![]const u8 {
    const a = p.scratch.allocator();
    const whole = try tagText(p, a, pane);
    return whole[(try pathPrefix(p, a, pane)).len..];
}

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

test "a pane tag's computed words are the words that act now, its own text after them (UX K'1, K'3)" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30, .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    const f = &pane.file.?;
    p.sync();
    // A file reading (its jumps walk): Keep (its walk's, after its path),
    // Del.
    try std.testing.expectEqualStrings("/test.txt Keep Del ", try tagText(p, p.scratch.allocator(), pane));
    // Held and clean, no undo step: Del alone.
    pane.trail.held = true;
    try std.testing.expectEqualStrings(" Del ", try afterPath(p, pane));
    // Typed into twice: unsaved, an undo step: Save Undo Del.
    typeKeys(p, "ix");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    typeKeys(p, "iy");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings(" Save Undo Del ", try afterPath(p, pane));
    // Undone once: a step each way, Redo after Undo.
    typeKeys(p, "u");
    try std.testing.expectEqualStrings(" Save Undo Redo Del ", try afterPath(p, pane));
    // Saved: clean, Save gone.
    f.saved_revision = f.revision;
    try std.testing.expectEqualStrings(" Undo Redo Del ", try afterPath(p, pane));
    // A diff, a pager, a pager holding a diff: Diff, Filter first.
    const path = f.path;
    f.path = @constCast("/x.patch");
    try std.testing.expectEqualStrings(" Diff Undo Redo Del", computedWords(pane));
    f.path = path;
    f.pager = true;
    try std.testing.expectEqualStrings(" Filter Undo Redo Del", computedWords(pane));
    f.pager_diff = true;
    try std.testing.expectEqualStrings(" Diff Filter Undo Redo Del", computedWords(pane));
    f.pager = false;
    f.pager_diff = false;
    // A +New: Del, and Undo once it is typed into (it saves nowhere).
    p.newScratchBelow(0);
    const scratch = p.panes[p.view().active].?;
    try std.testing.expect(scratch != pane);
    try std.testing.expectEqualStrings(" Del ", try afterPath(p, scratch));
    typeKeys(p, "iz");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings(" Undo Del ", try afterPath(p, scratch));
    // A kind's own words, then Del; a pane of no kind: Del.
    const doc_id = p.freeSlot().?;
    const doc = try pardes.Kind.open(p, doc_id, pardes.Kind.test_kind.of(p), "/tmp/words.ppm", "");
    try std.testing.expect(std.mem.endsWith(u8, computedWords(doc), " Del"));
    try std.testing.expect(std.mem.indexOf(u8, computedWords(doc), "Collapse") == null);
}

test "typing in a tag goes after its computed words, and stays the user's text through a change of state (UX K'1)" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30, .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    pane.trail.held = true;
    p.sync();
    // `:` `:` gives the keyboard to the tag, on its own text, after Del.
    enterTag(p, pane);
    p.sync();
    typeKeys(p, "iMine");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings("Mine", pane.tag.own.?);
    try std.testing.expectEqualStrings(" Del Mine", try afterPath(p, pane));
    // An edit of the computed words is refused: a Backspace at the start
    // of the user's text, on the blank before it.
    pane.tag.cur_col = @intCast((try restPrefix(p, p.scratch.allocator(), pane)).len);
    typeKeys(p, "i");
    p.update(.{ .key = .{ .cp = pardes.Key.backspace } });
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings("Mine", pane.tag.own.?);
    try std.testing.expectEqualStrings(" Del Mine", try afterPath(p, pane));
    // The body changed: Save Undo come in, the user's text after them,
    // the tag's caret on the same character of it.
    pane.focus = .body;
    typeKeys(p, "ix");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    p.sync();
    try std.testing.expectEqualStrings(" Save Undo Del Mine", try afterPath(p, pane));
    try std.testing.expectEqualStrings("Mine", pane.tag.own.?);
    const whole = try tagText(p, p.scratch.allocator(), pane);
    try std.testing.expectEqual(@as(u8, 'M'), whole[@intCast(pane.tag.cur_col)]);
}

test "a dump of a build before UX K' restores a tag's old default own text as none, any other as the user's (UX K'1)" {
    const dump = @import("dump.zig");
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30, .tty_only = true });
    defer p.deinit();
    const pane = try p.setTestFile("one\n");
    // What a tag of its kind said before (its own text, once edited).
    pane.tag.own = try p.gpa.dupe(u8, kindTail(pane));
    try dump.dumpState(p);
    const dropped = try dump.restore(p, p.dump_out.?, "old");
    defer dropped.deinit();
    try std.testing.expect(dropped.panes[0].?.tag.own == null);
    try std.testing.expectEqualStrings("/test.txt Keep Del ", try tagText(dropped, dropped.scratch.allocator(), dropped.panes[0].?));
    // Edited around: kept whole, after the computed words.
    p.gpa.free(pane.tag.own.?);
    pane.tag.own = try p.gpa.dupe(u8, " Save Term Collapse Follow Del Mine");
    try dump.dumpState(p);
    const kept = try dump.restore(p, p.dump_out.?, "custom");
    defer kept.deinit();
    try std.testing.expectEqualStrings(" Save Term Collapse Follow Del Mine", kept.panes[0].?.tag.own.?);
}

test "a header reads its computed words, then the user's text: typed there, kept through a change of its words (UX K'1, K'2)" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30, .tty_only = true });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    try std.testing.expectEqualStrings("Find Grep Newcol Help Exit ", topbar(p));
    try std.testing.expectEqualStrings("New Term ", columnTag(p, 0));
    // The window's tag given the keyboard starts on the user's text.
    enterHeader(p, null);
    typeKeys(p, "iMine");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings("Mine", p.global_tag.own.?);
    try std.testing.expectEqualStrings("Find Grep Newcol Help Exit Mine", topbar(p));
    // A Backspace on the blank before it is refused: the words are no one's.
    p.global_tag.cur_col = "Find Grep Newcol Help Exit ".len;
    typeKeys(p, "i");
    p.update(.{ .key = .{ .cp = pardes.Key.backspace } });
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings("Find Grep Newcol Help Exit Mine", topbar(p));
    // A dump: its Restore comes into the words, the user's text after it.
    p.setLastDump("/tmp/a.zon");
    try std.testing.expectEqualStrings("Find Grep Newcol Help Exit Restore /tmp/a.zon Mine", topbar(p));
    // A second column: Joincol and Delcol come into every column's words.
    exitHeader(p);
    try std.testing.expect(p.executeBuiltinLine(0, "Newcol"));
    p.sync();
    try std.testing.expectEqualStrings("New Term Joincol Delcol ", columnTag(p, 0));
    try std.testing.expectEqualStrings("New Term Joincol Delcol ", columnTag(p, 1));
    // Newcol gave the keyboard to the new column's tag, on its user's text.
    try std.testing.expectEqual(@as(?usize, 1), p.headerColumn());
    typeKeys(p, "iTwo");
    p.update(.{ .key = .{ .cp = pardes.Key.escape } });
    try std.testing.expectEqualStrings("New Term Joincol Delcol Two", columnTag(p, 1));
    try std.testing.expectEqualStrings("Two", p.view().col_tags[1].own.?);
}

test "a dump of a build before UX K' restores a header's old default own text as none, any other as the user's (UX K'1)" {
    const dump = @import("dump.zig");
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 30, .tty_only = true });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    // What the window's and a column's tags said before, with a Restore.
    p.global_tag.own = try p.gpa.dupe(u8, config.topbar_terminal_str ++ " Restore /tmp/old.zon");
    p.view().col_tags[0].own = try p.gpa.dupe(u8, column_tag_default);
    try dump.dumpState(p);
    const dropped = try dump.restore(p, p.dump_out.?, "old");
    defer dropped.deinit();
    try std.testing.expect(dropped.global_tag.own == null);
    try std.testing.expect(dropped.view().col_tags[0].own == null);
    try std.testing.expectEqualStrings("New Term ", columnTag(dropped, 0));
    // The window's row with Fonts, and no Restore, is dropped too.
    p.gpa.free(p.global_tag.own.?);
    p.global_tag.own = try p.gpa.dupe(u8, config.topbar_window_str);
    try dump.dumpState(p);
    const window = try dump.restore(p, p.dump_out.?, "window");
    defer window.deinit();
    try std.testing.expect(window.global_tag.own == null);
    // Edited around: kept whole, after the computed words.
    p.gpa.free(p.global_tag.own.?);
    p.global_tag.own = try p.gpa.dupe(u8, config.topbar_terminal_str ++ " Mine");
    p.gpa.free(p.view().col_tags[0].own.?);
    p.view().col_tags[0].own = try p.gpa.dupe(u8, "New Mine");
    try dump.dumpState(p);
    const kept = try dump.restore(p, p.dump_out.?, "custom");
    defer kept.deinit();
    try std.testing.expectEqualStrings(config.topbar_terminal_str ++ " Mine", kept.global_tag.own.?);
    try std.testing.expectEqualStrings("New Term New Mine", columnTag(kept, 0));
}

test "a server's progress goes after the window's words where the row has room for it, and moves them by nothing where it has not (UX K'2)" {
    const p = try Pardes.init(std.testing.allocator, .{ .cols = 84, .rows = 20, .tty_only = true });
    defer p.deinit();
    _ = try p.setTestFile("one\n");
    const alone = windowRow(p).words;
    try std.testing.expectEqual(@as(u16, 84 - "Find Grep Newcol Help Exit ".len - 1), alone);
    // Too long for the row beside the column's words: not drawn, and the
    // words stay where they were.
    _ = Messages.say(p, .progress, pardes.MAX_PANES, "lsp zls ready \u{2014} /tmp/claude-1000/a/long/session/directory");
    try std.testing.expectEqual(alone, windowRow(p).words);
    // Short: after the words, two cells between, the words left by as
    // much (`⋯ zls 3/9`, 9 cells).
    _ = Messages.say(p, .progress, pardes.MAX_PANES, "zls 3/9");
    try std.testing.expectEqual(alone - 2 - 9, windowRow(p).words);
}