summaryrefslogtreecommitdiff
path: root/src/Text.zig
blob: 43a515e1f6206a142cd0489f12c4ada292d68b84 (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
//! One editable text, acme's Text (editors/acme/dat.h:171-190, text.c): the
//! cursor, the selections and the modal state that edit it, and the undo of
//! an edit buffer. A pane's body is one, its tag is another, and so are the
//! answer typed into a pane's prompt and the tags of the columns and the
//! workspace. Where a body's characters come from --
//! a file's content, a terminal's edit overlay, a PDF's text -- is the
//! window's business (edit.zig's editText and flatSurface), the way acme's
//! Text reads its File; every other text owns its characters. Everything
//! here works on the flat text it is handed.
const std = @import("std");
const panes = @import("panes.zig");
const modal = @import("modal.zig");
const config = @import("config.zig");
const memory = @import("memory.zig");
const Pane = panes.Pane;
const File = panes.File;
const terminal = panes.terminal;
const Text = @This();

pub const Mode = enum { normal, insert, tty };

/// Which text of its window this is, acme's `what`. It says where the
/// characters live and whether moving the cursor scrolls a body.
pub const What = enum { body, tag, input, column, workspace };

pub const CharSel = struct {
    active: bool = false,
    row: i32 = 0,
    col: i32 = 0,
    explicit: bool = false,
};

pub const max_selections = memory.limits.selections;

pub const SelRange = struct {
    row: i32,
    col: i32,
    arow: i32,
    acol: i32,
    /// this range's own j/k goal column (helix Range::old_visual_position);
    /// the PRIMARY's copy is Text.sticky_col
    sticky: i32 = -1,
};

/// The replay digest's walk (src/walk.zig) of the histories and the ranges:
/// as far as they go (the ranges' room is made whole and used `nsel` deep).
pub const replica = .{ .len = .{ .{ "ed_undo", "ed_undo_len" }, .{ "ed_redo", "ed_redo_len" }, .{ "sels", "nsel" } } };

what: What = .body,
/// The characters of a text that holds its own (gpa-owned): everything but
/// a body, which reads its pane's. A tag nobody has changed has none yet and
/// shows the default its pane's kind starts with.
own: ?[]u8 = null,
mode: Mode = .normal,
cur_pinned: bool = false,
cur_row: i32 = 0,
cur_col: i32 = 0,
vsel: CharSel = .{},
/// The ranges beside the primary, `nsel` of them: room for max_selections - 1
/// made when a second range appears and given back when the selection is one
/// range again, so a single cursor holds nothing here.
sels: []SelRange = &.{},
nsel: u16 = 0,
/// What a column's or the workspace's tag allocates its ranges from; a text
/// with a pane uses the pane's.
gpa: ?std.mem.Allocator = null,
select: bool = false,
/// sticky goal column for j/k runs (helix old_visual_position): any
/// non-vertical range write resets it to -1.
sticky_col: i32 = -1,
/// The insert session began with `a`: on Esc every range gives back the
/// one character it was stretched by (helix restore_cursor).
restore_cursor: bool = false,
/// Where the last edit ended, a deletion's start or an insertion's end, in
/// surface rows: for `g.` (helix last_edit_pos).
last_edit: ?struct { row: i32, col: i32 } = null,
/// insert `Ctrl-r` was pressed: the next key names the register to insert
reg_wait: bool = false,
normal: modal.Normal.State = .{},
/// last f/F/t/T motion, for Alt-. repeat
find_op: ?modal.Normal.Find = null,
find_ch: u21 = 0,
ed_undo: [terminal.history_max]terminal.Snapshot = undefined,
ed_undo_len: usize = 0,
ed_redo: [terminal.history_max]terminal.Snapshot = undefined,
ed_redo_len: usize = 0,
/// Set when an edit would have changed characters this text does not own
/// (a tag's computed prefix) and was refused; the key that tried it puts
/// the cursor back.
refused: bool = false,

/// The window this text belongs to (acme's t->w). A column's or the
/// workspace's tag belongs to none, and the optional makes every caller
/// say what it does then.
pub fn pane(t: *Text) ?*Pane {
    return switch (t.what) {
        .body => @alignCast(@fieldParentPtr("body", t)),
        .tag => @alignCast(@fieldParentPtr("tag", t)),
        .input => @alignCast(@fieldParentPtr("input", t)),
        .column, .workspace => null,
    };
}

/// Free what a text owns: its characters and the buffers its undo keeps.
pub fn deinit(t: *Text, gpa: std.mem.Allocator) void {
    if (t.sels.len > 0) gpa.free(t.sels);
    if (t.own) |own| gpa.free(own);
    for (t.ed_undo[0..t.ed_undo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text);
    for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text);
    t.* = .{ .what = t.what, .gpa = t.gpa };
}

fn allocator(t: *Text) ?std.mem.Allocator {
    return if (t.pane()) |w| w.gpa else t.gpa;
}

/// Room for the ranges beside the primary; false when there is none to be had.
pub fn reserveSels(t: *Text) bool {
    if (t.sels.len > 0) return true;
    const gpa = t.allocator() orelse return false;
    t.sels = gpa.alloc(SelRange, max_selections - 1) catch return false;
    return true;
}

/// The ranges beside the primary as they were (a refused edit's undoing).
pub fn restoreSels(t: *Text, kept: []const SelRange) void {
    if (kept.len == 0) return t.dropSels();
    if (!t.reserveSels()) return;
    @memcpy(t.sels[0..kept.len], kept);
    t.nsel = @intCast(kept.len);
}

/// Back to one range: the room for the others goes.
pub fn dropSels(t: *Text) void {
    t.nsel = 0;
    if (t.sels.len == 0) return;
    if (t.allocator()) |gpa| gpa.free(t.sels);
    t.sels = &.{};
}

/// Bring the cursor into view (acme's textshow). Only a body scrolls to it;
/// the tagline follows its caret where it is drawn, and a prompt's answer is
/// drawn whole.
pub fn show(t: *Text) void {
    if (t.what == .body) if (t.pane()) |w| w.ensureCursorVisible();
}

pub fn toModalCursor(t: *Text) modal.Cursor {
    return .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) };
}

pub fn fromModalCursor(t: *Text, c: modal.Cursor) void {
    t.cur_row = @as(i32, @intCast(c.row));
    t.cur_col = @intCast(c.col);
    t.cur_pinned = true;
}

pub fn insertVerticalCursor(lines: []const []const u8, c: modal.Cursor, down: bool) modal.Cursor {
    if (lines.len == 0) return c;
    // A cursor past the lines (its text changed under it) moves from the last.
    const row = if (down) @min(c.row + 1, lines.len - 1) else @min(c.row, lines.len) -| 1;
    const target = lines[row];
    if (target.len == 0) return .{ .row = row, .col = 0 };
    const source = if (c.row < lines.len) lines[c.row] else "";
    const goal = File.rawDisplayCol(source, c.col);
    const mapped = File.rawAtDisplay(target, goal);
    const last = modal.prevGrapheme(target, target.len);
    return .{ .row = row, .col = modal.graphemeStart(target, @min(mapped, last)) };
}

pub fn primaryRange(t: *Text, text: []const u8, row0: i32) modal.Selection {
    const c = File.textOffset(t, text, .{ .row = @intCast(@max(0, t.cur_row - row0)), .col = @intCast(@max(0, t.cur_col)) });
    // Both ends through the line index, as the cursor's: cellRange counts
    // lines from the top for each, a pass over a big file per call (the
    // places' settle and every insert-mode key asked it).
    if (t.vsel.active) return cellOffRange(text, File.textOffset(t, text, .{ .row = @intCast(@max(0, t.vsel.row - row0)), .col = @intCast(@max(0, t.vsel.col)) }), c);
    return .{ .anchor = c, .head = modal.nextGrapheme(text, c) };
}

pub fn cellRange(text: []const u8, arow: i32, acol: i32, hrow: i32, hcol: i32) modal.Selection {
    const a = modal.offsetAt(text, .{ .row = @intCast(@max(0, arow)), .col = @intCast(@max(0, acol)) });
    const c = modal.offsetAt(text, .{ .row = @intCast(@max(0, hrow)), .col = @intCast(@max(0, hcol)) });
    return cellOffRange(text, a, c);
}

/// the same, from the two cells' gap offsets
pub fn cellOffRange(text: []const u8, a: usize, c: usize) modal.Selection {
    if (a <= c) return .{ .anchor = a, .head = modal.nextGrapheme(text, c) };
    return .{ .anchor = modal.nextGrapheme(text, a), .head = c };
}

/// A range's cursor and anchor cells, as offsets.
pub const Cells = struct { cur: usize, anc: usize };

pub fn rangeCells(text: []const u8, r: modal.Selection) Cells {
    if (r.head > r.anchor) return .{ .cur = modal.prevGrapheme(text, r.head), .anc = r.anchor };
    if (r.head < r.anchor) return .{ .cur = r.head, .anc = modal.prevGrapheme(text, r.anchor) };
    return .{ .cur = r.head, .anc = r.head };
}

pub fn setRange(t: *Text, text: []const u8, row0: i32, r0: modal.Selection, explicit: bool) void {
    var r = r0;
    if (r.anchor == r.head) r.head = modal.nextGrapheme(text, r.head); // min_width_1
    const off = rangeCells(text, r);
    const cc = File.textPosition(t, text, off.cur);
    // a bare block cursor has both cells on the same offset — the common
    // case by far — and this conversion is not free even indexed
    const ac = if (off.anc == off.cur) cc else File.textPosition(t, text, off.anc);
    t.cur_row = @as(i32, @intCast(cc.row)) + row0;
    t.cur_col = @intCast(cc.col);
    t.vsel = .{
        .active = off.anc != off.cur or t.select,
        .row = @as(i32, @intCast(ac.row)) + row0,
        .col = @intCast(ac.col),
        .explicit = explicit or t.select,
    };
    t.dropSels(); // writing ONE range means the selection IS that range
    t.cur_pinned = true;
    t.sticky_col = -1;
    t.normal.clear();
    t.show();
}

pub fn ranges(t: *Text, text: []const u8, row0: i32, out: *[max_selections]modal.Selection) struct { n: usize, pri: usize } {
    const pr = primaryRange(t, text, row0);
    var n: usize = 0;
    var pri: usize = 0;
    var placed = false;
    for (t.sels[0..t.nsel]) |s| {
        const r = cellRange(text, s.arow - row0, s.acol, s.row - row0, s.col);
        if (!placed and @min(pr.anchor, pr.head) <= @min(r.anchor, r.head)) {
            pri = n;
            out[n] = pr;
            n += 1;
            placed = true;
        }
        out[n] = r;
        n += 1;
    }
    if (!placed) {
        pri = n;
        out[n] = pr;
        n += 1;
    }
    return .{ .n = n, .pri = pri };
}

pub fn setRanges(t: *Text, text: []const u8, in: []const modal.Selection, sticky: []const i32, pri0: usize, explicit: bool) void {
    if (in.len == 0) return; // helix asserts non-empty; here it just means "no change"
    var r: [max_selections]modal.Selection = undefined;
    var st: [max_selections]i32 = undefined;
    var n: usize = @min(in.len, max_selections);
    var pri: usize = @min(pri0, n - 1);
    for (in[0..n], 0..) |x, i| {
        r[i] = x;
        if (r[i].anchor == r[i].head) r[i].head = modal.nextGrapheme(text, r[i].head);
        st[i] = if (i < sticky.len) sticky[i] else -1;
    }
    // insertion sort by start — n is tiny and usually already ordered
    var i: usize = 1;
    while (i < n) : (i += 1) {
        var j = i;
        while (j > 0 and @min(r[j].anchor, r[j].head) < @min(r[j - 1].anchor, r[j - 1].head)) : (j -= 1) {
            std.mem.swap(modal.Selection, &r[j], &r[j - 1]);
            std.mem.swap(i32, &st[j], &st[j - 1]);
            if (pri == j) pri = j - 1 else if (pri == j - 1) pri = j;
        }
    }
    var k: usize = 0;
    i = 1;
    while (i < n) : (i += 1) {
        const a = r[k];
        const b = r[i];
        const af = @min(a.anchor, a.head);
        const at = @max(a.anchor, a.head);
        const bf = @min(b.anchor, b.head);
        const bt = @max(b.anchor, b.head);
        if (af == bf or (at > bf and bt > af)) {
            r[k] = if (a.anchor > a.head and b.anchor > b.head)
                .{ .anchor = @max(a.anchor, b.anchor), .head = @min(a.head, b.head) }
            else
                .{ .anchor = @min(af, bf), .head = @max(at, bt) };
            if (pri == i) pri = k;
            if (st[k] < 0) st[k] = st[i];
            continue;
        }
        k += 1;
        r[k] = b;
        st[k] = st[i];
        if (pri == i) pri = k;
    }
    n = k + 1;
    setRange(t, text, 0, r[pri], explicit);
    if (n > 1 and !t.reserveSels()) return; // no room: the primary alone
    t.sticky_col = st[pri];
    var w: usize = 0;
    for (r[0..n], 0..) |x, idx| {
        if (idx == pri) continue;
        const c = rangeCells(text, x);
        const cc = modal.positionAt(text, c.cur);
        const ac = modal.positionAt(text, c.anc);
        t.sels[w] = .{
            .row = @as(i32, @intCast(cc.row)),
            .col = @intCast(cc.col),
            .arow = @as(i32, @intCast(ac.row)),
            .acol = @intCast(ac.col),
            .sticky = st[idx],
        };
        w += 1;
    }
    t.nsel = @intCast(w);
}

/// helix `scroll` without cursor sync (Ctrl-f/b, PgUp/PgDn, zj/zk): shift
/// the view, then snap a fallen-out cursor to the near scrolloff edge, col 0
pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: i32) void {
    // a view to move through is a body's; a tag or an answer is all shown
    if (t.what != .body) return;
    const w = t.pane() orelse return;
    const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2));
    w.scrollBy(delta);
    const top = w.scroll();
    const last_row: i32 = @intCast(File.textLineCount(t, text) - 1);
    const cur = modal.selectionCursor(text, range);
    if (delta > 0) {
        const snap: i32 = @max(0, @min(top + margin, last_row));
        const head = File.textLineStart(t, text, @intCast(snap));
        if (head <= cur) return;
        const anchor = if (t.select) range.anchor else head;
        setRange(t, text, 0, .{ .anchor = anchor, .head = head }, false);
    } else {
        const snap: i32 = @max(0, @min(top + @as(i32, w.rows) - margin - 1, last_row));
        const head = File.textLineStart(t, text, @intCast(snap));
        if (head >= cur) return;
        const anchor = if (t.select) range.anchor else head;
        setRange(t, text, 0, .{ .anchor = anchor, .head = head }, false);
    }
}

/// helix Range::line_range — the inclusive line span a range covers
pub fn rangeLineSpan(text: []const u8, r: modal.Selection) struct { start: usize, end: usize } {
    const from = @min(r.anchor, r.head);
    const to = @max(r.anchor, r.head);
    const to_adj = if (from == to) to else @max(modal.prevGrapheme(text, to), from);
    return .{ .start = modal.lineAtOffset(text, from), .end = modal.lineAtOffset(text, to_adj) };
}

/// pull the cursor back inside `text` after a rewrite; `row0` is the
/// absolute surface row of its first line (0 for a file)
pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void {
    const n = modal.lineCount(text);
    const row: usize = @min(@as(usize, @intCast(@max(0, t.cur_row - row0))), if (n == 0) 0 else n - 1);
    const llen = modal.lineSlice(text, row).len;
    t.cur_row = @as(i32, @intCast(row)) + row0;
    t.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_col))), llen));
    t.cur_pinned = true;
    t.vsel.active = false;
    t.show();
}

// ---- undo: the edits a text took, as a journal ----

/// One edit as an undo takes it back: at `off`, the bytes `removed` were
/// taken out and `ins` bytes put in. An undo turns it round (keeping the
/// bytes it had put in, and the count of those it took out), so a redo is
/// the same move again.
pub const Entry = struct {
    /// Never written once made: a new one takes its place and the old is
    /// freed raw (a replica's rollback copy pins it, a digest hashes it once).
    pub const replica = .{ .blob = .{"removed"}, .derived = .{"room"} };
    off: usize,
    removed: []u8,
    ins: usize,
    /// A text replaced whole (Get, Edit's e, a Restore, a 9P > body write):
    /// `removed` is the text as it was, its own buffer kept by pointer, not
    /// a copy (`Journal.swap`), and an undo swaps the buffers back.
    swap: bool = false,
    /// The bytes `removed`'s buffer has room for (0: as many as it holds).
    room: usize = 0,
};

/// Where a text was at an undo step's edge: its cursor and selection, and
/// for a file its name's generation and whether, and as what, it was saved
/// (File.restoreName), as acme's undo puts the name back with the text.
pub const Place = struct {
    cur_row: i32 = 0,
    cur_col: i32 = 0,
    vsel: CharSel = .{},
    gen: u32 = 0,
    clean: bool = false,
    saved_hash: ?u64 = null,
    saved_len: ?usize = null,
};

/// One undo step, the entries made from one mark to the next
/// (`entries[first..][0..n]`), and the places at its edges: an undo goes
/// back to `before`, a redo to `after`, where it was undone from.
pub const Step = struct {
    first: usize,
    n: usize = 0,
    before: Place,
    after: Place = .{},
};

/// A text's undo as the edits it took: `steps[0..done]` to undo, last
/// first, the rest to redo. A step is what one key did however many ranges
/// it edited, one open's writes, the writes between two `mark`s. Bounded at
/// limits.undo_max steps and limits.undo_bytes of what they hold, the
/// oldest step dropped first and the newest kept whatever its size.
pub const Journal = struct {
    steps: std.ArrayList(Step) = .empty,
    done: usize = 0,
    entries: std.ArrayList(Entry) = .empty,
    /// What the entries hold: the bytes they took out, and their own size.
    bytes: usize = 0,

    pub fn deinit(j: *Journal, gpa: std.mem.Allocator) void {
        for (j.entries.items) |e| free(gpa, e);
        j.entries.deinit(gpa);
        j.steps.deinit(gpa);
        j.* = .{};
    }

    /// A step's edge, made before an edit: what follows is one step, which
    /// an undo takes back to `place`. None when the last step changed
    /// nothing, its edits undone giving `text` as it is: that step goes on,
    /// its place kept, as a snapshot equal to the text was none.
    pub fn mark(j: *Journal, gpa: std.mem.Allocator, text: []const u8, place: Place) error{OutOfMemory}!void {
        if (j.done > 0) {
            const top = j.steps.items[j.done - 1];
            if (top.before.gen == place.gen and try unchanged(gpa, j.entries.items[top.first..][0..top.n], text)) return;
        }
        try j.steps.ensureUnusedCapacity(gpa, 1);
        j.dropRedo(gpa);
        if (j.steps.items.len == memory.limits.undo_max) j.dropOldest(gpa);
        j.steps.appendAssumeCapacity(.{ .first = j.entries.items.len, .before = place });
        j.done = j.steps.items.len;
    }

    /// The `len` bytes of `text` at `off` about to be replaced by `ins`
    /// bytes, kept in the last step: in its last entry when they touch it
    /// (typing on, deleting what was typed or what borders it, a write
    /// going on where the last ended), else as an entry of its own. The
    /// steps to redo go, made on the text before it; an edit with no step to
    /// go in (before the first mark, or with every step undone) is kept by
    /// none. On no memory the journal empties: its entries would no longer
    /// be the text's.
    pub fn record(j: *Journal, gpa: std.mem.Allocator, text: []const u8, off: usize, len: usize, ins: usize) void {
        if (len == 0 and ins == 0) return;
        j.dropRedo(gpa);
        if (j.done == 0) return;
        const top = &j.steps.items[j.done - 1];
        if (top.n > 0 and !j.entries.items[j.entries.items.len - 1].swap) {
            const last = &j.entries.items[j.entries.items.len - 1];
            if (off >= last.off and off + len <= last.off + last.ins) {
                last.ins = last.ins - len + ins;
                if (last.ins == 0 and last.removed.len == 0) {
                    _ = j.entries.pop();
                    top.n -= 1;
                    j.bytes -= @sizeOf(Entry);
                }
                return;
            }
            const before = off + len == last.off;
            if (ins == 0 and (before or off == last.off + last.ins)) {
                const more = memory.unfilled(gpa, last.removed.len + len) catch return j.deinit(gpa);
                const taken = text[off..][0..len];
                if (before) {
                    @memcpy(more[0..len], taken);
                    @memcpy(more[len..], last.removed);
                    last.off = off;
                } else {
                    @memcpy(more[0..last.removed.len], last.removed);
                    @memcpy(more[last.removed.len..], taken);
                }
                memory.freeRaw(gpa, last.removed);
                last.removed = more;
                j.bytes += len;
                return j.bound(gpa);
            }
        }
        const removed = memory.dupeUnfilled(gpa, text[off..][0..len]) catch return j.deinit(gpa);
        j.entries.append(gpa, .{ .off = off, .removed = removed, .ins = ins }) catch {
            memory.freeRaw(gpa, removed);
            return j.deinit(gpa);
        };
        top.n += 1;
        j.bytes += len + @sizeOf(Entry);
        j.bound(gpa);
    }

    /// A text replaced whole, its old buffer `room` (holding `len` bytes)
    /// kept in the last step by pointer where `record` would copy it, so
    /// neither the edit nor its undo moves a byte; counted in the bound in
    /// bytes by its entry alone. Two are kept a text: a third drops the
    /// oldest steps until two are left, and answers true, that the undo
    /// before them is gone. With no step to go in it is freed.
    pub fn swap(j: *Journal, gpa: std.mem.Allocator, room: []u8, len: usize, ins: usize) bool {
        j.dropRedo(gpa);
        const kept: Entry = .{ .off = 0, .removed = room[0..len], .ins = ins, .swap = true, .room = room.len };
        if (j.done == 0) {
            free(gpa, kept);
            return false;
        }
        j.entries.append(gpa, kept) catch {
            free(gpa, kept);
            j.deinit(gpa);
            return false;
        };
        j.steps.items[j.done - 1].n += 1;
        j.bytes += @sizeOf(Entry);
        var dropped = false;
        while (j.done > 1) {
            var swaps: usize = 0;
            for (j.entries.items) |e| swaps += @intFromBool(e.swap);
            if (swaps <= 2) break;
            j.dropOldest(gpa);
            dropped = true;
        }
        return dropped;
    }

    /// The oldest steps dropped while over the bound in bytes, the last kept.
    fn bound(j: *Journal, gpa: std.mem.Allocator) void {
        while (j.bytes > memory.limits.undo_bytes and j.done > 1) j.dropOldest(gpa);
    }

    fn dropRedo(j: *Journal, gpa: std.mem.Allocator) void {
        if (j.done == j.steps.items.len) return;
        const first = j.steps.items[j.done].first;
        for (j.entries.items[first..]) |e| {
            j.bytes -= held(e);
            free(gpa, e);
        }
        j.entries.shrinkRetainingCapacity(first);
        j.steps.shrinkRetainingCapacity(j.done);
    }

    fn dropOldest(j: *Journal, gpa: std.mem.Allocator) void {
        const n = j.steps.items[0].n;
        for (j.entries.items[0..n]) |e| {
            j.bytes -= held(e);
            free(gpa, e);
        }
        const rest = j.entries.items.len - n;
        @memmove(j.entries.items[0..rest], j.entries.items[n..]);
        j.entries.shrinkRetainingCapacity(rest);
        _ = j.steps.orderedRemove(0);
        for (j.steps.items) |*s| s.first -= n;
        j.done -= 1;
    }

    /// Step `at` made one entry, its first: the rest freed and gone (`turn`
    /// swapped the whole text back, and its first holds what they made).
    pub fn fold(j: *Journal, gpa: std.mem.Allocator, at: usize) void {
        const folded = &j.steps.items[at];
        if (folded.n < 2) return;
        const rest = j.entries.items[folded.first + 1 ..][0 .. folded.n - 1];
        for (rest) |e| {
            j.bytes -= held(e);
            free(gpa, e);
        }
        j.entries.replaceRangeAssumeCapacity(folded.first + 1, rest.len, &.{});
        for (j.steps.items[at + 1 ..]) |*s| s.first -= rest.len;
        folded.n = 1;
    }

    /// What an entry counts in the bound: its copied bytes and its own size.
    pub fn held(e: Entry) usize {
        return @sizeOf(Entry) + if (e.swap) 0 else e.removed.len;
    }

    /// An entry's bytes freed, a swap's whole buffer.
    pub fn free(gpa: std.mem.Allocator, e: Entry) void {
        memory.freeRaw(gpa, e.removed.ptr[0..@max(e.room, e.removed.len)]);
    }
};

/// Whether undoing `entries` gives `text` back as it is. Only the stretch
/// they fell in is undone, in a copy: before their lowest offset nothing
/// changed, nor after the furthest end any reached.
fn unchanged(gpa: std.mem.Allocator, entries: []const Entry, text: []const u8) error{OutOfMemory}!bool {
    if (entries.len == 0) return true;
    var grown: isize = 0;
    for (entries) |e| grown += @as(isize, @intCast(e.ins)) - @as(isize, @intCast(e.removed.len));
    if (grown != 0) return false;
    if (entries.len == 1) return std.mem.eql(u8, text[entries[0].off..][0..entries[0].ins], entries[0].removed);
    var lo: usize = std.math.maxInt(usize);
    var hi: usize = 0;
    for (entries) |e| {
        if (hi > e.off) hi = if (hi >= e.off + e.removed.len) hi - e.removed.len + e.ins else e.off + e.ins;
        lo = @min(lo, e.off);
        hi = @max(hi, e.off + e.ins);
    }
    var window: std.ArrayList(u8) = .empty;
    defer window.deinit(gpa);
    try window.appendSlice(gpa, text[lo..hi]);
    var i = entries.len;
    while (i > 0) {
        i -= 1;
        const e = entries[i];
        try window.replaceRange(gpa, e.off - lo, e.ins, e.removed);
    }
    return std.mem.eql(u8, window.items, text[lo..hi]);
}

fn pushHistory(gpa: std.mem.Allocator, slots: []terminal.Snapshot, len: *usize, value: terminal.Snapshot) void {
    if (len.* == slots.len) {
        if (slots[0].ovl) |overlay| gpa.free(overlay.text);
        std.mem.copyForwards(terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]);
        len.* -= 1;
    }
    slots[len.*] = value;
    len.* += 1;
}

/// Record an edit buffer (a terminal's overlay, a tag's own text) as it
/// stands before an edit, once per change of it, and forget what could have
/// been redone. Null is a buffer not made yet.
pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer) error{OutOfMemory}!void {
    if (t.ed_undo_len > 0) {
        const top = t.ed_undo[t.ed_undo_len - 1];
        const same = if (top.ovl) |overlay| if (current) |now| overlay.row == now.row and
            overlay.rows == now.rows and std.mem.eql(u8, overlay.text, now.text) else false else current == null;
        if (same) return;
    }
    const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = try gpa.dupe(u8, now.text) } else null;
    pushHistory(gpa, &t.ed_undo, &t.ed_undo_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel });
    for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text);
    t.ed_redo_len = 0;
}

/// Undo (back) or redo one edit of an edit buffer: `current` goes on the
/// other history and the state to return to comes back, its cursor and
/// selection already restored here. The caller installs its buffer, which
/// it then owns. Null when there is nothing to step to.
pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer, back: bool) error{OutOfMemory}!?terminal.Snapshot {
    const from, const from_len, const to, const to_len = if (back)
        .{ &t.ed_undo, &t.ed_undo_len, &t.ed_redo, &t.ed_redo_len }
    else
        .{ &t.ed_redo, &t.ed_redo_len, &t.ed_undo, &t.ed_undo_len };
    if (from_len.* == 0) return null;
    const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = try gpa.dupe(u8, now.text) } else null;
    pushHistory(gpa, to, to_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel });
    from_len.* -= 1;
    const back_to = from[from_len.*];
    t.cur_row = back_to.cur_row;
    t.cur_col = back_to.cur_col;
    t.cur_pinned = true;
    t.vsel = back_to.vsel;
    return back_to;
}