summaryrefslogtreecommitdiff
path: root/core/Text.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/Text.zig')
-rw-r--r--core/Text.zig673
1 files changed, 673 insertions, 0 deletions
diff --git a/core/Text.zig b/core/Text.zig
new file mode 100644
index 00000000..5acd6146
--- /dev/null
+++ b/core/Text.zig
@@ -0,0 +1,673 @@
+//! 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 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,
+};
+
+/// The owned text standing in for `rows` live terminal rows, beginning at
+/// absolute surface row `row`. The emulator grid remains untouched underneath.
+pub const EditBuffer = struct {
+ row: i32 = 0,
+ rows: i32 = 1,
+ text: []u8 = &.{},
+};
+
+/// One whole-state terminal edit boundary. Null means the pane has not yet
+/// materialized an edit buffer; non-null snapshots own their text.
+pub const Snapshot = struct {
+ ovl: ?EditBuffer,
+ cur_row: i32,
+ cur_col: i32,
+ vsel: CharSel,
+};
+
+pub const history_max = 64;
+
+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 (core/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: [history_max]Snapshot = undefined,
+ed_undo_len: usize = 0,
+ed_redo: [history_max]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 inline fn pane(t: *Text) ?*Pane {
+ // the library's text has none (lib_editor.zig): known at compile time,
+ // so what an edit does with a pane is not compiled there
+ if (comptime @import("pardes_config").lib) return null;
+ 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: []Snapshot, len: *usize, value: Snapshot) void {
+ if (len.* == slots.len) {
+ if (slots[0].ovl) |overlay| gpa.free(overlay.text);
+ std.mem.copyForwards(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: ?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: ?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: ?EditBuffer, back: bool) error{OutOfMemory}!?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: ?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;
+}