From 95a3a1bb822e583988bfe0f312d0ef219b27a454 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 23:06:11 -0300 Subject: Give a pane's body its own Text holding the cursor, selections, mode and undo acme keeps what edits a text in its Text (dat.h:171-190) and the window holds a body and a tag of that type. The cursor, the selections, the modal state and the edit-buffer undo move off Pane into Text.zig, Pane holds them as its body, and the edit and normal-mode operations take the Text they edit. Nothing changes in behaviour; this is the step that lets the tag become a second Text. Co-Authored-By: Claude Opus 5.5 --- src/Text.zig | 606 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 606 insertions(+) create mode 100644 src/Text.zig (limited to 'src/Text.zig') diff --git a/src/Text.zig b/src/Text.zig new file mode 100644 index 00000000..ad5aa186 --- /dev/null +++ b/src/Text.zig @@ -0,0 +1,606 @@ +//! 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. Where its 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; 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 Pane = panes.Pane; +const File = panes.File; +const Terminal = panes.Terminal; +const Text = @This(); + +pub const Mode = enum { normal, insert, tty }; + +/// A modal line selection (helix `x`): whole rows [r0, r1], absolute. +pub const LineSel = struct { + active: bool = false, + r0: i32 = 0, + r1: i32 = 0, +}; + +pub const CharSel = struct { + active: bool = false, + row: i32 = 0, + col: i32 = 0, + explicit: bool = false, +}; + +pub const max_selections = 64; + +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, +}; + +mode: Mode = .normal, +cur_pinned: bool = false, +cur_row: i32 = 0, +cur_col: i32 = 0, +msel: LineSel = .{}, +vsel: CharSel = .{}, +sels: [max_selections - 1]SelRange = undefined, +nsel: u8 = 0, +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, +append_at: ?struct { row: i32, col: i32 } = null, +normal: modal.Normal.State = .{}, +/// last f/F/t/T motion, for Alt-. repeat +find_op: u8 = 0, +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, + +/// The window this text belongs to (acme's t->w). +pub fn pane(t: *Text) *Pane { + return @alignCast(@fieldParentPtr("body", t)); +} + +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; + const row = if (down) @min(c.row + 1, lines.len - 1) else c.row -| 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)) }); + if (t.msel.active) { + // legacy line selection (file-search results highlight): linewise + const r0: usize = @intCast(@max(0, @min(t.msel.r0, t.msel.r1) - row0)); + const r1: usize = @intCast(@max(0, @max(t.msel.r0, t.msel.r1) - row0)); + const s = modal.lineStartOffset(text, r0); + const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); + return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; + } + if (t.vsel.active) return cellRange(text, t.vsel.row - row0, t.vsel.col, t.cur_row - row0, t.cur_col); + 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 }; +} + +pub fn rangeCells(text: []const u8, r: modal.Selection) struct { cur: usize, anc: usize } { + 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.msel.active = false; + t.nsel = 0; // writing ONE range means the selection IS that range + t.cur_pinned = true; + t.sticky_col = -1; + t.normal.clear(); + t.pane().ensureCursorVisible(); +} + +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); + 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); +} + +pub fn multiSelAction(t: *Text, text: []const u8, kind: modal.Normal.Multi, cnt: usize) void { + var rs: [max_selections]modal.Selection = undefined; + const got = ranges(t, text, 0, &rs); + const n = got.n; + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + if (kind == .remove_primary) { + if (n < 2) return; // helix: "no selections remaining" + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + for (rs[0..n], 0..) |r, i| { + if (i == got.pri) continue; + out[m] = r; + m += 1; + } + // helix Selection::remove: the NEXT range takes over, or the + // previous one when the primary was last + return setRanges(t, text, out[0..m], &.{}, @min(got.pri, m - 1), expl); + } + if (kind == .rotate_forward or kind == .rotate_backward) { + const step = cnt % n; + const pri = if (kind == .rotate_forward) (got.pri + step) % n else (got.pri + (n - step)) % n; + return setRanges(t, text, rs[0..n], &.{}, pri, expl); + } + if (kind == .merge) { + // helix merge_selections: first.merge(last) — the ranges are + // sorted, so that is simply the whole span + const lo = @min(rs[0].anchor, rs[0].head); + const hi = @max(rs[n - 1].anchor, rs[n - 1].head); + const rev = rs[0].anchor > rs[0].head and rs[n - 1].anchor > rs[n - 1].head; + const one: modal.Selection = if (rev) .{ .anchor = hi, .head = lo } else .{ .anchor = lo, .head = hi }; + return setRanges(t, text, &.{one}, &.{}, 0, expl); + } + if (kind == .merge_consecutive) { + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + var pri: usize = 0; + for (rs[0..n], 0..) |r, i| { + if (m > 0 and @min(r.anchor, r.head) == @max(out[m - 1].anchor, out[m - 1].head)) { + const lo = @min(@min(out[m - 1].anchor, out[m - 1].head), @min(r.anchor, r.head)); + const hi = @max(@max(out[m - 1].anchor, out[m - 1].head), @max(r.anchor, r.head)); + out[m - 1] = .{ .anchor = lo, .head = hi }; + if (i == got.pri) pri = m - 1; + continue; + } + if (i == got.pri) pri = m; + out[m] = r; + m += 1; + } + return setRanges(t, text, out[0..m], &.{}, pri, expl); + } + if (kind == .split_newline) { + // helix selection::split_on_newline — one range per line the + // selection covers, the newlines themselves left out + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + for (rs[0..n]) |r| { + const from = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + if (from == to) { + if (m < max_selections) { + out[m] = r; + m += 1; + } + continue; + } + var start = from; + while (start < to and m < max_selections) { + const eol = modal.lineEndOffset(text, modal.lineAtOffset(text, start)); + if (eol >= to) { + out[m] = .{ .anchor = start, .head = to }; + m += 1; + break; + } + out[m] = .{ .anchor = start, .head = eol }; + m += 1; + start = eol + 1; + } + } + if (m == 0) return; + return setRanges(t, text, out[0..m], &.{}, 0, true); // helix keeps primary 0 + } + if (kind == .trim) { + // helix trim_selections: whitespace off both ends; ranges that are + // empty or all whitespace are dropped entirely + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + for (rs[0..n]) |r| { + var from = @min(r.anchor, r.head); + var to = @max(r.anchor, r.head); + while (from < to and std.ascii.isWhitespace(text[from])) from += 1; + while (to > from and std.ascii.isWhitespace(text[to - 1])) to -= 1; + if (from >= to) continue; + out[m] = if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to }; + m += 1; + } + if (m == 0) { // helix: collapse_selection + keep_primary_selection + const c = modal.selectionCursor(text, rs[got.pri]); + return setRange(t, text, 0, .{ .anchor = c, .head = c }, false); + } + // helix: the first survivor that OVERLAPS the old primary, else the last + const pf = @min(rs[got.pri].anchor, rs[got.pri].head); + const pt = @max(rs[got.pri].anchor, rs[got.pri].head); + var pri = m - 1; + for (out[0..m], 0..) |r, i| { + const f = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + if (f == pf or (to > pf and pt > f)) { + pri = i; + break; + } + } + return setRanges(t, text, out[0..m], &.{}, pri, expl); + } + const below = kind == .copy_below; + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + var pri: usize = 0; + const nlines = modal.cursorLineCount(text); + for (rs[0..n], 0..) |r, ri| { + const is_pri = ri == got.pri; + // head-exclusive: back the leading end off onto its own cell + const hp = modal.positionAt(text, if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head); + const ap = modal.positionAt(text, if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor)); + const height = @max(hp.row, ap.row) - @min(hp.row, ap.row) + 1; + if (m >= max_selections) break; + if (is_pri) pri = m; + out[m] = r; + m += 1; + var made: usize = 0; + var k: usize = 0; + while (made < cnt and m < max_selections) : (k += 1) { + const d = (k + 1) * height; + const arow = if (below) ap.row + d else ap.row -| d; + const hrow = if (below) hp.row + d else hp.row -| d; + if (arow >= nlines or hrow >= nlines) break; + const a2 = modal.offsetAt(text, .{ .row = arow, .col = ap.col }); + const h2 = modal.offsetAt(text, .{ .row = hrow, .col = hp.col }); + // a line too short to reach the column is skipped, not clamped + if (modal.positionAt(text, a2).col == ap.col and modal.positionAt(text, h2).col == hp.col) { + if (is_pri) pri = m; + out[m] = modal.moveSelectionCursor(text, .{ .anchor = a2, .head = a2 }, h2, true); + m += 1; + made += 1; + } + if (arow == 0 and hrow == 0) break; + } + } + setRanges(t, text, out[0..m], &.{}, pri, expl); +} + +/// a range's start CELL (document order key) — the smaller of its two ends +pub fn selStart(s: SelRange) struct { row: i32, col: i32 } { + if (s.arow < s.row or (s.arow == s.row and s.acol < s.col)) return .{ .row = s.arow, .col = s.acol }; + return .{ .row = s.row, .col = s.col }; +} + +pub fn maxLine(text: []const u8) usize { + const nl = modal.cursorLineCount(text); + return if (text.len == 0 or text[text.len - 1] == '\n') nl -| 2 else nl - 1; +} + +/// point-target motion: collapse there (extend in select mode) +pub fn pointMove(t: *Text, text: []const u8, range: modal.Selection, target: usize) void { + setRange(t, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false); +} + +/// word motions select their traversed span (extend mode: head only) +pub fn wordMove(t: *Text, text: []const u8, range: modal.Selection, cnt: usize, target: modal.WordTarget) void { + const wr = modal.moveWord(text, range, cnt, target); + const res = if (t.select) modal.moveSelectionCursor(text, range, modal.selectionCursor(text, wr), true) else wr; + setRange(t, text, 0, res, false); +} + +/// f/t/F/T: anchor at the old cursor cell, head on the hit (not found: no move) +pub fn findMove(t: *Text, text: []const u8, range: modal.Selection, ch: u21, fwd: bool, till: bool, cnt: usize) void { + const cur = modal.selectionCursor(text, range); + const target = modal.findTarget(text, cur, ch, fwd, till, cnt) orelse return; + const res = if (t.select) + modal.moveSelectionCursor(text, range, target, true) + else + modal.moveSelectionCursor(text, .{ .anchor = cur, .head = cur }, target, true); + setRange(t, text, 0, res, false); +} + +/// j/k and friends: sticky goal column, clamped onto short lines' newline +pub fn verticalMove(t: *Text, text: []const u8, range: modal.Selection, down: bool, cnt: usize) void { + const cur = modal.selectionCursor(text, range); + const pos = File.textPosition(t, text, cur); + const goal: usize = if (t.sticky_col >= 0) + @intCast(t.sticky_col) + else + File.rawDisplayCol(File.textLine(t, text, pos.row), pos.col); + const last_row = File.textLineCount(t, text) - 1; + const nline = if (down) @min(pos.row + @max(1, cnt), last_row) else pos.row -| @max(1, cnt); + const target_col = File.rawAtDisplay(File.textLine(t, text, nline), goal); + const target = File.textOffset(t, text, .{ .row = nline, .col = target_col }); + // extend mode never walks onto the empty trailing line (helix) + if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return; + setRange(t, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false); + t.sticky_col = @intCast(goal); +} + +pub fn visualMove( + t: *Text, + text: []const u8, + range: modal.Selection, + down: bool, + cnt: usize, + width: usize, +) void { + const cur = modal.selectionCursor(text, range); + const pos = File.textPosition(t, text, cur); + const last_row = File.textLineCount(t, text) - 1; + var row = pos.row; + var line = modal.lineSlice(text, row); + var vrow = File.visualRow(line, pos.col, width); + const goal: usize = if (t.sticky_col >= 0) + @intCast(t.sticky_col) + else + File.rawDisplayCol(line[vrow.start..vrow.end], pos.col -| vrow.start); + var steps = @max(1, cnt); + while (steps > 0) : (steps -= 1) { + if (down) { + if (vrow.end < line.len) { + vrow = File.visualRow(line, vrow.end, width); + continue; + } + if (row == last_row) break; + row += 1; + line = modal.lineSlice(text, row); + vrow = File.visualRow(line, 0, width); + } else { + if (vrow.start > 0) { + vrow = File.visualRow(line, vrow.start - 1, width); + continue; + } + if (row == 0) break; + row -= 1; + line = modal.lineSlice(text, row); + vrow = File.visualRow(line, line.len, width); + } + } + // The newline slot is a real cursor position, but the first byte of the + // NEXT visual row is not: landing there would read as two rows moved. + var target_col = vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); + if (vrow.end < line.len and target_col >= vrow.end) + target_col = modal.graphemeStart(line, vrow.end - 1); + const target = File.textOffset(t, text, .{ .row = row, .col = target_col }); + // extend mode never walks onto the empty trailing line (helix) + if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return; + setRange(t, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false); + t.sticky_col = @intCast(goal); +} + +/// Ctrl-d/u: scroll half a page AND move the cursor by the same rows +pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bool) void { + const half: i32 = @max(1, @divTrunc(@as(i32, t.pane().rows), 2)); + t.pane().scrollBy(if (down) half else -half); + verticalMove(t, text, range, down, @intCast(half)); +} + +/// 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 { + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); + t.pane().scrollBy(delta); + const top = t.pane().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, t.pane().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); + } +} + +/// gt/gc/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) +pub fn gotoWindow(t: *Text, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); + const top = t.pane().scroll(); + const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); + const last_vis: i32 = @min(@as(i32, t.pane().rows) - 1, last_row - top); + const n: i32 = @intCast(cnt - 1); + var vline: i32 = switch (which) { + .top => top + margin + n, + .center => top + @divTrunc(last_vis, 2), + .bottom => top + last_vis - (margin + n), + }; + vline = @max(vline, top + margin); + vline = @min(vline, top + last_vis - margin); + const row: i32 = std.math.clamp(vline, 0, last_row); + pointMove(t, text, range, File.textLineStart(t, text, @intCast(row))); +} + +/// 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) }; +} + +fn lineStartOrEof(text: []const u8, line: usize) usize { + if (line >= modal.cursorLineCount(text)) return text.len; + return modal.lineStartOffset(text, line); +} + +/// helix `x` extend_line_below: full lines incl. the newline, cursor ON +/// the last one's '\n'; an already-line-bounded selection grows downward +pub fn lineSelect(t: *Text, text: []const u8, range: modal.Selection, cnt: usize) void { + const span = rangeLineSpan(text, range); + const start = modal.lineStartOffset(text, span.start); + const end = lineStartOrEof(text, span.end + 1); + const full = @min(range.anchor, range.head) == start and @max(range.anchor, range.head) == end; + const head = lineStartOrEof(text, span.end + cnt + @intFromBool(full)); + setRange(t, text, 0, .{ .anchor = start, .head = head }, true); +} + +/// helix `X` extend_to_line_bounds (direction kept) +pub fn lineBoundsSelect(t: *Text, text: []const u8, range: modal.Selection) void { + const span = rangeLineSpan(text, range); + const start = modal.lineStartOffset(text, span.start); + const end = lineStartOrEof(text, span.end + 1); + const r: modal.Selection = if (range.head < range.anchor) + .{ .anchor = end, .head = start } + else + .{ .anchor = start, .head = end }; + setRange(t, text, 0, r, true); +} + +/// helix `Alt-x` shrink_to_line_bounds (single-line selections untouched) +pub fn shrinkSelToLineBounds(t: *Text, text: []const u8, range: modal.Selection) void { + const span = rangeLineSpan(text, range); + if (span.start == span.end) return; + const from = @min(range.anchor, range.head); + const to = @max(range.anchor, range.head); + var start = modal.lineStartOffset(text, span.start); + var end = lineStartOrEof(text, span.end + 1); + if (start != from) start = lineStartOrEof(text, span.start + 1); + if (end != to) end = modal.lineStartOffset(text, span.end); + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + const r: modal.Selection = if (range.head < range.anchor) + .{ .anchor = end, .head = start } + else + .{ .anchor = start, .head = end }; + setRange(t, text, 0, r, expl); +} + +/// 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.msel.active = false; + t.pane().ensureCursorVisible(); +} -- cgit v1.3 From 9584b0682b45f17aaa42157540947904d867777a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 23:42:53 -0300 Subject: Give prompts their own line to type into instead of the tag's tail A search, pipe or Save prompt wrote its marker and answer onto the end of the tag, so the tag's cursor, its selection, its 9P writes and a prompt abandoned by a click all shared one buffer: the abandoned text stayed in the tag and a 9P write landed inside the prompt. The answer is now its own Text on the pane, typed in insert mode and shown on the notice band where it was already drawn, and the tag never holds any of it. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 5 +- src/File.zig | 3 +- src/Pipe.zig | 19 ++-- src/Text.zig | 33 +++++-- src/body_layer.zig | 4 +- src/edit.zig | 116 +++++++++++++++--------- src/exec.zig | 8 +- src/mouse.zig | 4 + src/normal.zig | 11 +-- src/panes.zig | 36 ++++---- src/pardes.zig | 168 +++++++++++++++++++---------------- test/panes.zig | 154 ++++++++------------------------ test/pdf.zig | 4 +- test/snapshots/find.golden | 1 - test/snapshots/find.snap | 3 +- test/snapshots/tagbottomshort.golden | 2 +- test/snapshots/tagbottomshort.snap | 9 +- 17 files changed, 282 insertions(+), 298 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 4de3901a..0813c193 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -235,8 +235,9 @@ other cursors where they are (`FileSnap` holds one range). ### Regex selection (`s` / `S`) — the interactive pair -Both arm the tag input the same way `/` does — the pattern is typed into the -tag tail after a marker, no popup — and both re-run on EVERY keystroke, from +Both arm the prompt the same way `/` does — the pattern is typed after a +marker on the prompt's own line in the notice band, no popup — and both +re-run on EVERY keystroke, from the selection the prompt opened on (`Pane.sel_snap`). That is what makes the selection a live preview, what makes typing a pattern one character at a time land where pasting it whole would, and what makes Esc a plain restore. Enter diff --git a/src/File.zig b/src/File.zig index 239aa4ba..bf4bf08c 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1129,7 +1129,8 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; - const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); + const typing_body = !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side); + const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) const body_y = p.bodyTop(r); const context_bg = p.theme().tag_bg; diff --git a/src/Pipe.zig b/src/Pipe.zig index c2b49f31..3e6752a8 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -73,13 +73,12 @@ pub fn submitPipe(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; - const prompt = switch (pane.prompt) { + const how = switch (pane.prompt) { .pipe => |pipe| pipe, else => return, }; - const tail = pane.tagSlice(); - const armed = tail[@min(prompt.at, tail.len)..]; - const marker = pipeMarker(prompt.how); + const armed = pane.promptText() orelse return; + const marker = pipeMarker(how); if (!std.mem.startsWith(u8, armed, marker)) return; const command = armed[marker.len..]; if (command.len == 0) return; @@ -87,11 +86,11 @@ pub fn submitPipe(p: *Pardes, id: usize) void { var ranges: [panes.Text.max_selections]modal.Selection = undefined; const got = pane.body.ranges(f.content, 0, &ranges); // `!`/`A-!` take no stdin and run ONCE — see `PendingPipe.nranges`. - const ninputs = if (prompt.how.pipes()) got.n else 1; + const ninputs = if (how.pipes()) got.n else 1; const inputs = p.gpa.alloc(selection_pipe.Input, ninputs) catch return; var made: usize = 0; for (ranges[0..ninputs], 0..) |range, i| { - const bytes = if (prompt.how.pipes()) bytes: { + const bytes = if (how.pipes()) bytes: { const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); if (hi > f.content.len) break; @@ -131,7 +130,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void { .ranges = ranges, .primary = @intCast(got.pri), .explicit = (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active, - .how = prompt.how, + .how = how, .nranges = @intCast(got.n), }; p.emit(.{ .pipe = .{ .id = p.pipe.seq } }); @@ -295,12 +294,12 @@ test "selection pipe prompt submits exact request and Escape cancels" { pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(pane.tag_edit and pane.prompt == .pipe); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), config.pipe_marker)); + try std.testing.expect(!pane.tag_edit and pane.prompt == .pipe); + try std.testing.expectEqualStrings(config.pipe_marker, pane.promptText().?); try std.testing.expect(nextPipeEffect(p) == null); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); + try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe and pane.input.own == null); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); diff --git a/src/Text.zig b/src/Text.zig index ad5aa186..aaa6dc88 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -1,9 +1,11 @@ //! 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. Where its 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; everything here works on the flat text it is handed. +//! an edit buffer. A pane's body is one, and so is the answer typed into a +//! pane's prompt. 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"); @@ -15,6 +17,10 @@ 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, input }; + /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. pub const LineSel = struct { active: bool = false, @@ -41,6 +47,10 @@ pub const SelRange = struct { sticky: i32 = -1, }; +what: What = .body, +/// The characters of a text that holds its own (gpa-owned): everything but +/// a body, which reads its pane's. +own: ?[]u8 = null, mode: Mode = .normal, cur_pinned: bool = false, cur_row: i32 = 0, @@ -65,7 +75,16 @@ ed_redo_len: usize = 0, /// The window this text belongs to (acme's t->w). pub fn pane(t: *Text) *Pane { - return @alignCast(@fieldParentPtr("body", t)); + return switch (t.what) { + .body => @alignCast(@fieldParentPtr("body", t)), + .input => @alignCast(@fieldParentPtr("input", t)), + }; +} + +/// Bring the cursor into view (acme's textshow). Only a body scrolls to it; +/// a prompt's answer is drawn whole. +pub fn show(t: *Text) void { + if (t.what == .body) t.pane().ensureCursorVisible(); } pub fn toModalCursor(t: *Text) modal.Cursor { @@ -143,7 +162,7 @@ pub fn setRange(t: *Text, text: []const u8, row0: i32, r0: modal.Selection, expl t.cur_pinned = true; t.sticky_col = -1; t.normal.clear(); - t.pane().ensureCursorVisible(); + t.show(); } pub fn ranges(t: *Text, text: []const u8, row0: i32, out: *[max_selections]modal.Selection) struct { n: usize, pri: usize } { @@ -602,5 +621,5 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.cur_pinned = true; t.vsel.active = false; t.msel.active = false; - t.pane().ensureCursorVisible(); + t.show(); } diff --git a/src/body_layer.zig b/src/body_layer.zig index 71529326..1f210220 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -460,8 +460,8 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id } // cursor: tracks the shell cursor until pinned by a click or a key - // (the tag cursor above wins while the tag is focused) - if (active and !pane.tag_edit) { + // (the tag's or a prompt's cursor wins while that is being typed into) + if (active and !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side)) { if (pane.body.mode != .tty) { const cur = panes.Terminal.gridCursor(pane); const goff = panes.Terminal.gridOffset(pane); diff --git a/src/edit.zig b/src/edit.zig index f1b381d6..5249a64c 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -84,12 +84,23 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { const pane = p.panes[id] orelse return; if (req) |r| if (pane.serial != r.serial) return; p.active = id; + if (pane.prompt != .none and pane.prompt != .del_side) { + // an answer is one line: a newline in it would only be submitting it + const line = p.scratch.allocator().alloc(u8, bytes.len) catch return; + var n: usize = 0; + for (bytes) |byte| if (byte != '\n' and byte != '\r') { + line[n] = byte; + n += 1; + }; + if (n > 0) insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] }); + if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); + return; + } if (pane.tag_edit) { const text = p.tagText(p.scratch.allocator(), pane) catch return; const range: @TypeOf(Pardes.tagSelBounds(pane)) = if (pane.tag_sel) Pardes.tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; _ = p.replaceTagText(pane, range.lo, hi, bytes); - if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); @@ -274,7 +285,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { t.cur_col = @intCast(bc.col); t.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); for (t.sels[0..t.nsel]) |*s| { const sgap = modal.offsetAt(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) }); const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap); @@ -288,8 +299,15 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { } pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { - const pane = t.pane(); const arena = p.scratch.allocator(); + if (t.what != .body) { + const text = t.own orelse ""; + const lines = try arena.alloc([]const u8, std.mem.count(u8, text, "\n") + 1); + var it = std.mem.splitScalar(u8, text, '\n'); + for (lines) |*line| line.* = it.next().?; + return lines; + } + const pane = t.pane(); if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.hasPdf()) { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); @@ -299,9 +317,8 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { - const pane = t.pane(); - if (pane.file != null) - return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); + if (t.what == .body and t.pane().file != null) + return panes.File.byteAtRowDisplay(t.pane(), row, from_raw, display_col); const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col); const local = row; if (local < 0 or @as(usize, @intCast(local)) >= lines.len) @@ -316,14 +333,20 @@ pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_ /// Freeze the live terminal cursor into the modal coordinate space. The /// emulator reports screen cells; editing state stores UTF-8 byte offsets. pub fn pinPaneCursor(p: *Pardes, t: *Text) void { - const pane = t.pane(); if (t.cur_pinned) return; + // Only a body has a live cursor of someone else's to freeze. + if (t.what != .body) { + t.cur_pinned = true; + return; + } + const pane = t.pane(); pane.pinCursor(); if (pane.file == null and !pane.hasPdf()) t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); } pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { + if (t.what != .body) return t.own orelse ""; const pane = t.pane(); if (pane.file) |f| return f.content; if (pane.hasPdf()) { @@ -335,13 +358,16 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { + if (t.what != .body) return 0; const pane = t.pane(); if (pane.file == null) return 0; return panes.File.wrapWidth(pane, p.settings.wrap); } -/// Route shared edit operations to a file's content or a terminal overlay. +/// Route shared edit operations to the characters `t` edits: its own, or +/// for a body its file's content or its terminal's overlay. fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { + if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; @@ -358,6 +384,11 @@ fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { /// install a rewritten editable text (frees the old one) fn setEditText(p: *Pardes, t: *Text, new: []u8) void { + if (t.what != .body) { + if (t.own) |old| p.gpa.free(old); + t.own = new; + return; + } const pane = t.pane(); if (pane.file) |*f| return panes.File.setContent(p, f, new); panes.Terminal.setEditText(p, pane, new); @@ -368,6 +399,7 @@ pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_a /// Files insert only inside existing rows and at grapheme boundaries. /// Terminal overlays can materialize virtual rows/columns, so keep those. pub fn clampFileCursor(t: *Text) bool { + if (t.what != .body) return false; const pane = t.pane(); const file = if (pane.file) |*file| file else return false; const old_row = t.cur_row; @@ -380,8 +412,7 @@ pub fn clampFileCursor(t: *Text) bool { } pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { - const pane = t.pane(); - if (pane.hasPdf()) return; + if (t.what == .body and t.pane().hasPdf()) return; pinPaneCursor(p, t); _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so @@ -478,7 +509,7 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { t.mode = .insert; t.msel.active = false; t.normal.clear(); - pane.ensureCursorVisible(); + t.show(); } pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { @@ -487,7 +518,6 @@ pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { } pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { - const pane = t.pane(); // helix aliases: normalize to the base key and re-dispatch if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace }); if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter }); @@ -507,7 +537,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { else => cur0, }; t.fromModalCursor(nc); - pane.ensureCursorVisible(); + t.show(); return; }, Key.page_up, Key.page_down => { @@ -515,14 +545,15 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { // scroll + cursor snap as normal mode const flat = flatSurface(p, t) catch return; const range = t.primaryRange(flat, 0); - const step: i32 = @intCast(@max(1, pane.rows)); + if (t.what != .body) return; + const step: i32 = @intCast(@max(1, t.pane().rows)); t.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); return; }, Key.home => { t.cur_col = 0; t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; }, Key.end => { @@ -531,7 +562,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const cur0 = t.toModalCursor(); t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; }, else => {}, @@ -549,7 +580,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { } else t.cur_col += 1; } t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } // helix insert-mode kills (word/line; deleteSpan is exclusive) @@ -569,7 +600,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; t.cur_col = @intCast(fc.col); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } if (hit(key, config.delete_word_forward)) { @@ -592,7 +623,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { setEditText(p, t, new); t.cur_col = 0; t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } if (hit(key, config.kill_to_line_end)) { @@ -615,7 +646,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.cur_row += 1; t.cur_col = @intCast(indent); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); }, Key.backspace => { if (t.cur_col > 0) { @@ -625,7 +656,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { setEditText(p, t, new); t.cur_col = @intCast(prev); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } // at col 0: eat the newline above (join up) — a terminal grows @@ -640,7 +671,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.cur_row -= 1; t.cur_col = @intCast(prevlen); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); }, Key.delete => { // delete forward; at line end eat the newline (join), which on @@ -661,7 +692,8 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { Key.tab => { const ln = modal.lineSlice(text, c.row); if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { - const f = pane.file orelse break :dot; + if (t.what != .body) break :dot; + const f = t.pane().file orelse break :dot; if (f.output != null or !lsp.speaks(f.path)) break :dot; const seq = p.lsp_seq; p.lspRequest(p.active, .completion, ""); @@ -684,7 +716,7 @@ pub fn insertTab(p: *Pardes, t: *Text) void { setEditText(p, t, new); t.cur_col += @intCast(pad); t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 }; @@ -779,7 +811,7 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { t.cur_col = 0; t.msel.active = false; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } else { pushUndo(p, t); const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return; @@ -799,12 +831,11 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { } pub fn normalYank(p: *Pardes, t: *Text) void { - const pane = t.pane(); t.select = false; - if (pane.rawPointerText(pane.sel[sel_slot])) |text| { + if (t.what == .body) if (t.pane().rawPointerText(t.pane().sel[sel_slot])) |text| { setYank(p, text); return; - } + }; if (t.vsel.active) { setYank(p, vselText(p, t)); return; @@ -882,11 +913,10 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz } t.msel.active = false; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } pub fn normalChange(p: *Pardes, t: *Text) void { - const pane = t.pane(); t.select = false; t.sticky_col = -1; if (t.vsel.active) { @@ -913,7 +943,7 @@ pub fn normalChange(p: *Pardes, t: *Text) void { t.cur_pinned = true; t.mode = .insert; t.normal.clear(); - pane.ensureCursorVisible(); + t.show(); return; } setYank(p, vselText(p, t)); @@ -974,7 +1004,7 @@ pub fn normalChange(p: *Pardes, t: *Text) void { t.cur_pinned = true; t.mode = .insert; t.normal.clear(); - pane.ensureCursorVisible(); + t.show(); } else { pushUndo(p, t); const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return; @@ -1075,7 +1105,7 @@ fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) void { } t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } /// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), @@ -1174,7 +1204,7 @@ pub fn normalJoin(p: *Pardes, t: *Text) void { t.msel.active = false; t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { @@ -1242,7 +1272,7 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { t.msel.active = false; t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } pub fn normalToggleComment(p: *Pardes, t: *Text) void { @@ -1277,7 +1307,7 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { } next = @max(next, end); } - const ext = if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; + const ext = if (t.what != .body) "" else if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; var token: []const u8 = config.comment_token_default; lang: for (config.comment_tokens) |row| { for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { @@ -1359,7 +1389,7 @@ pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) void { t.cur_col = @intCast(cc.col); t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } /// `]Space` / `[Space`: add blank lines below/above, the cursor staying @@ -1381,7 +1411,7 @@ pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) void { t.vsel.row += @intCast(cnt); } t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } /// pair mapping for m-mode: either bracket names the pair; anything else @@ -1450,7 +1480,7 @@ pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) void { t.cur_col = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0)); t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } /// `md`: delete the enclosing pair's chars; the cursor maps through @@ -1487,7 +1517,7 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) void { t.vsel.active = false; t.msel.active = false; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } /// `mr`: swap the enclosing pair's chars for 's @@ -1512,20 +1542,24 @@ pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) void { } pub fn pushUndo(p: *Pardes, t: *Text) void { - const pane = t.pane(); // one keystroke, one undo step — even when it edited at ten cursors. if (p.multi_on and !p.multi_first) return; + // a prompt's answer is typed once and gone; it keeps no history + if (t.what != .body) return; + const pane = t.pane(); if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { + if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); panes.Terminal.undo(p, pane); } pub fn doRedo(p: *Pardes, t: *Text) void { + if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); diff --git a/src/exec.zig b/src/exec.zig index 0a9d6f31..a2dbac7c 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -219,12 +219,8 @@ pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { /// Enter on a save input: the path is everything past the marker. pub fn submitSave(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - const at = switch (pane.prompt) { - .save => |a| a, - else => return, - }; - const armed = pane.tag_tail[at..pane.tag_tail_len]; - pane.tag_tail_len = at; // drop the prompt back to the seeded tail + if (pane.prompt != .save) return; + const armed = pane.promptText() orelse return; if (!std.mem.startsWith(u8, armed, config.save_marker)) return; const path = std.mem.trim(u8, armed[config.save_marker.len..], " \t\r\n"); if (path.len == 0) return; diff --git a/src/mouse.zig b/src/mouse.zig index a840c8fc..5f77634b 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -304,6 +304,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { { if (m.button == config.select_button) if (p.panes[p.active]) |pane| { if (pane.tag_edit) Pardes.exitTagEdit(pane); + pane.closePrompt(); }; var column: ?usize = null; var x: u16 = 0; @@ -439,6 +440,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const pane = p.panes[id] orelse return; if (id != p.active) if (p.panes[p.active]) |previous| { if (previous.tag_edit) Pardes.exitTagEdit(previous); + previous.closePrompt(); }; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; const body_y = p.bodyTop(r); @@ -449,12 +451,14 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } else if (mrow >= tag_y and mrow < tag_y + BOX_H) { if (mcol < r.x + TAG_TEXT_INSET) return; p.active = id; + pane.closePrompt(); p.enterTagEdit(pane, if (tagColumn(p, .pane, id, p.pointer_tag_hit, false)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, r.x + TAG_TEXT_INSET)); pane.tag_anchor = pane.tag_col; p.drag = .{ .tag = .{ .id = id } }; } else { p.active = id; if (pane.tag_edit) Pardes.exitTagEdit(pane); + pane.closePrompt(); const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; pane.clearPointerSelection(sel_slot); pane.sel[sel_slot] = pointed.sel; diff --git a/src/normal.zig b/src/normal.zig index 192fd933..a77f27a7 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -76,13 +76,8 @@ fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void { } pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { - const prompt_at = switch (pane.prompt) { - .search => |at| at, - else => return null, - }; - if (pane.nsel_snap == 0) return null; - const tail = pane.tagSlice(); - const armed = tail[@min(prompt_at, tail.len)..]; + if (pane.prompt != .search or pane.nsel_snap == 0) return null; + const armed = pane.input.own orelse ""; const split = std.mem.startsWith(u8, armed, config.split_marker); if (!split and !std.mem.startsWith(u8, armed, config.select_marker)) return null; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null; @@ -274,7 +269,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { } t.setRanges(text, rs[0..n], st[0..n], pri, after_expl); after.into(t); - t.pane().ensureCursorVisible(); // the view follows the PRIMARY, not the last pass + t.show(); // the view follows the PRIMARY, not the last pass } pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { diff --git a/src/panes.zig b/src/panes.zig index e6634583..c26065ca 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -59,12 +59,13 @@ pub const Pane = struct { const PdfSlot = if (Pdf.enabled) ?Pdf.State else void; + /// What an open prompt is asking. The answer is typed into `input`. pub const Prompt = union(enum) { none, - search: u16, - pipe: struct { at: u16, how: modal.Normal.PipeBehavior }, - /// Save on a scratch buffer or a terminal: the tail is a path to write to. - save: u16, + search, + pipe: modal.Normal.PipeBehavior, + /// Save on a scratch buffer or a terminal: the answer is a path to write to. + save, /// Del from the keyboard with open panes both above and below: which /// one takes the rows. Nothing is typed; one key answers. del_side, @@ -94,9 +95,11 @@ pub const Pane = struct { file: ?File.State = null, image: ?Image.State = null, pdf: PdfSlot = if (Pdf.enabled) null else {}, - /// Tag-tail input state. The tag text is presentation; this tag carries - /// which operation owns it and the tail offset restored on submit/cancel. prompt: Prompt = .none, + /// The answer to an open prompt: its marker and what is typed after it, + /// edited in insert mode and shown on the notice band. It is its own text + /// so a prompt never touches the tag. + input: Text = .{ .what = .input }, search_pane: ?usize = null, search_row: ?usize = null, look_at: ?LookSpot = null, @@ -297,20 +300,23 @@ pub const Pane = struct { pub fn tagSlice(p: *const Pane) []const u8 { return p.tag_tail[0..p.tag_tail_len]; } - pub fn promptAt(p: *const Pane) ?u16 { - return switch (p.prompt) { - .none, .del_side => null, - .search, .save => |at| at, - .pipe => |pipe| pipe.at, - }; + /// Close an open prompt, answered or not. Its answer goes with it, and an + /// s/S preview keeps whatever it last previewed. + pub fn closePrompt(pane: *Pane) void { + if (pane.input.own) |text| pane.gpa.free(text); + pane.input = .{ .what = .input }; + pane.prompt = .none; + pane.nsel_snap = 0; } /// What an open prompt shows on its notice band: the one answer every /// painter of the band reads. pub fn promptText(p: *const Pane) ?[]const u8 { - if (p.prompt == .del_side) return config.del_question; - const at = p.promptAt() orelse return null; - return p.tagSlice()[@min(at, p.tag_tail_len)..]; + return switch (p.prompt) { + .none => null, + .del_side => config.del_question, + else => p.input.own orelse "", + }; } pub fn appendTag(p: *Pane, text: []const u8) bool { diff --git a/src/pardes.zig b/src/pardes.zig index 15b2c49b..a29973e7 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1824,10 +1824,10 @@ test "Save on a scratch asks for a path in its inherited dir and makes it a file // Save on a scratch arms a PATH input, prefilled with the inherited dir try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(np.prompt == .save); - try std.testing.expect(std.mem.endsWith(u8, np.tagSlice(), " Save /tmp/pardes-save-dir/")); + try std.testing.expectEqualStrings(" Save /tmp/pardes-save-dir/", np.promptText().?); // typing the filename and submitting converts it into an ordinary file - try std.testing.expect(np.appendTag("note.txt")); + edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" }); exec.submitSave(p, id); try std.testing.expect(np.file.?.output == null); try std.testing.expectEqualStrings("/tmp/pardes-save-dir/note.txt", np.file.?.path); @@ -1852,7 +1852,7 @@ test "Save on a terminal writes its plaintext scrollback and stays a terminal" { try std.testing.expect(p.executeBuiltinLine(0, "Save")); try std.testing.expect(pane.prompt == .save); - try std.testing.expect(pane.appendTag("log.txt")); + edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" }); exec.submitSave(p, 0); // the pane is untouched: still a terminal, no file behind it @@ -1901,7 +1901,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(out)); try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(out.prompt == .save); - try std.testing.expect(out.appendTag("help.txt")); + edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); exec.submitSave(p, id); // the buffer itself is untouched: same origin, same name, still refillable @@ -4109,6 +4109,7 @@ pub const Pardes = struct { if (comptime pdf_enabled) if (pane.pdf) |*pv| panes.Pdf.deinitPane(p, pane, pv); if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); + if (pane.input.own) |text| p.gpa.free(text); for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); @@ -4836,7 +4837,7 @@ pub const Pardes = struct { } pub fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void { - if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; + if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len); p.seedTail(pane); if (!pane.tag_init) return; @@ -4869,7 +4870,7 @@ pub const Pardes = struct { } pub fn exitTagEdit(pane: *Pane) void { - if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; + if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; if (pane.isTerminal()) { if (pane.tag_edit) pane.body.mode = pane.tag_mode; } else pane.body.mode = .normal; @@ -4877,8 +4878,6 @@ pub const Pardes = struct { pane.tag_sel = false; pane.tag_name_len = null; pane.tag_scroll = 0; - pane.prompt = .none; // an abandoned prompt stays as tag text - pane.nsel_snap = 0; // ...and its s/S preview keeps whatever it previewed } pub fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } { @@ -5273,6 +5272,7 @@ pub const Pardes = struct { p.active = id; p.exitHeader(); if (pane.tag_edit) exitTagEdit(pane); + pane.closePrompt(); pane.body.mode = previous; switch (previous) { .tty => { @@ -5294,6 +5294,7 @@ pub const Pardes = struct { p.active = id; p.exitHeader(); if (pane.tag_edit) exitTagEdit(pane); + pane.closePrompt(); if (pane.body.mode == .tty) { pane.body.mode = .normal; pane.body.normal.clear(); @@ -5351,7 +5352,7 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - if (hit(key, config.window_prefix) and pane.body.mode != .insert) { + if (hit(key, config.window_prefix) and pane.body.mode != .insert and pane.prompt == .none) { p.ctrl_w_pending = true; return; } @@ -5384,34 +5385,29 @@ pub const Pardes = struct { if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } - if (pane.prompt != .none and (hit(key, config.search_submit) or hit(key, config.escape))) { - const submit = hit(key, config.search_submit); - switch (pane.prompt) { - .pipe => |pipe| { - if (submit) Pipe.submitPipe(p, p.active); - pane.tag_tail_len = @min(pipe.at, pane.tag_tail_len); - }, - .save => |at| { - if (submit) exec.submitSave(p, p.active) else pane.tag_tail_len = @min(at, pane.tag_tail_len); - }, - .search => |at| { - if (submit) + if (pane.prompt != .none) { + if (hit(key, config.search_submit) or hit(key, config.escape)) { + const submit = hit(key, config.search_submit); + switch (pane.prompt) { + .pipe => if (submit) Pipe.submitPipe(p, p.active), + .save => if (submit) exec.submitSave(p, p.active), + .search => if (submit) look.submitSearch(p, p.active) else if (normal.selRegexArmed(pane)) |_| - normal.applySelRegex(p, pane, "", false); - pane.tag_tail_len = @min(at, pane.tag_tail_len); - }, - .none, .del_side => unreachable, + normal.applySelRegex(p, pane, "", false), + .none, .del_side => unreachable, + } + pane.closePrompt(); + pane.body.mode = .normal; + pane.body.normal.clear(); + return; } - exitTagEdit(pane); - pane.body.mode = .normal; - pane.body.normal.clear(); + edit.handleInsert(p, &pane.input, key); + if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } if (pane.tag_edit) { if (pane.body.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); - const pn = p.panes[p.active] orelse return; - if (normal.selRegexArmed(pn)) |a| normal.applySelRegex(p, pn, a.pat, a.split); return; } if (pane.body.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { @@ -5506,33 +5502,24 @@ pub const Pardes = struct { break :pipe Pipe.pipeMarker(how); }, }; - p.seedTail(pane); - if (!pane.tag_init) return; + // Save asks for a path, so its answer starts out as the pane's own + // directory for the name to be typed onto. const dir = if (request == .save) paneDir(pane) else ""; - const slash = request == .save and (dir.len == 0 or dir[dir.len - 1] != '/'); - var room = pane.tag_tail.len - pane.tag_tail_len; - if (marker.len > room) return; - room -= marker.len; - if (dir.len > room) return; - room -= dir.len; - if (slash and room == 0) return; - const prefix_len = (p.tagPrefix(pane) catch return).len; - const prompt_at: u16 = @intCast(pane.tag_tail_len); - _ = pane.appendTag(marker); - if (request == .save) { - _ = pane.appendTag(dir); - if (slash) _ = pane.appendTag("/"); - } + const slash: []const u8 = if (request == .save and (dir.len == 0 or dir[dir.len - 1] != '/')) "/" else ""; + const answer = std.mem.concat(p.gpa, u8, &.{ marker, dir, slash }) catch return; + if (pane.tag_edit) exitTagEdit(pane); + // Not closePrompt: an s/S snapshot was taken for this very prompt. + if (pane.input.own) |old| p.gpa.free(old); pane.prompt = switch (request) { - .search => .{ .search = prompt_at }, - .pipe => |how| .{ .pipe = .{ .at = prompt_at, .how = how } }, - .save => .{ .save = prompt_at }, + .search => .search, + .pipe => |how| .{ .pipe = how }, + .save => .save, }; - pane.tag_edit = true; - pane.tag_sel = false; - pane.body.mode = .insert; + pane.input = .{ .what = .input, .own = answer, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(answer.len) }; + // Whatever mode the body was in, it is in normal mode once the + // prompt is answered or dropped. + pane.body.mode = .normal; pane.body.normal.clear(); - pane.tag_col = @intCast(prefix_len + pane.tag_tail_len); } pub const SavePath = Effect.Buf(effect_path_cap); @@ -6066,7 +6053,7 @@ pub const Pardes = struct { p.trackJump(); for (&p.panes, 0..) |*slot, id| { const pane = slot.* orelse continue; - if (pane.tag_edit and pane.prompt == .none and (id != p.active or p.topbar_col != null)) + if (pane.tag_edit and (id != p.active or p.topbar_col != null)) exitTagEdit(pane); if (comptime terminal_panes) if (pane.terminal) |state| { var off: u16 = 0; @@ -6279,18 +6266,14 @@ pub const Pardes = struct { // the detached wire will encode -- which drops every frame for // as long as the prompt is up. const printed = Messages.printRight(s, cx, row, chip -| 1, text, style); - if (kind != .prompt or id != p.active) continue; - const at = pane.promptAt() orelse continue; - const prompt0 = (p.tagPrefix(pane) catch continue).len + at; - const col = @as(usize, pane.tag_col); - if (col < prompt0) continue; + if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; // The cursor follows the text to wherever it landed; a caret // in the part a narrow band dropped has nowhere to be. - const prompt_col = panes.File.displayWidth(text[0..@min(col - prompt0, text.len)]); + const prompt_col = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); if (prompt_col < printed.dropped) continue; const caret = printed.left + (prompt_col - printed.dropped); if (caret < tx + tw) - s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.body.mode == .insert }; + s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.input.mode == .insert }; } } @@ -6652,7 +6635,7 @@ pub const Pardes = struct { layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = if (p.settings.tag_bottom) r.y + r.h - BOX_H else r.y, .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; layer.cols = columns; layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - layer.cursor = if (p.topbar_col == null and pane.promptAt() == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; + layer.cursor = if (p.topbar_col == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; } var text_buf: [1200]u8 = undefined; // With the workspace tag row handed to native chrome there is no @@ -6711,14 +6694,11 @@ pub const Pardes = struct { p.surface.tag_layers[layer_index].fade = fade; // The caret rides the band, where the prompt's glyphs are, // at the same place in the text the grid pass puts it. - if (kind != .prompt or id != p.active) continue; - const at = pane.promptAt() orelse continue; - const prompt0 = (p.tagPrefix(pane) catch continue).len + at; - if (pane.tag_col < prompt0) continue; - const typed = panes.File.displayWidth(text[0..@min(pane.tag_col - prompt0, text.len)]); + if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; + const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); const dropped = shown - panes.File.displayWidth(kept); if (typed < dropped) continue; - p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.body.mode == .insert }; + p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.input.mode == .insert }; } } if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { @@ -6877,8 +6857,7 @@ pub const Pardes = struct { .font_role = .tagline, }); const tag = try p.tagText(arena, pane); - const prompt_at = pane.promptAt(); - if (active and pane.tag_edit and prompt_at == null) { + if (active and pane.tag_edit) { const caret = panes.File.rawDisplayCol(tag, pane.tag_col); var scroll: usize = pane.tag_scroll; if (caret < scroll) scroll = caret; @@ -6890,16 +6869,12 @@ pub const Pardes = struct { scroll = panes.File.rawDisplayCol(tag, raw); } pane.tag_scroll = @intCast(scroll); - } else if (!pane.tag_edit or prompt_at != null) pane.tag_scroll = 0; - const tag_cut = if (prompt_at) |at| - @min(tag.len, tag.len - @min(tag.len, pane.tag_tail_len) + at) - else - tag.len; - const tag_start = @min(tag_cut, panes.File.rawAtDisplay(tag, pane.tag_scroll)); - _ = s.print(tx, tag_y, tw, tag[tag_start..tag_cut], tag_style); + } else pane.tag_scroll = 0; + const tag_start = panes.File.rawAtDisplay(tag, pane.tag_scroll); + _ = s.print(tx, tag_y, tw, tag[tag_start..], tag_style); if (tagTintRange(pane, tag, tag.len - curTail(pane).len)) |name| { const lo = @max(name.lo, tag_start); - const hi = @min(name.hi, tag_cut); + const hi = @min(name.hi, tag.len); if (lo < hi) { var col = panes.File.rawDisplayCol(tag, lo) -| pane.tag_scroll; const end = panes.File.rawDisplayCol(tag, hi) -| pane.tag_scroll; @@ -7204,6 +7179,43 @@ test "a prompt chip is a band with its caret, still on the grid, and only the ch for (pane.sel) |selection| try std.testing.expect(selection.state == .none); } +test "a prompt is typed on its own line in the notice band and leaves the tag row alone" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile("one two\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); + defer std.testing.allocator.free(tag_before); + + p.update(.{ .key = .{ .cp = '/' } }); + p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); + p.update(.{ .key = .{ .cp = Key.left } }); + try std.testing.expect(pane.prompt == .search and !pane.tag_edit); + try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + // The tagline is exactly what it was: nothing of the prompt is in it. + try std.testing.expectEqual(tag_before.len, p.surface.tag_layers[0].cells.len); + for (tag_before, p.surface.tag_layers[0].cells) |was, is| try std.testing.expect(was.visuallyEqual(&is)); + try std.testing.expect(p.surface.tag_layers[0].cursor == null); + // The band carries the answer and the caret, one cell back from its end. + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.cols != 0 and layer.kind == .notice) break layer; + } else return error.NoPromptBand; + const caret = band.cursor orelse return error.MissingBandCaret; + try std.testing.expectEqualStrings("t", band.cells[caret.col - 1].grapheme()); + try std.testing.expectEqualStrings("w", band.cells[caret.col].grapheme()); + const grid = p.surface.cursor orelse return error.MissingPromptCursor; + try std.testing.expectEqual(p.bodyTop(p.rects[0]), grid.y); + + // Submitting searches for what was typed and gives the prompt its line back. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(pane.prompt == .none and pane.input.own == null); +} + test "a stillborn pane gives its column to the first pane that joins it" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); diff --git a/test/panes.zig b/test/panes.zig index 4c969ab5..f1adafee 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1353,8 +1353,9 @@ test "paste into pane commands and prompts never inserts into the body" { try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .search = config.search_marker }); - p.update(.{ .paste = "two" }); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), "two")); + p.update(.{ .paste = "t\r\nwo" }); + try std.testing.expectEqualStrings(config.search_marker ++ "two", pane.promptText().?); + try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); try std.testing.expectEqualStrings("one two one\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); @@ -1646,7 +1647,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv try std.testing.expectEqualStrings("kept edit", pane.ovl.?.text); } -test "tag prompt entry and cancellation preserve exact text and cursor state" { +test "a prompt's entry and cancellation leave the tag, the body and its cursor as they were" { const Case = struct { key: ?Key = null, save: bool = false, marker: []const u8 }; const cases = [_]Case{ .{ .marker = config.search_marker }, @@ -1665,8 +1666,6 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { @memcpy(pane.tag_tail[0..tail.len], tail); pane.tag_tail_len = tail.len; pane.tag_init = true; - pane.tag_sel = true; - pane.tag_col = 1; pane.body.cur_row = 1; pane.body.cur_col = 2; pane.body.cur_pinned = true; @@ -1677,16 +1676,16 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { } else { p.startPrompt(pane, .{ .search = config.search_marker }); } - try std.testing.expect(pane.tag_edit); - try std.testing.expect(!pane.tag_sel); - try std.testing.expectEqual(.insert, pane.body.mode); + // The answer is typed into the prompt's own line, never the tag. + try std.testing.expect(!pane.tag_edit); + try std.testing.expectEqual(.insert, pane.input.mode); + try std.testing.expectEqualStrings(case.marker, pane.promptText().?); + try std.testing.expectEqual(@as(i32, @intCast(case.marker.len)), pane.input.cur_col); + try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); try std.testing.expectEqualDeep(modal.Normal.State{}, pane.body.normal); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..tail.len]); - try std.testing.expectEqualStrings(case.marker, pane.tag_tail[tail.len..pane.tag_tail_len]); - try std.testing.expectEqual(pane.file.?.path.len + pane.tag_tail_len, pane.tag_col); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.input.own == null); try std.testing.expectEqual(.normal, pane.body.mode); try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -1695,28 +1694,23 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { } } -test "tag prompt capacity refusal leaves the existing tail and input state untouched" { +test "a prompt opens whatever the tag already holds" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); @memset(&pane.tag_tail, 'x'); - pane.tag_tail_len = pane.tag_tail.len - 1; + pane.tag_tail_len = pane.tag_tail.len; pane.tag_init = true; - pane.tag_col = 17; - pane.tag_sel = true; for (0..3) |case| { switch (case) { 0 => p.startPrompt(pane, .{ .search = config.search_marker }), 1 => p.startPrompt(pane, .save), else => p.update(.{ .key = .{ .cp = '|' } }), } - try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_edit); - try std.testing.expect(pane.tag_sel); - try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqual(@as(u16, 17), pane.tag_col); - try std.testing.expectEqual(pane.tag_tail.len - 1, pane.tag_tail_len); + try std.testing.expect(pane.prompt != .none); + try std.testing.expectEqual(pane.tag_tail.len, pane.tag_tail_len); for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); + p.update(.{ .key = .{ .cp = Key.escape } }); } } @@ -1735,7 +1729,7 @@ test "generated output refuses every pipe prompt before seeding the tag" { } } -test "tag prompt owns the pipe behavior through cancellation and submission" { +test "a prompt owns the pipe behavior through cancellation and submission" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\n"); @@ -1746,7 +1740,7 @@ test "tag prompt owns the pipe behavior through cancellation and submission" { p.startPrompt(pane, .{ .pipe = .append }); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .pipe = how }); - try std.testing.expectEqual(how, pane.prompt.pipe.how); + try std.testing.expectEqual(how, pane.prompt.pipe); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const pending = p.pipe.wait orelse return error.MissingPipe; @@ -1758,7 +1752,7 @@ test "tag prompt owns the pipe behavior through cancellation and submission" { } } -test "tag prompt cancellation restores the selection before regex previews" { +test "prompt cancellation restores the selection before regex previews" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one two one"); @@ -1786,133 +1780,57 @@ test "tag prompt cancellation restores the selection before regex previews" { } } -test "tag prompt prefix allocation failure preserves an already seeded prompt" { +test "a prompt that cannot be opened leaves the open one as it was" { const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[2].type.?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); - const tail = " keep /prior"; - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; - pane.prompt = .{ .search = 5 }; - pane.tag_edit = true; - pane.tag_sel = true; - pane.tag_col = 14; - pane.tag_anchor = 7; + p.startPrompt(pane, .{ .search = config.search_marker }); + p.update(.{ .key = .{ .cp = 'p', .text = "prior" } }); pane.body.normal = .{ .count = 9, .prefix = .goto }; - const previous_prompt = pane.prompt; const previous_normal = pane.body.normal; _ = p.scratch.reset(.free_all); failing.fail_index = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualDeep(previous_prompt, pane.prompt); + try std.testing.expect(pane.prompt == .search); + try std.testing.expectEqualStrings(config.search_marker ++ "prior", pane.promptText().?); try std.testing.expectEqualDeep(previous_normal, pane.body.normal); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); - try std.testing.expect(pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqual(@as(u16, 14), pane.tag_col); - try std.testing.expectEqual(@as(u16, 7), pane.tag_anchor); + try std.testing.expect(!pane.tag_init and !pane.tag_edit); } } -test "tag prompt Save requires room for its complete directory prefix" { +test "Save's prompt starts from the pane's directory" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); for ([_][]const u8{ "/dír space", "/dír space/", "" }) |dir| { try pane.setOwnedCwd(dir); - const slash: usize = @intFromBool(dir.len == 0 or dir[dir.len - 1] != '/'); - const needed = config.save_marker.len + dir.len + slash; - for ([_]usize{ 1, 0 }) |shortfall| { - @memset(&pane.tag_tail, 'x'); - pane.tag_tail_len = pane.tag_tail.len - needed + shortfall; - pane.tag_init = true; - pane.tag_edit = false; - pane.tag_sel = true; - pane.tag_col = 17; - const start = pane.tag_tail_len; - p.startPrompt(pane, .save); - if (shortfall != 0) { - try std.testing.expect(pane.prompt == .none); - try std.testing.expectEqual(start, pane.tag_tail_len); - try std.testing.expect(!pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(@as(u16, 17), pane.tag_col); - for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); - } else { - try std.testing.expect(pane.prompt == .save); - try std.testing.expectEqual(pane.tag_tail.len, pane.tag_tail_len); - try std.testing.expectEqualStrings(config.save_marker, pane.tag_tail[start..][0..config.save_marker.len]); - try std.testing.expectEqualStrings(dir, pane.tag_tail[start + config.save_marker.len ..][0..dir.len]); - try std.testing.expectEqual(@as(u8, '/'), pane.tag_tail[pane.tag_tail_len - 1]); - p.update(.{ .key = .{ .cp = Key.escape } }); - } - } + const slash = if (dir.len == 0 or dir[dir.len - 1] != '/') "/" else ""; + p.startPrompt(pane, .save); + try std.testing.expect(pane.prompt == .save); + const answer = pane.promptText().?; + try std.testing.expect(std.mem.startsWith(u8, answer, config.save_marker)); + try std.testing.expectEqualStrings(dir, answer[config.save_marker.len..][0..dir.len]); + try std.testing.expectEqualStrings(slash, answer[config.save_marker.len + dir.len ..]); + p.update(.{ .key = .{ .cp = Key.escape } }); } } -test "tag prompt successful seeded entry needs one scratch allocation" { +test "a prompt opens with one allocation" { const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[2].type.?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); - pane.tag_tail_len = 0; - pane.tag_init = true; _ = p.scratch.reset(.free_all); const before = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expectEqual(before + 1, failing.alloc_index); - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); - } -} - -test "tag prompt failure may initialize only the default tail" { - const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[2].type.?; - for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { - var saw_seeded_failure = false; - var succeeded = false; - for (0..16) |failure| { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("one\n"); - const path = try p.gpa.dupe(u8, "/" ++ "a" ** 2048 ++ ".zig"); - p.gpa.free(pane.file.?.path); - pane.file.?.path = path; - p.seedTail(pane); - try std.testing.expect(pane.tag_init); - const default_tail = pane.tag_tail; - const default_len = pane.tag_tail_len; - pane.tag_init = false; - pane.tag_tail_len = 0; - pane.tag_col = 17; - pane.tag_sel = true; - pane.body.normal = .{ .count = 9, .prefix = .goto }; - const previous_normal = pane.body.normal; - _ = p.scratch.reset(.free_all); - failing.fail_index = failing.alloc_index + failure; - p.startPrompt(pane, request); - if (!failing.has_induced_failure) { - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); - succeeded = true; - break; - } - try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqualDeep(previous_normal, pane.body.normal); - try std.testing.expectEqual(@as(u16, 17), pane.tag_col); - if (pane.tag_init) { - saw_seeded_failure = true; - try std.testing.expectEqualStrings(default_tail[0..default_len], pane.tag_tail[0..pane.tag_tail_len]); - } else try std.testing.expectEqual(@as(usize, 0), pane.tag_tail_len); - } - try std.testing.expect(succeeded and saw_seeded_failure); + try std.testing.expect(!pane.tag_edit and pane.input.mode == .insert); } } diff --git a/test/pdf.zig b/test/pdf.zig index 52fb62aa..5bc271d4 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1113,9 +1113,9 @@ test "PDF normal adapter consumes unsupported actions and navigates page fallbac p.update(.{ .key = .{ .cp = '!' } }); try std.testing.expect(!p.leader_on); p.update(.{ .key = .{ .cp = '/' } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.prompt == .search and !pane.tag_edit); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.prompt == .none); } test "Escape cancels PDF chrome in place and Shift-Escape leaves the pane" { diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 12dac242..b6b7b322 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -81,7 +81,6 @@ |4: |30: 1 gamma body Last == snap nomatch grid=120x41 cursor=7,39 -|2: /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del Find / |3: 1 Find |18: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del |19: 1 diff --git a/test/snapshots/find.snap b/test/snapshots/find.snap index fbd585f7..fe1ecad3 100644 --- a/test/snapshots/find.snap +++ b/test/snapshots/find.snap @@ -64,7 +64,8 @@ key enter stable 700 15000 snap back # executing the WORD Find (middle-click in a body) arms the same input — the -# enum IS the dispatch — and Esc abandons it, restoring the tag tail +# enum IS the dispatch — and Esc abandons it. The input is its own line, so an +# abandoned one leaves nothing behind in the tag press middle 8 4 release middle 8 4 stable 700 10000 diff --git a/test/snapshots/tagbottomshort.golden b/test/snapshots/tagbottomshort.golden index a5d53fe2..c11fe4ac 100644 --- a/test/snapshots/tagbottomshort.golden +++ b/test/snapshots/tagbottomshort.golden @@ -21,7 +21,7 @@ | New Tty Find Grep Joincol Delcol | 1 one /ZZ | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap tag-only grid=80x2 cursor=70,1 +== snap tag-only grid=80x2 cursor=79,1 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap regrown grid=80x11 cursor=79,2 diff --git a/test/snapshots/tagbottomshort.snap b/test/snapshots/tagbottomshort.snap index 2574df36..58da6a87 100644 --- a/test/snapshots/tagbottomshort.snap +++ b/test/snapshots/tagbottomshort.snap @@ -10,8 +10,8 @@ wait 8000 s.txt stable 700 20000 key space t b stable 700 15000 -# `/` with room to spare: the prompt is cut off the tagline (grid 9) and drawn -# on grid 8, the last body row, with the cursor. +# `/` with room to spare: the prompt is its own line, drawn on grid 8, the last +# body row, with the cursor; the tagline (grid 9) never holds any of it. key / send ZZ stable 600 8000 @@ -27,9 +27,8 @@ resize 4 80 stable 700 10000 snap one-body # the tagline alone. No body row, so nothing of the prompt is drawn anywhere — -# not over the tag, not on the row above the pane. The tagline itself is -# untouched: the marker sits after the builtins, so cutting the tail there -# leaves every column of it exactly as `tag-only` would look unarmed. +# not over the tag, not on the row above the pane, and its caret with it. The +# tagline itself is untouched, exactly as `tag-only` would look unarmed. resize 2 80 stable 700 10000 snap tag-only -- cgit v1.3 From 23f430573efe4f6ef55b0180aa0d742ff4eca1d9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:01:57 -0300 Subject: Make a pane's tag a Text edited with the body's own keys The tag was a fixed buffer with its own one-line editor, a cursor measured across the path, and a hijack of the body's mode while it was typed into. It is now the pane's second Text: its own characters after the computed prefix (path, dirty marker, PDF page), which is never stored in it, so a rename or a dirty marker never moves its cursor. Normal and insert mode are the body's, undo included; `:` moves the keyboard between body and tag, the tag remembers its cursor and starts on Save, and executing a word from it hands the keyboard back. The mouse still sees the prefix: a sweep selects across it and a click on the path drafts a new name. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 2 +- src/Pipe.zig | 6 +- src/Terminal.zig | 63 +--- src/Text.zig | 79 ++++- src/body_layer.zig | 5 +- src/colors.zig | 2 +- src/dump.zig | 2 +- src/edit.zig | 41 ++- src/exec.zig | 7 +- src/look.zig | 3 +- src/mouse.zig | 82 ++++-- src/ninep/pane.zig | 44 ++- src/normal.zig | 20 +- src/panes.zig | 66 ++--- src/pardes.zig | 639 +++++++++++++++++------------------------ test/mode.zig | 31 +- test/panes.zig | 384 +++++++++++++------------ test/pdf.zig | 23 +- test/snapshots/cmdword.golden | 4 +- test/snapshots/cmdword.snap | 24 +- test/snapshots/collapse.golden | 4 +- test/snapshots/collapse.snap | 7 +- test/snapshots/tag.snap | 20 +- test/snapshots/tagalign.snap | 9 +- test/snapshots/tagcmd.snap | 20 +- test/snapshots/tagnav.golden | 43 +-- test/snapshots/tagnav.snap | 136 +++------ test/snapshots/tagpath.golden | 23 +- test/snapshots/tagpath.snap | 28 +- test/snapshots/ttyclick.golden | 4 - test/snapshots/ttyclick.snap | 14 +- 31 files changed, 856 insertions(+), 979 deletions(-) (limited to 'src/Text.zig') diff --git a/src/File.zig b/src/File.zig index bf4bf08c..2bf9f57d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1129,7 +1129,7 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; - const typing_body = !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side); + const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) const body_y = p.bodyTop(r); diff --git a/src/Pipe.zig b/src/Pipe.zig index 3e6752a8..4cabfd88 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -294,12 +294,12 @@ test "selection pipe prompt submits exact request and Escape cancels" { pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(!pane.tag_edit and pane.prompt == .pipe); + try std.testing.expect(pane.focus == .body and pane.prompt == .pipe); try std.testing.expectEqualStrings(config.pipe_marker, pane.promptText().?); try std.testing.expect(nextPipeEffect(p) == null); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe and pane.input.own == null); + try std.testing.expect(pane.focus == .body and pane.prompt != .pipe and pane.input.own == null); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); @@ -311,7 +311,7 @@ test "selection pipe prompt submits exact request and Escape cancels" { p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); + try std.testing.expect(pane.focus == .body and pane.prompt != .pipe); try std.testing.expectEqualSlices(u8, before, pane.file.?.content); try std.testing.expect(nextPipeEffect(p) == null); } diff --git a/src/Terminal.zig b/src/Terminal.zig index fbe7bfc0..7b5af696 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -686,8 +686,7 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { const at_bottom = atBottom(pane); if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); p.shell_rows.markStale(pane); - const body_mode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; - if (body_mode == .tty and at_bottom) followOutput(pane); + if (pane.body.mode == .tty and at_bottom) followOutput(pane); } const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; @@ -2463,64 +2462,22 @@ pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { while (i < pad) : (i += 1) p.emitWrite(id, "\r"); } -/// the snapshot takes ownership of a COPY of the edit buffer's text -pub fn snap(p: *Pardes, pane: *Pane) ?Snapshot { - var ovl: ?EditBuffer = null; - if (pane.ovl) |o| ovl = .{ .row = o.row, .rows = o.rows, .text = p.gpa.dupe(u8, o.text) catch return null }; - return .{ .ovl = ovl, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel }; -} - -/// undo/redo restores the selection recorded with the snapshot (helix -/// keeps selections in its history transactions) -pub fn restoreSnap(p: *Pardes, pane: *Pane, s: Snapshot) void { - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = s.ovl; - pane.body.cur_row = s.cur_row; - pane.body.cur_col = s.cur_col; - pane.body.cur_pinned = true; - pane.body.vsel = s.vsel; - pane.body.msel.active = false; - pane.ensureCursorVisible(); -} - -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; -} - pub fn pushUndo(p: *Pardes, pane: *Pane) void { - const current = pane.ovl orelse EditBuffer{ .rows = 0 }; - if (pane.body.ed_undo_len > 0) { - const top = pane.body.ed_undo[pane.body.ed_undo_len - 1]; - const same = if (top.ovl) |overlay| pane.ovl != null and overlay.row == current.row and - overlay.rows == current.rows and std.mem.eql(u8, overlay.text, current.text) else pane.ovl == null; - if (same) return; - } - const value = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.body.ed_undo, &pane.body.ed_undo_len, value); - for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |item| if (item.ovl) |overlay| p.gpa.free(overlay.text); - pane.body.ed_redo_len = 0; + pane.body.remember(p.gpa, pane.ovl); } pub fn undo(p: *Pardes, pane: *Pane) void { - if (pane.body.ed_undo_len == 0) return; - const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.body.ed_redo, &pane.body.ed_redo_len, current); - pane.body.ed_undo_len -= 1; - restoreSnap(p, pane, pane.body.ed_undo[pane.body.ed_undo_len]); + const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = back_to.ovl; + pane.ensureCursorVisible(); } pub fn redo(p: *Pardes, pane: *Pane) void { - if (pane.body.ed_redo_len == 0) return; - const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.body.ed_undo, &pane.body.ed_undo_len, current); - pane.body.ed_redo_len -= 1; - restoreSnap(p, pane, pane.body.ed_redo[pane.body.ed_redo_len]); + const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = forward_to.ovl; + pane.ensureCursorVisible(); } pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { diff --git a/src/Text.zig b/src/Text.zig index aaa6dc88..3e48a42e 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -1,11 +1,11 @@ //! 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, and so is the answer typed into a -//! pane's prompt. 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. +//! an edit buffer. A pane's body is one, its tag is another, and so is the +//! answer typed into a pane's prompt. 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"); @@ -19,7 +19,7 @@ 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, input }; +pub const What = enum { body, tag, input }; /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. pub const LineSel = struct { @@ -49,7 +49,8 @@ pub const SelRange = struct { what: What = .body, /// The characters of a text that holds its own (gpa-owned): everything but -/// a body, which reads its pane's. +/// 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, @@ -77,12 +78,14 @@ ed_redo_len: usize = 0, 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)), }; } /// Bring the cursor into view (acme's textshow). Only a body scrolls to it; -/// a prompt's answer is drawn whole. +/// 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) t.pane().ensureCursorVisible(); } @@ -273,8 +276,8 @@ pub fn multiSelAction(t: *Text, text: []const u8, kind: modal.Normal.Multi, cnt: return setRanges(t, text, out[0..m], &.{}, @min(got.pri, m - 1), expl); } if (kind == .rotate_forward or kind == .rotate_backward) { - const step = cnt % n; - const pri = if (kind == .rotate_forward) (got.pri + step) % n else (got.pri + (n - step)) % n; + const turn = cnt % n; + const pri = if (kind == .rotate_forward) (got.pri + turn) % n else (got.pri + (n - turn)) % n; return setRanges(t, text, rs[0..n], &.{}, pri, expl); } if (kind == .merge) { @@ -510,6 +513,8 @@ pub fn visualMove( /// Ctrl-d/u: scroll half a page AND move the cursor by the same rows pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bool) void { + // a view to move through is a body's; a tag or an answer is all shown + if (t.what != .body) return; const half: i32 = @max(1, @divTrunc(@as(i32, t.pane().rows), 2)); t.pane().scrollBy(if (down) half else -half); verticalMove(t, text, range, down, @intCast(half)); @@ -518,6 +523,8 @@ pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bo /// 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 margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); t.pane().scrollBy(delta); const top = t.pane().scroll(); @@ -540,6 +547,8 @@ pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: /// gt/gc/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) pub fn gotoWindow(t: *Text, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { + // a view to move through is a body's; a tag or an answer is all shown + if (t.what != .body) return; const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); const top = t.pane().scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); @@ -623,3 +632,51 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.msel.active = false; t.show(); } + +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) 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 = gpa.dupe(u8, now.text) catch return } 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) ?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 = gpa.dupe(u8, now.text) catch return null } 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; + t.msel.active = false; + return back_to; +} diff --git a/src/body_layer.zig b/src/body_layer.zig index 1f210220..e85e10f1 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -363,6 +363,9 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id for (pane.sel, 0..) |sl, b| { if (sl.state == .none) continue; if (sl.state == .done and b != 0) continue; + // A select sweep over the tag is the tag's selection, painted there + // in the tag's own selection colours. + if (b == pardes.sel_slot and @min(sl.r0, sl.r1) < BOX_H) continue; paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); } // modal line selection (helix `x`): whole body rows, normal mode only @@ -461,7 +464,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // cursor: tracks the shell cursor until pinned by a click or a key // (the tag's or a prompt's cursor wins while that is being typed into) - if (active and !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side)) { + if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side)) { if (pane.body.mode != .tty) { const cur = panes.Terminal.gridCursor(pane); const goff = panes.Terminal.gridOffset(pane); diff --git a/src/colors.zig b/src/colors.zig index 741187c6..f92f67b1 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -602,7 +602,7 @@ test "line numbers stay quiet without a current-line tag background" { const moved = try p.render(p.scratch.allocator()); try std.testing.expect(!moved.at(x, y).style.bold); try std.testing.expect(moved.at(x, y + 1).style.bold); - p.enterTagEdit(pane, -1); + p.enterTag(pane); const tag_edit = try p.render(p.scratch.allocator()); try std.testing.expect(!tag_edit.at(x, y + 1).style.bold); } diff --git a/src/dump.zig b/src/dump.zig index 2fb9ce80..7112e1f0 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -621,7 +621,7 @@ pub fn dumpState(p: *Pardes) !void { try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) else try pardes.panes.Terminal.dumpPane(pane, arena, tag, body, scroll); - dp.tag_tail = if (pane.tag_init) pane.tagSlice() else null; + dp.tag_tail = pane.tag.own; dump_panes[panes_len] = dp; panes_len += 1; } diff --git a/src/edit.zig b/src/edit.zig index 5249a64c..02e138e8 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -96,18 +96,12 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - if (pane.tag_edit) { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const range: @TypeOf(Pardes.tagSelBounds(pane)) = if (pane.tag_sel) Pardes.tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; - const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; - _ = p.replaceTagText(pane, range.lo, hi, bytes); - return; - } - if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); + const t = if (pane.focus == .tag) &pane.tag else &pane.body; + if (t.what == .body and pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); switch (if (req) |r| r.mode else .after) { - .after => pasteText(p, &pane.body, bytes, false, 1), - .before => pasteText(p, &pane.body, bytes, true, 1), - .replace => replaceWithText(p, &pane.body, bytes), + .after => pasteText(p, t, bytes, false, 1), + .before => pasteText(p, t, bytes, true, 1), + .replace => replaceWithText(p, t, bytes), } } @@ -301,7 +295,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { const arena = p.scratch.allocator(); if (t.what != .body) { - const text = t.own orelse ""; + const text = try flatSurface(p, t); const lines = try arena.alloc([]const u8, std.mem.count(u8, text, "\n") + 1); var it = std.mem.splitScalar(u8, text, '\n'); for (lines) |*line| line.* = it.next().?; @@ -346,6 +340,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { } pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { + if (t.what == .tag) return Pardes.curTail(t.pane()); if (t.what != .body) return t.own orelse ""; const pane = t.pane(); if (pane.file) |f| return f.content; @@ -367,6 +362,10 @@ pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { /// Route shared edit operations to the characters `t` edits: its own, or /// for a body its file's content or its terminal's overlay. fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { + // A tag nobody has changed shows its default; the first edit makes that + // default its own text. + if (t.what == .tag and t.own == null) + t.own = p.gpa.dupe(u8, Pardes.defaultTail(t.pane())) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; @@ -1544,14 +1543,19 @@ pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) void { pub fn pushUndo(p: *Pardes, t: *Text) void { // one keystroke, one undo step — even when it edited at ten cursors. if (p.multi_on and !p.multi_first) return; - // a prompt's answer is typed once and gone; it keeps no history - if (t.what != .body) return; + switch (t.what) { + .body => {}, + .tag => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), + // a prompt's answer is typed once and gone; it keeps no history + .input => return, + } const pane = t.pane(); if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { + if (t.what == .tag) return stepOwn(p, t, true); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); @@ -1559,12 +1563,21 @@ pub fn doUndo(p: *Pardes, t: *Text) void { } pub fn doRedo(p: *Pardes, t: *Text) void { + if (t.what == .tag) return stepOwn(p, t, false); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); } +/// Undo or redo an edit of a text's own characters; stepping back past its +/// first edit gives a tag its default again. +fn stepOwn(p: *Pardes, t: *Text, back: bool) void { + const to = t.step(p.gpa, if (t.own) |own| .{ .text = own } else null, back) orelse return; + if (t.own) |own| p.gpa.free(own); + t.own = if (to.ovl) |buffer| buffer.text else null; +} + const PointerTextSelection = struct { sel: Pane.Sel, on_tag: bool, diff --git a/src/exec.zig b/src/exec.zig index a2dbac7c..82b3da4a 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -260,8 +260,9 @@ pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void { f.output = null; // an ordinary file pane from here on f.watch_after_save = true; pane.clearCwd(); - pane.tag_init = false; // re-derive the tag as a plain file - pane.tag_tail_len = 0; + // re-derive the tag as a plain file's + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); return; } @@ -351,7 +352,7 @@ pub fn replaceStillborn(p: *Pardes) void { const out = file.output orelse return; if (out.from != .cmd or out.from.cmd != .New) return; if (file.revision != 0 or file.content.len != 0) return; - if (old.tag_init and !std.mem.eql(u8, old.tagSlice(), Pardes.defaultTail(old))) return; + if (old.tag.own) |own| if (!std.mem.eql(u8, own, Pardes.defaultTail(old))) return; const was_active = p.active == old_id; layout.compute(p); // the joiner may have no rect yet; absorb snaps to rows p.removePane(old_id, new_id) catch |err| return p.reportError(old_id, "close", err); diff --git a/src/look.zig b/src/look.zig index efc3f312..6f9f8c6a 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1150,8 +1150,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const found = resolveLookTarget(p, id, txt, &realbuf); switch (found) { .none => { - const bmode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; - if (pane.image != null or bmode == .tty) return; + if (pane.image != null or pane.body.mode == .tty) return; runSearch(p, id, trimmed, .text, .cursor) catch |err| { p.reportError(id, "search", err); return; diff --git a/src/mouse.zig b/src/mouse.zig index 5f77634b..ae047c58 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -39,7 +39,6 @@ pub const Drag = union(enum) { /// `grab`: how far into the grip it was pressed, so the column's left /// edge lands at `cur_x - grab`. A release still on the grip moves nothing. column_move: struct { serial: u32, cur_x: u16, grab: u16 = 0 }, - tag: struct { id: usize }, /// chorded: a 1-2/1-3 cut/paste chord fired during this left drag — /// the drag's own release is then inert select: struct { @@ -55,7 +54,7 @@ pub const Drag = union(enum) { fn button(drag: Drag) ?Mouse.Button { return switch (drag) { .none => null, - .border_v, .border_h, .move, .column_move, .tag => config.select_button, + .border_v, .border_h, .move, .column_move => config.select_button, .select => |selection| selection.button, }; } @@ -228,7 +227,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const previous_tag_hit = p.pointer_tag_hit; p.pointer_tag_hit = if (m.tag_hit) |point| p.reprojectTagHit(point) else null; if (m.tag_hit != null and p.pointer_tag_hit == null and m.kind == .press) return; - if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { + if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (p.drag == .select or p.header_drag)) { if (previous_tag_hit) |previous| { var continued = previous; continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); @@ -236,7 +235,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { p.pointer_tag_hit = continued; } } - if ((m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { + if ((m.kind == .drag or m.kind == .release) and (p.drag == .select or p.header_drag)) { if (previous_tag_hit) |previous| if (p.pointer_tag_hit) |*current| { current.kind = previous.kind; current.id = previous.id; @@ -303,7 +302,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { (m.button == config.select_button or m.button == config.exec_button or m.button == config.look_button)) { if (m.button == config.select_button) if (p.panes[p.active]) |pane| { - if (pane.tag_edit) Pardes.exitTagEdit(pane); + pane.focus = .body; pane.closePrompt(); }; var column: ?usize = null; @@ -439,7 +438,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const r = p.rects[id]; const pane = p.panes[id] orelse return; if (id != p.active) if (p.panes[p.active]) |previous| { - if (previous.tag_edit) Pardes.exitTagEdit(previous); + previous.focus = .body; previous.closePrompt(); }; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; @@ -448,20 +447,29 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { // gutter scrollbar: a left click scrolls UP to that row p.active = id; pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); - } else if (mrow >= tag_y and mrow < tag_y + BOX_H) { - if (mcol < r.x + TAG_TEXT_INSET) return; - p.active = id; - pane.closePrompt(); - p.enterTagEdit(pane, if (tagColumn(p, .pane, id, p.pointer_tag_hit, false)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, r.x + TAG_TEXT_INSET)); - pane.tag_anchor = pane.tag_col; - p.drag = .{ .tag = .{ .id = id } }; } else { + const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; + if (on_tag and mcol < r.x + TAG_TEXT_INSET) return; p.active = id; - if (pane.tag_edit) Pardes.exitTagEdit(pane); pane.closePrompt(); const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; pane.clearPointerSelection(sel_slot); pane.sel[sel_slot] = pointed.sel; + // A clicked tag is typed straight into, from where it was + // clicked; `:` is the door to its normal mode. + pane.focus = if (on_tag) .tag else .body; + if (on_tag) { + // a count typed before the click was meant for the body + pane.body.normal.clear(); + pane.tag.mode = .insert; + pane.tag.normal.clear(); + pane.tag.vsel.active = false; + pane.tag.msel.active = false; + pane.tag.nsel = 0; + pane.tag.cur_pinned = true; + pane.tag.cur_row = 0; + pane.tag.cur_col = @intCast(p.tagOffsetAt(pane, @intCast(@max(0, pointed.sel.c0))) orelse 0); + } p.drag = .{ .select = .{ .id = id, .button = config.select_button, @@ -472,7 +480,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { config.select_button, mcol, mrow, - false, + pointed.on_tag, ), } }; } @@ -617,13 +625,6 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow); } }, - .tag => |d| { - const pane = p.panes[d.id] orelse return; - const c = if (tagColumn(p, .pane, d.id, p.pointer_tag_hit, true)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, p.rects[d.id].x + TAG_TEXT_INSET); - const text = p.tagText(p.scratch.allocator(), pane) catch return; - pane.tag_col = @intCast(@min(text.len, panes.File.rawAtDisplay(text, @as(usize, @intCast(@max(0, c))) + pane.tag_scroll))); - pane.tag_sel = pane.tag_col != pane.tag_anchor; - }, .none => {}, } } @@ -816,6 +817,16 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const sl = pane.sel[sel_slot]; const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; if (!dragged) pane.sel[sel_slot].state = .none; + if (sl.r0 < BOX_H) { + // On the tag the caret goes where the button came up. A + // click on the path, if it can be renamed, drafts a name. + const at = p.tagOffsetAt(pane, @intCast(@max(0, sl.c1))); + if (at) |col| { + pane.tag.cur_row = 0; + pane.tag.cur_col = @intCast(col); + } else if (!dragged) p.draftName(pane, @intCast(@max(0, sl.c1))); + return; + } if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; if (dragged and pane.body.mode == .tty) mirrorTtySelection(p, pane); const body_vis = sl.r1 - @as(i32, BOX_H); @@ -869,7 +880,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } const txt = operand.text; const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; - if (clk.r0 < BOX_H and s.button == config.exec_button and pane.tag_name_len != null) { + if (clk.r0 < BOX_H and s.button == config.exec_button and pane.prompt == .name) { const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; if (!p.commitTagName(pane)) return; @@ -895,7 +906,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { }); } }, - .tag => {}, // dragUpdate already left the tag cursor + selection set .none => {}, } } @@ -913,6 +923,30 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); return; }; + if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < BOX_H) { + // A sweep over the tag cuts from and pastes into the tag's own text; + // the part of it over the prefix is not the tag's to cut. + const t = &pane.tag; + if (!s.chorded) { + s.chorded = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const from = p.tagOffsetAt(pane, @intCast(@max(0, @min(sl.c0, sl.c1)))) orelse 0; + const to = p.tagOffsetAt(pane, @intCast(@max(0, @max(sl.c0, sl.c1)))) orelse 0; + t.cur_row = 0; + t.cur_col = @intCast(to); + t.cur_pinned = true; + t.vsel = .{ .active = from != to, .row = 0, .col = @intCast(from), .explicit = false }; + t.msel.active = false; + t.nsel = 0; + } + if (cut) { + if (t.vsel.active) edit.normalDelete(p, t, true); + } else if (t.vsel.active) { + edit.normalReplaceYank(p, t); + } else edit.pasteText(p, t, p.yank orelse return, true, 1); + return; + } if (pane.body.mode == .tty) { if (!s.chorded) { s.chorded = true; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 7e9cf7e7..282ae473 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -15,6 +15,7 @@ const addressing = @import("addr.zig"); const ctl = @import("ctl.zig"); const pty = @import("pty.zig"); const screen = @import("screen.zig"); +const limits = @import("../memory.zig").limits; const Pardes = pardes.Pardes; const Pane = pardes.Pane; @@ -384,7 +385,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply return switch (file) { .name => writeName(p, req, id, pane), .body => writeBody(p, req, id, pane), - .tag => writeTag(p, req, pane), + .tag => writeTag(req, pane), .ctl => ctl.writePane(p, req, pane), .addr, .dot, .limit => writeRange(req, pane, file), .data, .xdata => writeData(p, req, pane), @@ -417,15 +418,15 @@ fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } -fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { +fn writeTag(req: Req, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - p.seedTail(pane); - const room = pane.tag_tail.len - pane.tag_tail_len; + // The tag's own text grows by what is written, newlines and all: a tag + // is a text like any other (acme's tag file appends the same way). + const had = Pardes.curTail(pane).len; + const room = limits.max_tag_tail -| had; if (room == 0) return Reply.fail(req.tag, E.NOSPC); const take = wholeUtf8(req.data[0..@min(req.data.len, room)]); - @memcpy(pane.tag_tail[pane.tag_tail_len..][0..take], req.data[0..take]); - pane.tag_tail_len += take; - pane.tag_init = true; + pane.appendTag(req.data[0..take]) catch return Reply.fail(req.tag, E.NOMEM); return .{ .tag = req.tag, .written = @intCast(take) }; } @@ -553,8 +554,8 @@ pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) ! f.output = null; pane.clearCwd(); if (!preserve_tag) { - pane.tag_init = false; - pane.tag_tail_len = 0; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; } f.saved_revision = f.revision -% 1; f.watch_after_save = fs.localPath(full) != null; @@ -606,8 +607,13 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { setDot(pane, .{}); }, .tag => { - pane.tag_tail_len = 0; - pane.tag_init = true; + const empty = p.gpa.alloc(u8, 0) catch return .err; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = empty; + pane.tag.cur_row = 0; + pane.tag.cur_col = 0; + pane.tag.vsel.active = false; + pane.tag.nsel = 0; }, .addr => pf.addr = .{}, .limit => pf.limit = null, @@ -740,12 +746,20 @@ test "tag reads the whole tag and writes append to the editable tail" { const before = rd(p, node, 0, 4096).bytes.len; const w = wr(p, node, " Mine"); try testing.expectEqual(@as(u32, 5), w.reply.written); - try testing.expect(std.mem.endsWith(u8, pane.tag_tail[0..pane.tag_tail_len], " Mine")); + try testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), " Mine")); const after = rd(p, node, 0, 4096); try testing.expectEqual(before + 5, after.bytes.len); try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine")); - pane.tag_tail_len = pane.tag_tail.len; + // A tag is a text like the body: a newline written to it stays one, and + // the tag reads back taller by it. + try testing.expectEqual(@as(u32, 10), wr(p, node, "\nNext Line").reply.written); + try testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), " Mine\nNext Line")); + try testing.expect(std.mem.endsWith(u8, rd(p, node, 0, 4096).bytes, " Mine\nNext Line")); + + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.alloc(u8, limits.max_tag_tail); + @memset(pane.tag.own.?, 'x'); try testing.expectEqual(E.NOSPC, wr(p, node, "x").errno()); } @@ -873,10 +887,10 @@ test "truncating the tag clears its editable tail" { const pane = p.panes[0].?; const tag = Node.of(pane.serial, .tag); _ = wr(p, tag, " Mine"); - try testing.expect(pane.tag_tail_len > 0); + try testing.expect(Pardes.curTail(pane).len > 0); const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); try testing.expectEqual(Status.ok, cleared.reply.status); - try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); + try testing.expectEqualStrings("", pane.tag.own.?); try testing.expect(std.mem.indexOf(u8, rd(p, tag, 0, 4096).bytes, " Mine") == null); } diff --git a/src/normal.zig b/src/normal.zig index a77f27a7..e4fa075d 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -257,7 +257,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { if (p.multi_stop) { p.multi_stop = false; const pn = p.panes[id] orelse return; - if (pn.serial == serial) pn.body.nsel = 0; + if (pn.serial == serial) t.nsel = 0; return; } const text = edit.flatSurface(p, t) catch return; @@ -285,7 +285,7 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { const pane = t.pane(); - const raw_selection = pane.rawPointerText(pane.sel[sel_slot]) != null; + const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { pane.clearPointerSelection(sel_slot); @@ -334,7 +334,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .view_center => return t.gotoWindow(text, range, .center, go.count), .view_bottom => return t.gotoWindow(text, range, .bottom, go.count), }, - .view => |view| switch (view) { + .view => |view| if (t.what == .body) switch (view) { .top => { pane.scrollBy(t.cur_row - pane.scroll()); pane.ensureCursorVisible(); @@ -545,10 +545,11 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void p.leader_on = true; p.leader_n = 0; }, - .command_line => { - p.enterTagEdit(pane, -1); - if (pane.tag_edit) t.mode = .normal; - }, + // `:` is the one key a tag and a body do not share: it moves the + // keyboard between them. + .command_line => if (t.what == .tag) { + pane.focus = .body; + } else p.enterTag(pane), .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), .search_step => |direction| return look.lookWalk( @@ -590,10 +591,7 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { p.leader_on = true; p.leader_n = 0; }, - .command_line => { - p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.body.mode = .normal; - }, + .command_line => p.enterTag(pane), .search => p.startPrompt(pane, .{ .search = config.search_marker }), .search_forward => look.lookWalk(p, 1), .search_backward => look.lookWalk(p, -1), diff --git a/src/panes.zig b/src/panes.zig index c26065ca..720f655f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -69,9 +69,14 @@ pub const Pane = struct { /// Del from the keyboard with open panes both above and below: which /// one takes the rows. Nothing is typed; one key answers. del_side, + /// A new name for the file, drafted in place of the path on the + /// tagline after a click there; Enter commits it, as a buffer name + /// and never a disk rename. + name, }; pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; + pub const Focus = enum { body, tag }; terminal: ?*Terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, @@ -97,8 +102,9 @@ pub const Pane = struct { pdf: PdfSlot = if (Pdf.enabled) null else {}, prompt: Prompt = .none, /// The answer to an open prompt: its marker and what is typed after it, - /// edited in insert mode and shown on the notice band. It is its own text - /// so a prompt never touches the tag. + /// edited in insert mode and shown on the notice band, or a name draft + /// shown on the tagline in place of the path. It is its own text so a + /// prompt never touches the tag. input: Text = .{ .what = .input }, search_pane: ?usize = null, search_row: ?usize = null, @@ -107,23 +113,12 @@ pub const Pane = struct { nsel_snap: u8 = 0, sel_snap_pri: u8 = 0, sel_snap_expl: bool = false, - /// the editable tag tail: a bounded one-line command buffer. Input that - /// does not fit is refused atomically. - tag_tail: [limits.max_tag_tail]u8 = undefined, - tag_tail_len: usize = 0, - tag_init: bool = false, - tag_edit: bool = false, - tag_sel: bool = false, - /// the body mode a tag edit hijacked (tags are always insert); terminals - /// restore it on exit so clicking the tag never changes the pane's mode - tag_mode: Text.Mode = .normal, - tag_col: u16 = 0, - tag_saved_col: ?u16 = null, - tag_anchor: u16 = 0, - /// Filename edits are staged separately from the live buffer identity. - /// Enter commits the name; leaving tag editing discards the draft. - tag_name: [limits.host_path_cap]u8 = undefined, - tag_name_len: ?u16 = null, + /// The tag: what the user keeps after the computed prefix (the path, the + /// dirty marker, a PDF's page), its cursor, selections and undo. The + /// prefix is never stored in it, so it never moves the tag's cursor. + tag: Text = .{ .what = .tag }, + /// Which of the pane's texts the keyboard types into. + focus: Focus = .body, /// Display columns hidden to reveal the tag caret; tag addresses stay whole. tag_scroll: u16 = 0, cwd: Cwd = .none, @@ -297,9 +292,15 @@ pub const Pane = struct { return null; } - pub fn tagSlice(p: *const Pane) []const u8 { - return p.tag_tail[0..p.tag_tail_len]; + /// Add `text` to the end of the tag's own text, which starts out as the + /// default a pane of its kind shows. + pub fn appendTag(pane: *Pane, text: []const u8) !void { + const had = pane.tag.own orelse pardes.Pardes.defaultTail(pane); + const grown = try std.mem.concat(pane.gpa, u8, &.{ had, text }); + if (pane.tag.own) |old| pane.gpa.free(old); + pane.tag.own = grown; } + /// Close an open prompt, answered or not. Its answer goes with it, and an /// s/S preview keeps whatever it last previewed. pub fn closePrompt(pane: *Pane) void { @@ -313,33 +314,12 @@ pub const Pane = struct { /// painter of the band reads. pub fn promptText(p: *const Pane) ?[]const u8 { return switch (p.prompt) { - .none => null, + .none, .name => null, .del_side => config.del_question, else => p.input.own orelse "", }; } - pub fn appendTag(p: *Pane, text: []const u8) bool { - if (text.len > p.tag_tail.len - p.tag_tail_len) return false; - @memcpy(p.tag_tail[p.tag_tail_len..][0..text.len], text); - p.tag_tail_len += text.len; - return true; - } - - pub fn insertTagByte(p: *Pane, at: usize, byte: u8) bool { - if (at > p.tag_tail_len or p.tag_tail_len == p.tag_tail.len) return false; - std.mem.copyBackwards(u8, p.tag_tail[at + 1 .. p.tag_tail_len + 1], p.tag_tail[at..p.tag_tail_len]); - p.tag_tail[at] = byte; - p.tag_tail_len += 1; - return true; - } - - pub fn removeTagByte(p: *Pane, at: usize) void { - if (at >= p.tag_tail_len) return; - std.mem.copyForwards(u8, p.tag_tail[at .. p.tag_tail_len - 1], p.tag_tail[at + 1 .. p.tag_tail_len]); - p.tag_tail_len -= 1; - } - pub fn cwdSlice(p: *const Pane) []const u8 { return switch (p.cwd) { .none => "", diff --git a/src/pardes.zig b/src/pardes.zig index a29973e7..ce7c7065 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -687,9 +687,8 @@ test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { // Argument-taking builtins use the same gesture path: a tag sweep is the // complete command line, and Theme consumes its tail without a PTY write. - pane.tag_tail_len = 0; - try std.testing.expect(pane.appendTag(" Theme dark")); - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Theme dark"); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } }); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .drag, .col = tag_x + 10, .row = tag_y } }); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 10, .row = tag_y } }); @@ -707,8 +706,8 @@ test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { // A word absent from the builtin vocabulary takes the fallback, including // the terminating carriage return expected by the shell prompt. - pane.tag_tail_len = 0; - try std.testing.expect(pane.appendTag(" DefinitelyNotABuiltin")); + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " DefinitelyNotABuiltin"); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } }); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 1, .row = tag_y } }); var sent: [256]u8 = undefined; @@ -743,20 +742,20 @@ test "Collapse builtin keeps content and restores the pane from its default tag" try std.testing.expectEqual(revision, pane.file.?.revision); try std.testing.expectEqualStrings("keep this text\n", pane.file.?.content); try std.testing.expect((try p.render(p.scratch.allocator())).cursor == null); - p.enterTagEdit(pane, -1); + p.enterTag(pane); const tag_cursor = (try p.render(p.scratch.allocator())).cursor orelse return error.MissingTagCursor; try std.testing.expectEqual(p.rects[0].y, tag_cursor.y); - Pardes.exitTagEdit(pane); + pane.focus = .body; try std.testing.expect(p.executeBuiltinLine(0, "Collapse")); p.sync(); try std.testing.expect(!pane.collapsed); try std.testing.expectEqual(height, p.rects[0].h); // Unedited defaults from the preceding version gain the new command. - pane.tag_init = false; - pane.tag_tail_len = 0; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; p.restoreTailAt(pane, pre_collapse_file_pane_tail, "", .file); - try std.testing.expect(!pane.tag_init); + try std.testing.expect(pane.tag.own == null); try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(pane)); } @@ -859,8 +858,8 @@ test "TreeContext command and custom tag survive a workspace round trip" { try std.testing.expect(pane.file.?.tree_context); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext invalid")); try std.testing.expect(pane.file.?.tree_context); - try std.testing.expect(pane.appendTag(" Save Keep Del")); - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Save Keep Del"); try dump.dumpState(p); const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); @@ -874,22 +873,23 @@ test "Togglettymode builtin and keyboard chord share mode transitions including defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Mode ") != null); - p.seedTail(pane); - try std.testing.expect(pane.appendTag(" Togglettymode")); + try pane.appendTag(" Togglettymode"); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); - p.enterTagEdit(pane, -1); - try std.testing.expectEqual(Text.Mode.insert, pane.body.mode); + // The tag has its own mode: the body keeps tty while the tag is typed into. + p.enterTag(pane); + try std.testing.expect(pane.focus == .tag); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); - try std.testing.expect(!pane.tag_edit); - p.enterTagEdit(pane, -1); + try std.testing.expect(pane.focus == .body); + p.enterTag(pane); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); p.acknowledgePanelPresentation(&.{}); const tag = try p.tagText(p.scratch.allocator(), pane); @@ -974,10 +974,8 @@ test "compact tag commands stay beside their own prefix across layout changes" { try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); while (p.nextEffect()) |_| {} - - p.seedTail(below); - try std.testing.expectEqualStrings(tail, below.tagSlice()); - try std.testing.expect(below.appendTag(" lots and lots of typing out here")); + try std.testing.expectEqualStrings(tail, Pardes.curTail(below)); + try below.appendTag(" lots and lots of typing out here"); try std.testing.expectEqual(above_tag.len, (try p.tagText(p.scratch.allocator(), above)).len); p.update(.{ .resize = .{ .cols = 100, .rows = 2 } }); @@ -997,14 +995,14 @@ test "legacy default tag tails upgrade while custom tails remain owned" { legacy_pane_tail, }); p.restoreTail(terminal, terminal_old); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); const terminal_previous = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ try p.tagPrefix(terminal), }); p.restoreTail(terminal, terminal_previous); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); const terminal_prefilter = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ @@ -1012,60 +1010,60 @@ test "legacy default tag tails upgrade while custom tails remain owned" { prev_terminal_pane_tail, }); p.restoreTail(terminal, terminal_prefilter); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); for ([_][]const u8{ pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail }) |old_tail| { const old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try p.tagPrefix(terminal), old_tail }); p.restoreTail(terminal, old); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); } const custom_mode = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s} Keep", .{ try p.tagPrefix(terminal), pre_mode_terminal_pane_tail }); p.restoreTail(terminal, custom_mode); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(pre_mode_terminal_pane_tail ++ " Keep", Pardes.curTail(terminal)); - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; const terminal_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Keep Del", .{ try p.tagPrefix(terminal), }); p.restoreTail(terminal, terminal_custom); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; p.restoreDumpTail(terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd Keep Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; p.restoreDumpTail(terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd New Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); // This happens to be the historical FILE default, but on a terminal it is // user-owned text and must not be swallowed by migration. - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; const terminal_fileish = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Del", .{ try p.tagPrefix(terminal), }); p.restoreTail(terminal, terminal_fileish); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(" Save Del", Pardes.curTail(terminal)); // A savable file has a distinct old default. Save remains first after the @@ -1076,25 +1074,25 @@ test "legacy default tag tails upgrade while custom tails remain owned" { legacy_file_pane_tail, }); p.restoreTail(file, file_old); - try std.testing.expect(!file.tag_init); + try std.testing.expect(file.tag.own == null); try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(file)); const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{ try p.tagPrefix(file), }); p.restoreTail(file, file_custom); - try std.testing.expect(file.tag_init); + try std.testing.expect(file.tag.own != null); try std.testing.expectEqualStrings(" Save Mine Del", Pardes.curTail(file)); // Conversely the generic pane's current default is a custom edit on a // savable file. Legacy recognition is scoped to the source pane class. - file.tag_tail_len = 0; - file.tag_init = false; + if (file.tag.own) |own| p.gpa.free(own); + file.tag.own = null; const file_generic = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ try p.tagPrefix(file), }); p.restoreTail(file, file_generic); - try std.testing.expect(file.tag_init); + try std.testing.expect(file.tag.own != null); try std.testing.expectEqualStrings(" New Del", Pardes.curTail(file)); const image_doc = try panes.Image.create(p, 1, "/tmp/legacy image.ppm", &.{}); @@ -1105,8 +1103,8 @@ test "legacy default tag tails upgrade while custom tails remain owned" { .body = "", .image = .{ .path = "/tmp/legacy image.ppm" }, }); - try std.testing.expect(image_doc.tag_init); - try std.testing.expectEqualStrings(" Keep Del", image_doc.tagSlice()); + try std.testing.expect(image_doc.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(image_doc)); } test "Joincol folds the active column into its right neighbor, keeping its panes" { @@ -1247,11 +1245,11 @@ test "pane defaults keep creation of scratch panes in column tags" { try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", p.columnTag(0)); const terminal = p.panes[0].?; p.restoreTailAt(terminal, pre_column_terminal_pane_tail, "", .terminal); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); const file = try p.setTestFile("unchanged\n"); p.restoreTailAt(file, pre_column_file_pane_tail, "", .file); - try std.testing.expect(!file.tag_init); + try std.testing.expect(file.tag.own == null); try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(file)); } @@ -1398,8 +1396,8 @@ test "image dump restores source bytes renderer choices and exact custom tail" { pane.image.?.glyph_art = true; pane.image.?.pmode = .terminal; pane.image.?.ascii = false; - try std.testing.expect(pane.appendTag(" Keep Del")); - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Keep Del"); try dump.dumpState(p); var first_dump = try dump.readZon(gpa, p.dump_out.?, "image-first-dump"); @@ -1416,8 +1414,8 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expect(restored_pane.image.?.glyph_art); try std.testing.expectEqual(image.PaletteMode.terminal, restored_pane.image.?.pmode); try std.testing.expect(!restored_pane.image.?.ascii); - try std.testing.expect(restored_pane.tag_init); - try std.testing.expectEqualStrings(" Keep Del", restored_pane.tagSlice()); + try std.testing.expect(restored_pane.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(restored_pane)); try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); try dump.dumpState(restored); @@ -2095,20 +2093,20 @@ test "Save reaches every tagline with text behind it and no other" { pane_tail, }); p.restoreTail(out, dumped); - try std.testing.expect(!out.tag_init); + try std.testing.expect(out.tag.own == null); try std.testing.expectEqualStrings(locations_pane_tail, Pardes.curTail(out)); // A scratch is an output buffer that has worn the FILE tails all along, // so its own older default upgrades from that family too. out.file.?.output = .{ .from = .{ .cmd = std.meta.stringToEnum(Builtin, "New").? } }; - out.tag_tail_len = 0; - out.tag_init = false; + if (out.tag.own) |own| p.gpa.free(own); + out.tag.own = null; const scratch_dumped = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try p.tagPrefix(out), prev_file_pane_tail, }); p.restoreTail(out, scratch_dumped); - try std.testing.expect(!out.tag_init); + try std.testing.expect(out.tag.own == null); try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(out)); // An image's bytes on disk already are what they are: nothing of the @@ -2629,24 +2627,25 @@ test "Unicode display cells map back to body and tag byte cursors" { p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + 2, .row = body_y } }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - // A click in the wide path glyph likewise becomes a byte cursor at the + // A click in the wide path glyph drafts a name with its caret at the // grapheme start; arrow motion then advances by the full UTF-8 cluster. - p.enterTagEdit(pane, 1); - try std.testing.expectEqual(@as(u16, 0), pane.tag_col); - p.tagInsertKey(pane, .{ .cp = Key.right }); - try std.testing.expectEqual(@as(u16, 3), pane.tag_col); - p.tagInsertKey(pane, .{ .cp = Key.right }); - try std.testing.expectEqual(@as(u16, 6), pane.tag_col); - - const before = try gpa.dupe(u8, pane.tagSlice()); + p.draftName(pane, 1); + try std.testing.expectEqual(@as(i32, 0), pane.input.cur_col); + edit.insertKey(p, &pane.input, .{ .cp = Key.right }); + try std.testing.expectEqual(@as(i32, 3), pane.input.cur_col); + edit.insertKey(p, &pane.input, .{ .cp = Key.right }); + try std.testing.expectEqual(@as(i32, 6), pane.input.cur_col); + pane.closePrompt(); + + const before = try gpa.dupe(u8, Pardes.curTail(pane)); defer gpa.free(before); - p.enterTagEdit(pane, -1); - const insertion = pane.tag_col; - p.tagInsertKey(pane, .{ .cp = 'λ', .text = "λ" }); - try std.testing.expectEqual(insertion + 2, pane.tag_col); - p.tagInsertKey(pane, .{ .cp = Key.backspace }); - try std.testing.expectEqual(insertion, pane.tag_col); - try std.testing.expectEqualStrings(before, pane.tagSlice()); + p.enterTag(pane); + const insertion = pane.tag.cur_col; + edit.insertKey(p, &pane.tag, .{ .cp = 'λ', .text = "λ" }); + try std.testing.expectEqual(insertion + 2, pane.tag.cur_col); + edit.insertKey(p, &pane.tag, .{ .cp = Key.backspace }); + try std.testing.expectEqual(insertion, pane.tag.cur_col); + try std.testing.expectEqualStrings(before, Pardes.curTail(pane)); } test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { @@ -4110,6 +4109,9 @@ pub const Pardes = struct { if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); if (pane.input.own) |text| p.gpa.free(text); + if (pane.tag.own) |text| p.gpa.free(text); + for (pane.tag.ed_undo[0..pane.tag.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); + for (pane.tag.ed_redo[0..pane.tag.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); @@ -4762,7 +4764,7 @@ pub const Pardes = struct { ); if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); if (pane.file) |f| { - const name = if (pane.tag_name_len) |len| pane.tag_name[0..len] else f.path; + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; if (panes.Output.fileTraits(f.output).saves and f.revision != f.saved_revision) return std.fmt.allocPrint(arena, "{s}{s}", .{ name, dirty_marker }); return arena.dupe(u8, name); @@ -4770,10 +4772,10 @@ pub const Pardes = struct { return arena.dupe(u8, pane.cwdSlice()); } - /// the editable tail: the user's edited buffer once touched, else defaults - fn curTail(pane: *Pane) []const u8 { - if (pane.tag_init) return pane.tagSlice(); - return defaultTail(pane); + /// The tag's own text: what the user made of it, or until then the + /// default a pane of its kind starts with. + pub fn curTail(pane: *Pane) []const u8 { + return pane.tag.own orelse defaultTail(pane); } pub fn defaultTail(pane: *const Pane) []const u8 { @@ -4793,6 +4795,8 @@ pub const Pardes = struct { return null; } + /// The tag as it is shown, read and pointed at: its computed prefix and + /// its own text after it. pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { const prefix = try p.tagPrefix(pane); const tail = curTail(pane); @@ -4814,7 +4818,7 @@ pub const Pardes = struct { } var start: usize = 0; const name = if (pane.file) |file| - if (pane.tag_name_len) |len| pane.tag_name[0..len] else file.path + if (pane.prompt == .name) pane.input.own orelse file.path else file.path else if (pane.image) |state| blk: { // Image tags put renderer controls before the path. start = prefix_len -| state.path.len; @@ -4827,88 +4831,76 @@ pub const Pardes = struct { return .{ .lo = start + basename, .hi = start + name.len }; } - pub fn seedTail(_: *Pardes, pane: *Pane) void { - if (pane.tag_init) return; + /// 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 Save, so that `:` and the execute key write the file. + pub fn enterTag(p: *Pardes, pane: *Pane) void { + const t = &pane.tag; const tail = curTail(pane); - if (tail.len > pane.tag_tail.len) return; - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; - } - - pub fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void { - if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; - const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len); - p.seedTail(pane); - if (!pane.tag_init) return; - if (!pane.tag_edit) pane.tag_mode = pane.body.mode; - pane.tag_edit = true; - pane.tag_sel = false; - // a one-line tag has no use for normal mode: always insert - pane.body.mode = .insert; - pane.body.normal.clear(); - const end = edit0 + @as(i32, @intCast(pane.tag_tail_len)); - const tail = pane.tagSlice(); - const lead: i32 = @intCast(tail.len - std.mem.trimStart(u8, tail, " ").len); - if (col < 0) { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - if (pane.tag_saved_col) |saved| { - pane.tag_col = @intCast(modal.graphemeStart(text, @min(saved, text.len))); - } else { - pane.tag_col = @intCast(@min(edit0 + lead, end)); - } - if (pane.tag_saved_col == null) if (p.paneIdOf(pane)) |id| { + if (!t.cur_pinned) { + var words = std.mem.tokenizeAny(u8, tail, " \t\n"); + const at = while (words.next()) |word| { + if (std.mem.eql(u8, word, "Save")) break @intFromPtr(word.ptr) - @intFromPtr(tail.ptr); + } else tail.len - std.mem.trimStart(u8, tail, " ").len; + const cursor = modal.positionAt(tail, @min(at, tail.len)); + t.cur_row = @intCast(cursor.row); + t.cur_col = @intCast(cursor.col); + t.cur_pinned = true; + // Reveal the suffix together with its commands, not merely the + // first command letter at the viewport's far right edge. + if (p.paneIdOf(pane)) |id| { + const tag = p.tagText(p.scratch.allocator(), pane) catch return; + const line = tag[0 .. std.mem.indexOfScalar(u8, tag, '\n') orelse tag.len]; const width = p.tagCapacity(p.rects[id].w -| TAG_TEXT_INSET); - // Reveal the suffix together with its commands, not merely the - // first command letter at the viewport's far right edge. - pane.tag_scroll = @intCast(panes.File.displayWidth(text) + 1 -| width); - }; - } else { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - pane.tag_col = @intCast(@min(text.len, panes.File.rawAtDisplay(text, @as(usize, @intCast(col)) + pane.tag_scroll))); - } - } - - pub fn exitTagEdit(pane: *Pane) void { - if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; - if (pane.isTerminal()) { - if (pane.tag_edit) pane.body.mode = pane.tag_mode; - } else pane.body.mode = .normal; - pane.tag_edit = false; - pane.tag_sel = false; - pane.tag_name_len = null; - pane.tag_scroll = 0; - } - - pub fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } { - const a: usize = pane.tag_anchor; - const c: usize = pane.tag_col; - return .{ .lo = @min(a, c), .hi = @max(a, c) }; - } - - fn tagChordText(p: *Pardes, pane: *Pane) ?[]const u8 { - const text = p.tagText(p.scratch.allocator(), pane) catch return null; - if (pane.tag_sel) { - const b = tagSelBounds(pane); - const hi = modal.nextGrapheme(text, b.hi); - return if (hi > b.lo) text[b.lo..hi] else null; + pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); + } } - const b = config.wordBounds(text, @min(@as(usize, pane.tag_col), text.len)); - return if (b.hi > b.lo) text[b.lo..b.hi] else null; + // The text may have changed since (a 9P write, a rename), so the + // remembered cursor is pulled back inside it. It is the cursor that + // is remembered, not a selection. + const rows = modal.cursorLineCount(tail); + t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); + const line = modal.lineSlice(tail, @intCast(t.cur_row)); + t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); + t.vsel.active = false; + t.msel.active = false; + t.nsel = 0; + t.select = false; + t.append_at = null; + t.sticky_col = -1; + t.mode = .normal; + t.normal.clear(); + pane.focus = .tag; + } + + /// Where display column `col` of the tagline (tag scroll included) lands + /// in the tag's own text, or null when it is on the prefix. + pub fn tagOffsetAt(p: *Pardes, pane: *Pane, col: usize) ?usize { + const prefix = p.tagPrefix(pane) catch return null; + const width = panes.File.displayWidth(prefix); + if (col < width) return null; + const tail = curTail(pane); + const line = tail[0 .. std.mem.indexOfScalar(u8, tail, '\n') orelse tail.len]; + return modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)); } - fn tagNameEnd(pane: *const Pane) ?usize { - const f = pane.file orelse return null; - if (!panes.Output.fileTraits(f.output).saves or f.path.len > pane.tag_name.len) return null; - return if (pane.tag_name_len) |len| len else f.path.len; + /// 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 return; + pane.closePrompt(); + pane.prompt = .name; + pane.input = .{ .what = .input, .own = name, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(@min(name.len, panes.File.rawAtDisplay(name, col))) }; } - /// Commit a staged buffer name, never a disk rename or write. Keep the + /// 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 { - const len = pane.tag_name_len orelse return true; + if (pane.prompt != .name) return true; const id = p.paneIdOf(pane) orelse return false; - const name = pane.tag_name[0..len]; + const name = pane.input.own orelse ""; if (name.len == 0 or name[name.len - 1] == '/' or !std.unicode.utf8ValidateSlice(name)) { p.reportError(id, "name", error.InvalidName); return false; @@ -4917,8 +4909,6 @@ pub const Pardes = struct { p.reportError(id, "name", error.InvalidName); return false; }; - const old_prefix = (p.tagPrefix(pane) catch return false).len; - const tail_col = @as(usize, pane.tag_col) -| old_prefix; const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ paneDir(pane), name }) catch |err| { p.reportError(id, "name", err); return false; @@ -4927,181 +4917,10 @@ pub const Pardes = struct { p.reportError(id, "name", err); return false; }; - pane.tag_name_len = null; - const prefix = (p.tagPrefix(pane) catch return false).len; - pane.tag_col = @intCast(prefix + @min(tail_col, pane.tag_tail_len)); - pane.tag_sel = false; - return true; - } - - /// Replace one range in the rendered tag. The file name and command tail - /// retain separate identities even when a selection crosses their boundary. - pub fn replaceTagText(p: *Pardes, pane: *Pane, start: usize, finish: usize, input: []const u8) bool { - const prefix_len = (p.tagPrefix(pane) catch return false).len; - const end = prefix_len + pane.tag_tail_len; - const lo = @min(start, end); - const hi = @max(lo, @min(finish, end)); - const name_end = tagNameEnd(pane); - const editing_name = if (name_end) |n| lo <= n else false; - if (!editing_name and lo < prefix_len) return false; - var bytes: [limits.max_tag_tail]u8 = undefined; - var count: usize = 0; - for (input) |byte| { - if (byte == '\n' or byte == '\r') continue; - if (count == bytes.len) return false; - bytes[count] = byte; - count += 1; - } - const tail_lo = lo -| prefix_len; - const tail_hi = hi -| prefix_len; - const tail_insert = if (editing_name) 0 else count; - const tail_len = pane.tag_tail_len - (tail_hi - tail_lo) + tail_insert; - if (tail_len > pane.tag_tail.len) return false; - if (editing_name) { - const n = name_end.?; - const name_hi = @min(hi, n); - const name_len = n - (name_hi - lo) + count; - if (name_len > pane.tag_name.len) return false; - if (pane.tag_name_len == null) @memcpy(pane.tag_name[0..n], pane.file.?.path); - if (count > name_hi - lo) - std.mem.copyBackwards(u8, pane.tag_name[lo + count .. name_len], pane.tag_name[name_hi..n]) - else - std.mem.copyForwards(u8, pane.tag_name[lo + count .. name_len], pane.tag_name[name_hi..n]); - @memcpy(pane.tag_name[lo..][0..count], bytes[0..count]); - pane.tag_name_len = @intCast(name_len); - } - if (tail_insert > tail_hi - tail_lo) - std.mem.copyBackwards(u8, pane.tag_tail[tail_lo + tail_insert .. tail_len], pane.tag_tail[tail_hi..pane.tag_tail_len]) - else - std.mem.copyForwards(u8, pane.tag_tail[tail_lo + tail_insert .. tail_len], pane.tag_tail[tail_hi..pane.tag_tail_len]); - if (!editing_name) @memcpy(pane.tag_tail[tail_lo..][0..count], bytes[0..count]); - pane.tag_tail_len = tail_len; - pane.tag_col = @intCast(lo + count); - pane.tag_sel = false; + pane.closePrompt(); return true; } - fn tagInsertKey(p: *Pardes, pane: *Pane, key: Key) void { - if (hit(key, config.escape)) { - exitTagEdit(pane); // the tag is ALWAYS insert; Esc leaves it - return; - } - // the acme chords on the selection or the word at the cursor - if (hit(key, config.look_key) or hit(key, config.exec_key)) { - if (pane.tag_name_len != null) { - const in_name = pane.tag_col < (p.tagPrefix(pane) catch return).len; - if (!p.commitTagName(pane)) return; - if (hit(key, config.look_key) or in_name) { - exitTagEdit(pane); - return; - } - } - if (p.tagChordText(pane)) |txt| { - pane.tag_sel = false; - exec.runBuiltin(p, if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", txt); - } - return; - } - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const end = text.len; - if (key.text.len > 0) { - const range: @TypeOf(tagSelBounds(pane)) = if (pane.tag_sel) tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; - const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; - _ = p.replaceTagText(pane, range.lo, hi, key.text); - return; - } - switch (key.cp) { - Key.backspace, Key.delete => { - if (pane.tag_sel) { - const range = tagSelBounds(pane); - _ = p.replaceTagText(pane, range.lo, modal.nextGrapheme(text, range.hi), ""); - } else if (key.cp == Key.backspace and pane.tag_col > 0) { - _ = p.replaceTagText(pane, modal.prevGrapheme(text, pane.tag_col), pane.tag_col, ""); - } else if (key.cp == Key.delete and pane.tag_col < end) { - _ = p.replaceTagText(pane, pane.tag_col, modal.nextGrapheme(text, pane.tag_col), ""); - } - }, - Key.left => if (pane.tag_col > 0) { - pane.tag_col = @intCast(modal.prevGrapheme(text, pane.tag_col)); - }, - Key.right => if (pane.tag_col < end) { - pane.tag_col = @intCast(modal.nextGrapheme(text, pane.tag_col)); - }, - Key.home => pane.tag_col = 0, - Key.end => pane.tag_col = @intCast(end), - else => {}, - } - } - - /// write a helix range back onto the tag cursor + selection: the rendered - /// tag's one-line mirror of setPaneRange. - fn setTagRange(pane: *Pane, text: []const u8, r: modal.Selection) void { - const lo = @min(r.anchor, r.head); - const hi = @max(r.anchor, r.head); - pane.tag_col = @intCast(modal.selectionCursor(text, r)); - pane.tag_sel = modal.nextGrapheme(text, lo) < hi; // one grapheme IS the block cursor - if (pane.tag_sel) pane.tag_anchor = @intCast(if (r.head > r.anchor) lo else modal.prevGrapheme(text, hi)); - } - - fn tagNormalKey(p: *Pardes, pane: *Pane, key: Key) void { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const cur: usize = @min(@as(usize, pane.tag_col), text.len); - // Esc abandons the command line: back to the body, tail kept as text - if (hit(key, config.escape) or hit(key, &.{.{ .cp = 'j' }})) return exitTagEdit(pane); - if (hit(key, config.look_key) or hit(key, config.exec_key)) { - const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; - const txt = p.tagChordText(pane) orelse return; - const id = p.active; - const body_mode = pane.tag_mode; - exitTagEdit(pane); // leave the tag FIRST: Del frees the pane - pane.body.mode = body_mode; - exec.runBuiltin(p, cmd, id, "", txt); - return; - } - if (hit(key, config.tag_yank)) { - if (p.tagChordText(pane)) |txt| edit.setClipboard(p, txt); - return; - } - if (hit(key, config.insert) or hit(key, config.append) or - hit(key, config.insert_line_start) or hit(key, config.insert_line_end)) - { - const edit0: usize = if (tagNameEnd(pane) != null) 0 else (p.tagPrefix(pane) catch return).len; - pane.tag_col = @intCast(@max(edit0, if (hit(key, config.append)) - modal.nextGrapheme(text, cur) - else if (hit(key, config.insert_line_start)) - 0 - else if (hit(key, config.insert_line_end)) - text.len - else - cur)); - pane.tag_sel = false; - pane.body.mode = .insert; - return; - } - const dir: ?Builtin = for (config.window_keys) |wk| { - var letter = wk.letter; - letter.cp = std.ascii.toUpper(@intCast(letter.cp)); - if (hit(key, &.{letter})) break wk.cmd; - } else null; - if (dir) |d| { - const from = p.active; - exec.runBuiltin(p, d, from, "", null); - if (p.active == from) { - if (d == .Up) { - exitTagEdit(pane); - p.enterHeader(if (p.columnBarHeight() > 0) (layout.findPane(p, from) orelse return).col else null); - } - return; - } - const dest = p.panes[p.active] orelse return; - exitTagEdit(pane); // the pane we left is fully out of its tag... - p.enterTagEdit(dest, -1); - if (dest.tag_edit) dest.body.mode = .normal; - return; - } - if (lineMotion(text, cur, key)) |r| setTagRange(pane, text, r); - } - fn lineMotion(text: []const u8, cur: usize, key: Key) ?modal.Selection { const target: ?usize = if (hit(key, config.line_move_left)) modal.prevGrapheme(text, cur) @@ -5243,8 +5062,7 @@ pub const Pardes = struct { const pane = p.panes[d].?; p.exitHeader(); p.active = d; - p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.body.mode = .normal; + p.enterTag(pane); return; } if (hit(key, config.topbar_up)) { @@ -5268,12 +5086,11 @@ pub const Pardes = struct { pub fn cycleMode(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (pane.file == null and !pane.isTerminal()) return; - const previous = if (pane.tag_edit) pane.tag_mode else pane.body.mode; + const previous = pane.body.mode; p.active = id; p.exitHeader(); - if (pane.tag_edit) exitTagEdit(pane); + pane.focus = .body; pane.closePrompt(); - pane.body.mode = previous; switch (previous) { .tty => { pane.body.mode = .normal; @@ -5293,7 +5110,7 @@ pub const Pardes = struct { if (!pane.isTerminal()) return; p.active = id; p.exitHeader(); - if (pane.tag_edit) exitTagEdit(pane); + pane.focus = .body; pane.closePrompt(); if (pane.body.mode == .tty) { pane.body.mode = .normal; @@ -5314,7 +5131,7 @@ pub const Pardes = struct { } if (p.topbar_col != null) return p.topbarKey(key); const pane = p.panes[p.active] orelse return; - if (pane.isTerminal() and pane.body.mode == .tty and !pane.tag_edit) { + if (pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) @@ -5352,7 +5169,8 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - if (hit(key, config.window_prefix) and pane.body.mode != .insert and pane.prompt == .none) { + const t = if (pane.focus == .tag) &pane.tag else &pane.body; + if (hit(key, config.window_prefix) and t.mode != .insert and pane.prompt == .none) { p.ctrl_w_pending = true; return; } @@ -5385,6 +5203,21 @@ pub const Pardes = struct { if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } + if (pane.prompt == .name) { + // Enter or the execute key commits the draft and the keyboard + // goes back to the body; Esc drops it. + if (hit(key, config.look_key) or hit(key, config.exec_key)) { + if (p.commitTagName(pane)) pane.focus = .body; + return; + } + if (hit(key, config.escape)) { + pane.closePrompt(); + pane.focus = .body; + return; + } + edit.handleInsert(p, &pane.input, key); + return; + } if (pane.prompt != .none) { if (hit(key, config.search_submit) or hit(key, config.escape)) { const submit = hit(key, config.search_submit); @@ -5395,7 +5228,7 @@ pub const Pardes = struct { look.submitSearch(p, p.active) else if (normal.selRegexArmed(pane)) |_| normal.applySelRegex(p, pane, "", false), - .none, .del_side => unreachable, + .none, .del_side, .name => unreachable, } pane.closePrompt(); pane.body.mode = .normal; @@ -5406,12 +5239,27 @@ pub const Pardes = struct { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - if (pane.tag_edit) { - if (pane.body.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); - return; - } - if (pane.body.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { + if (t.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; + if (pane.focus == .tag) { + // An explicit selection, else the word under the cursor in the + // tag as it is shown: the prefix is part of what a word is. + const tag = p.tagText(p.scratch.allocator(), pane) catch return; + const tail = curTail(pane); + const range = t.primaryRange(tail, 0); + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + const txt = if ((t.vsel.active and t.vsel.explicit) or t.msel.active) + tail[lo..hi] + else word: { + const b = config.wordBounds(tag, tag.len - tail.len + modal.selectionCursor(tail, range)); + break :word tag[b.lo..b.hi]; + }; + // Out of the tag FIRST: Del frees the pane. + pane.focus = .body; + if (txt.len > 0) exec.runBuiltin(p, cmd, p.active, "", txt); + return; + } edit.pinPaneCursor(p, &pane.body); const explicit = (p.native_images and pane.hasPdfSelection()) or (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active; @@ -5430,14 +5278,12 @@ pub const Pardes = struct { exec.runBuiltin(p, cmd, p.active, "", word); return; } - if (pane.body.mode == .normal and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); - switch (pane.body.mode) { - .normal => { - normal.handleNormal(p, &pane.body, key); - }, + if (t.mode == .normal and t.what == .body and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); + switch (t.mode) { + .normal => normal.handleNormal(p, t, key), .insert => { - if (hit(key, config.escape)) return edit.exitInsert(p, &pane.body); - edit.handleInsert(p, &pane.body, key); + if (hit(key, config.escape)) return edit.exitInsert(p, t); + edit.handleInsert(p, t, key); }, .tty => panes.Terminal.forwardKey(p, p.active, key), } @@ -5507,7 +5353,7 @@ pub const Pardes = struct { const dir = if (request == .save) paneDir(pane) else ""; const slash: []const u8 = if (request == .save and (dir.len == 0 or dir[dir.len - 1] != '/')) "/" else ""; const answer = std.mem.concat(p.gpa, u8, &.{ marker, dir, slash }) catch return; - if (pane.tag_edit) exitTagEdit(pane); + pane.focus = .body; // Not closePrompt: an s/S snapshot was taken for this very prompt. if (pane.input.own) |old| p.gpa.free(old); pane.prompt = switch (request) { @@ -5806,8 +5652,7 @@ pub const Pardes = struct { pub fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { if (src.tag_tail) |tail| { - if (!pane.appendTag(tail)) return; - pane.tag_init = true; + pane.tag.own = p.gpa.dupe(u8, tail) catch return; return; } const tail_class = tailClass(pane); @@ -5855,7 +5700,7 @@ pub const Pardes = struct { } fn restoreTailAt( - _: *Pardes, + p: *Pardes, pane: *Pane, saved_tag: []const u8, pfx: []const u8, @@ -5886,8 +5731,7 @@ pub const Pardes = struct { }; for (defaults) |default| if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; - if (!pane.appendTag(rest)) return; - pane.tag_init = true; + pane.tag.own = p.gpa.dupe(u8, rest) catch return; } /// Close a pane; its rows go to `to`, or where layout.absorbVWeight @@ -6053,8 +5897,18 @@ pub const Pardes = struct { p.trackJump(); for (&p.panes, 0..) |*slot, id| { const pane = slot.* orelse continue; - if (pane.tag_edit and (id != p.active or p.topbar_col != null)) - exitTagEdit(pane); + // The keyboard is on one pane, or on a header: a tag it has left + // hands it back to its body, and a name drafted there is dropped. + if (id != p.active or p.topbar_col != null) { + pane.focus = .body; + if (pane.prompt == .name) pane.closePrompt(); + } + // A sweep over the tag is the tag's while it has the keyboard. + const swept = pane.sel[sel_slot]; + if (pane.focus == .body and swept.state == .done and @min(swept.r0, swept.r1) < BOX_H) { + pane.clearPointerSelection(sel_slot); + pane.sel[sel_slot].state = .none; + } if (comptime terminal_panes) if (pane.terminal) |state| { var off: u16 = 0; while (off < state.reply_len) { @@ -6430,7 +6284,7 @@ pub const Pardes = struct { s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } }); } }, - .none, .select, .tag => if (p.pointer_inside) { + .none, .select => if (p.pointer_inside) { // hover hints on a pane's own trailing edge var c: usize = 0; while (c + 1 < p.ncol) : (c += 1) { @@ -6801,8 +6655,7 @@ pub const Pardes = struct { .font_role = .tagline, }; s.fill(r.x, tag_y, config.GUTTER, BOX_H, box_style); - const box_mode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; - s.set(r.x, tag_y, switch (box_mode) { + s.set(r.x, tag_y, switch (pane.body.mode) { .normal => config.tag_normal, .insert => config.tag_insert, .tty => config.tag_tty, @@ -6856,9 +6709,24 @@ pub const Pardes = struct { .bg = .{ .rgb = tag_bg }, .font_role = .tagline, }); - const tag = try p.tagText(arena, pane); - if (active and pane.tag_edit) { - const caret = panes.File.rawDisplayCol(tag, pane.tag_col); + const whole = try p.tagText(arena, pane); + const tail = curTail(pane); + const prefix_len = whole.len - tail.len; + // The tagline shows the tag's first line: its prefix and the first + // line of its own text. + const tag = whole[0 .. std.mem.indexOfScalar(u8, whole, '\n') orelse whole.len]; + // The keyboard's caret on it, as a byte offset: in its own text when + // the tag has the keyboard, in the path while a name is drafted. + const caret_at: ?usize = if (!active) + null + else if (pane.prompt == .name) + @min(tag.len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) + else if (pane.focus == .tag and pane.tag.cur_row == 0) + @min(tag.len, prefix_len + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) + else + null; + if (caret_at) |at| { + const caret = panes.File.rawDisplayCol(tag, at); var scroll: usize = pane.tag_scroll; if (caret < scroll) scroll = caret; if (caret >= scroll + capacity) scroll = caret - capacity + 1; @@ -6869,10 +6737,10 @@ pub const Pardes = struct { scroll = panes.File.rawDisplayCol(tag, raw); } pane.tag_scroll = @intCast(scroll); - } else pane.tag_scroll = 0; + } else if (pane.focus != .tag) pane.tag_scroll = 0; const tag_start = panes.File.rawAtDisplay(tag, pane.tag_scroll); _ = s.print(tx, tag_y, tw, tag[tag_start..], tag_style); - if (tagTintRange(pane, tag, tag.len - curTail(pane).len)) |name| { + if (tagTintRange(pane, tag, prefix_len)) |name| { const lo = @max(name.lo, tag_start); const hi = @min(name.hi, tag.len); if (lo < hi) { @@ -6889,23 +6757,31 @@ pub const Pardes = struct { body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); }; } - if (pane.tag_edit and pane.tag_sel) { - const b = tagSelBounds(pane); - var col = panes.File.rawDisplayCol(tag, b.lo) -| pane.tag_scroll; - const hi = modal.nextGrapheme(tag, b.hi); - const end = panes.File.rawDisplayCol(tag, hi); - while (col + pane.tag_scroll < end and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), tag_y); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; + // The tag's own selections, while it has the keyboard. A range of one + // grapheme is the block cursor, not a selection. + if (pane.focus == .tag) { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = pane.tag.ranges(tail, 0, &ranges); + const shown = tag.len - prefix_len; + for (ranges[0..got.n]) |range| { + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + if (modal.nextGrapheme(tail, lo) >= hi or lo >= shown) continue; + var col = panes.File.rawDisplayCol(tag, prefix_len + lo) -| pane.tag_scroll; + const end = panes.File.rawDisplayCol(tag, prefix_len + @min(hi, shown)); + while (col + pane.tag_scroll < end and col < tw) : (col += 1) { + const cell = s.at(tx + @as(u16, @intCast(col)), tag_y); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } } } - // cursor while editing the tag: byte offset mapped to its display cell - if (active and pane.tag_edit) { - // bar while typing, block for `:` normal mode (same rule as a body) - const col = panes.File.rawDisplayCol(tag, pane.tag_col) -| pane.tag_scroll; - if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = pane.body.mode == .insert }; + // the caret: bar while typing, block in normal mode (same rule as a body) + if (caret_at) |at| { + const col = panes.File.rawDisplayCol(tag, at) -| pane.tag_scroll; + const mode = if (pane.prompt == .name) pane.input.mode else pane.tag.mode; + if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = mode == .insert }; } for (pane.sel, 0..) |selection, button| { @@ -7034,10 +6910,10 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" const modal_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(rect.x + config.GUTTER + 1, modal_cursor.x); try std.testing.expectEqual(body_y, modal_cursor.y); - p.enterTagEdit(pane, 0); + p.enterTag(pane); const tag_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(if (p.settings.tag_bottom) rect.y + rect.h - BOX_H else rect.y, tag_cursor.y); - Pardes.exitTagEdit(pane); + pane.focus = .body; pane.body.mode = .tty; try std.testing.expect((try p.render(frame.allocator())).cursor == null); @@ -7193,7 +7069,7 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro p.update(.{ .key = .{ .cp = '/' } }); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); - try std.testing.expect(pane.prompt == .search and !pane.tag_edit); + try std.testing.expect(pane.prompt == .search and pane.focus == .body); try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); @@ -7243,8 +7119,7 @@ test "a stillborn pane gives its column to the first pane that joins it" { try std.testing.expect(p.executeBuiltinLine(shell, "Newcol")); const tagged = p.active; p.sync(); - p.seedTail(p.panes[tagged].?); - try std.testing.expect(p.panes[tagged].?.appendTag(" make")); + try p.panes[tagged].?.appendTag(" make"); try std.testing.expect(p.executeBuiltinLine(tagged, "Tty")); p.update(.tick); try std.testing.expect(p.panes[tagged] != null); diff --git a/test/mode.zig b/test/mode.zig index 19d59699..c429ea72 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -6,7 +6,7 @@ const Pardes = pardes.Pardes; fn mode(p: *Pardes, id: usize, expected: panes.Text.Mode) !void { try std.testing.expect(p.executeBuiltinLine(id, "Mode")); try std.testing.expectEqual(expected, p.panes[id].?.body.mode); - try std.testing.expect(!p.panes[id].?.tag_edit); + try std.testing.expect(p.panes[id].?.focus == .body); } fn clickModeTag(p: *Pardes) !void { @@ -17,13 +17,12 @@ fn clickModeTag(p: *Pardes) !void { const row = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| p.update(.{ .mouse = .{ .button = .left, .kind = kind, .col = rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(col)), .row = row } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.focus == .tag); } -fn customTag(pane: *pardes.Pane, text: []const u8) void { - @memcpy(pane.tag_tail[0..text.len], text); - pane.tag_tail_len = text.len; - pane.tag_init = true; +fn customTag(pane: *pardes.Pane, text: []const u8) !void { + if (pane.tag.own) |own| pane.gpa.free(own); + pane.tag.own = try pane.gpa.dupe(u8, text); } test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { @@ -37,14 +36,18 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") != null); try mode(p, 0, .normal); try mode(p, 0, .insert); + // A clicked tag is typed into; its execute key is a normal-mode key, as + // a body's is, and the body keeps its own mode meanwhile. try clickModeTag(p); - try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag_mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag.mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.body.mode); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); p.update(.{ .key = .{ .cp = pardes.Key.tab } }); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); while (p.nextEffect()) |effect| try std.testing.expect(effect != .write); - customTag(pane, " Togglettymode Keep"); + try customTag(pane, " Togglettymode Keep"); try mode(p, 0, .normal); try mode(p, 0, .insert); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); @@ -53,7 +56,7 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); - try std.testing.expectEqualStrings(" Togglettymode Keep", pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expectEqualStrings(" Togglettymode Keep", pane.tag.own.?); } test "Mode from actual tag Exec preserves parked file and output insert transactions" { @@ -65,17 +68,17 @@ test "Mode from actual tag Exec preserves parked file and output insert transact const pane = try p.setTestFile("ab\n"); if (output) pane.file.?.output = .{ .from = .search }; try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") == null); - customTag(pane, " Mode"); + try customTag(pane, " Mode"); try mode(p, 0, .insert); p.update(.{ .key = .{ .cp = '界', .text = "界" } }); p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); try std.testing.expectEqualStrings("界xab\n", pane.file.?.content); try clickModeTag(p); - try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag_mode); - if (normal_tag) pane.body.mode = .normal; + try std.testing.expectEqual(panes.Text.Mode.insert, pane.body.mode); + if (normal_tag) pane.tag.mode = .normal else p.update(.{ .key = .{ .cp = pardes.Key.escape } }); p.update(.{ .key = .{ .cp = pardes.Key.tab } }); try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); try std.testing.expect(pane.body.append_at == null); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("ab\n", pane.file.?.content); diff --git a/test/panes.zig b/test/panes.zig index f1adafee..a391dba2 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -12,6 +12,17 @@ const image = pardes.image; const syntax = pardes.syntax; const filesystem = pardes.filesystem; +/// The tag's caret as a byte offset into the tag as it is shown, prefix +/// included. +fn tagCaret(p: *Pardes, pane: *Pane) !usize { + return (try p.tagPrefix(pane)).len + @as(usize, @intCast(pane.tag.cur_col)); +} + +fn setTag(pane: *Pane, text: []const u8) !void { + if (pane.tag.own) |own| pane.gpa.free(own); + pane.tag.own = try pane.gpa.dupe(u8, text); +} + const TagLayerTests = struct { const Kind = @FieldType(pardes.TagLayer, "kind"); fn findLayer(p: *Pardes, kind: Kind, id: usize) !*pardes.TagLayer { @@ -36,10 +47,7 @@ const TagLayerTests = struct { p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 5, .tagline_h = 10 }; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/x"); - const tail = " " ++ "a" ** 38 ++ "\t界 END"; - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; + try setTag(pane, " " ++ "a" ** 38 ++ "\t界 END"); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); @@ -55,11 +63,11 @@ const TagLayerTests = struct { var stale = mouse(layer, x, .press); stale.tag_hit.?.serial +%= 1; p.update(.{ .mouse = stale }); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); p.update(.{ .mouse = mouse(layer, x, .press) }); p.update(.{ .mouse = mouse(layer, x, .release) }); - try std.testing.expect(pane.tag_edit); - try std.testing.expectEqual(@as(u16, @intCast(at)), pane.tag_col); + try std.testing.expect(pane.focus == .tag); + try std.testing.expectEqual(at, try tagCaret(p, pane)); p.update(.{ .key = .{ .cp = 'X', .text = "X" } }); _ = try p.render(frame.allocator()); const edited = try p.tagText(frame.allocator(), pane); @@ -91,7 +99,7 @@ const TagLayerTests = struct { event.row = @intFromFloat(painted_y); p.update(.{ .mouse = event }); } - try std.testing.expectEqual(@as(u16, @intCast(at)), pane.tag_col); + try std.testing.expectEqual(at, try tagCaret(p, pane)); } } @@ -119,19 +127,17 @@ const TagLayerTests = struct { try std.testing.expectEqualStrings(" ", p.surface.at(layer.viewport.x - 1, layer.viewport.y).grapheme()); p.update(.{ .mouse = mouse(layer, edge - 0.1, .press) }); try std.testing.expect(p.drag != .move); - try std.testing.expect(!p.panes[second].?.tag_edit); + try std.testing.expect(p.panes[second].?.focus == .body); p.update(.{ .mouse = mouse(layer, edge - 0.1, .release) }); p.update(.{ .mouse = mouse(layer, edge + 0.1, .press) }); p.update(.{ .mouse = mouse(layer, edge + 0.1, .release) }); try std.testing.expectEqual(second, p.active); - try std.testing.expect(p.panes[second].?.tag_edit); - try std.testing.expectEqual(@as(u16, 0), p.panes[second].?.tag_col); + // The first cell of the tag is its path: a click there drafts a name. + try std.testing.expect(p.panes[second].?.prompt == .name); + try std.testing.expectEqual(@as(i32, 0), p.panes[second].?.input.cur_col); p.update(.{ .key = .{ .cp = Key.escape } }); const left = p.panes[0].?; - const tail = " " ++ "a" ** 110; - @memcpy(left.tag_tail[0..tail.len], tail); - left.tag_tail_len = tail.len; - left.tag_init = true; + try setTag(left, " " ++ "a" ** 110); _ = try p.render(frame.allocator()); const left_layer = try findLayer(p, .pane, 0); const left_text = try p.tagText(frame.allocator(), left); @@ -142,8 +148,8 @@ const TagLayerTests = struct { p.update(.{ .mouse = mouse(layer, beyond_x, .release) }); try std.testing.expectEqual(@as(usize, 0), p.active); const end_col = left_layer.capacity(p.row_metrics) - 1; - try std.testing.expectEqual(@as(u16, @intCast(panes.File.rawAtDisplay(left_text, end_col))), left.tag_col); - try std.testing.expect(left.tag_sel); + try std.testing.expectEqual(panes.File.rawAtDisplay(left_text, end_col), try tagCaret(p, left)); + try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); const long = "a" ** 60 ++ "界END"; try std.testing.expect(p.global_tag.set(long)); @@ -167,12 +173,12 @@ const TagNavigationTests = struct { p.update(.{ .key = .{ .cp = cp } }); } - fn enterNormal(p: *Pardes) *Pane { - key(p, ':'); - return p.panes[p.active].?; + fn window(p: *Pardes, letter: u21) void { + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + key(p, letter); } - test "tag navigation retains each pane cursor and mouse placement overrides memory" { + test "a tag remembers its cursor, starts on Save, and a click moves it" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); defer p.deinit(); const first = try p.setTestFile("body\n"); @@ -183,65 +189,97 @@ const TagNavigationTests = struct { try std.testing.expect(layout.splitColumn(p, second_id, second_id, false)); p.update(.tick); p.active = 0; + // Nothing to remember yet: `:` lands on Save, in normal mode. key(p, ':'); + try std.testing.expect(first.focus == .tag and first.tag.mode == .normal); + const tail = Pardes.curTail(first); + try std.testing.expectEqualStrings("Save", tail[@intCast(first.tag.cur_col)..][0..4]); key(p, Key.home); for (0..3) |_| key(p, Key.right); - const first_col = first.tag_col; - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 3), first.tag.cur_col); + // `:` in the tag's normal mode is the way back to the body. + key(p, ':'); + try std.testing.expect(first.focus == .body); p.active = second_id; key(p, ':'); key(p, Key.home); for (0..5) |_| key(p, Key.right); - const second_col = second.tag_col; - key(p, Key.escape); + key(p, ':'); p.active = 0; key(p, ':'); - try std.testing.expectEqual(first_col, first.tag_col); - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 3), first.tag.cur_col); + key(p, ':'); p.active = second_id; key(p, ':'); - try std.testing.expectEqual(second_col, second.tag_col); - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 5), second.tag.cur_col); + key(p, ':'); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); const rect = p.rects[0]; const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; - ClickCursorTests.click(p, .left, rect.x + pardes.TAG_TEXT_INSET + 6, y); + const prefix: u16 = @intCast(panes.File.displayWidth(try p.tagPrefix(first))); + ClickCursorTests.click(p, .left, rect.x + pardes.TAG_TEXT_INSET + prefix + 6, y); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(u16, 6), first.tag_col); + try std.testing.expect(first.focus == .tag and first.tag.mode == .insert); + try std.testing.expectEqual(@as(i32, 6), first.tag.cur_col); key(p, Key.escape); + key(p, ':'); p.startPrompt(first, .{ .search = config.search_marker }); key(p, Key.escape); key(p, ':'); - try std.testing.expectEqual(@as(u16, 6), first.tag_col); - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 6), first.tag.cur_col); + key(p, ':'); try std.testing.expectEqualStrings("body\n", first.file.?.content); } - test "tag navigation clamps remembered columns to renamed graphemes and shorter tags" { + test "executing a word from the tag runs it and gives the keyboard back to the body" { + for ([_]u21{ Key.tab, Key.enter }) |chord| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("body\n"); + p.update(.{ .key = .{ .cp = 'i' } }); + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + while (p.nextEffect()) |_| {} + // `:` lands on Save; the execute key runs it, the look key looks + // it up. Either way the tag lets go of the keyboard first. + key(p, ':'); + try std.testing.expect(pane.focus == .tag); + key(p, chord); + try std.testing.expect(pane.focus == .body); + try std.testing.expectEqual(.normal, pane.body.mode); + var saved = false; + while (p.nextEffect()) |effect| { + if (effect == .save_file) saved = true; + } + try std.testing.expectEqual(chord == Key.tab, saved); + // ...and the tag still knows where it was. + key(p, ':'); + try std.testing.expectEqualStrings("Save", Pardes.curTail(pane)[@intCast(pane.tag.cur_col)..][0..4]); + } + } + + test "a renamed path never moves the tag's cursor and a shorter tag pulls it back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 14 }); defer p.deinit(); const pane = try p.setTestFile("body\n"); key(p, ':'); key(p, Key.home); for (0..3) |_| key(p, Key.right); - key(p, Key.escape); + key(p, ':'); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/界.zig"); key(p, ':'); - try std.testing.expectEqual(@as(u16, 1), pane.tag_col); - key(p, Key.end); - key(p, Key.escape); - p.gpa.free(pane.file.?.path); - pane.file.?.path = try p.gpa.dupe(u8, "/é"); - pane.tag_tail_len = 0; + try std.testing.expectEqual(@as(i32, 3), pane.tag.cur_col); + key(p, ':'); + try setTag(pane, "é"); key(p, ':'); - try std.testing.expectEqual(@as(u16, 3), pane.tag_col); + try std.testing.expectEqual(@as(i32, 2), pane.tag.cur_col); try std.testing.expectEqualStrings("body\n", pane.file.?.content); } - test "tag navigation J and K restore cursors in stacked panes" { + test "window keys move between panes from a tag and each tag keeps its cursor" { for ([_]bool{ false, true }) |bottom| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -253,88 +291,67 @@ const TagNavigationTests = struct { const second = p.panes[second_id].?; p.update(.tick); p.active = 0; - _ = enterNormal(p); + key(p, ':'); key(p, Key.home); key(p, 'l'); key(p, 'l'); - key(p, 'J'); + window(p, 'j'); try std.testing.expectEqual(second_id, p.active); - try std.testing.expect(!first.tag_edit and second.tag_edit); + try std.testing.expect(first.focus == .body and second.focus == .body); + key(p, ':'); key(p, Key.home); for (0..4) |_| key(p, 'l'); - key(p, 'K'); + window(p, 'k'); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(u16, 2), first.tag_col); - key(p, 'J'); - try std.testing.expectEqual(second_id, p.active); - try std.testing.expectEqual(@as(u16, 4), second.tag_col); + try std.testing.expect(second.focus == .body); + key(p, ':'); + try std.testing.expectEqual(@as(i32, 2), first.tag.cur_col); + window(p, 'j'); + key(p, ':'); + try std.testing.expectEqual(@as(i32, 4), second.tag.cur_col); } } - test "tag navigation uses uppercase pane and header keys while lowercase stays local" { + test "a tag's normal mode is the body's: motions stay in the tag and insert types into it" { for ([_]bool{ false, true }) |bottom| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); defer p.deinit(); _ = try p.setTestFile("body\n"); p.presentation.enabled = false; p.settings.tag_bottom = bottom; - p.settings.column_tags = true; try std.testing.expect(p.executeBuiltinLine(0, "New")); const right = p.active; try std.testing.expect(layout.splitColumn(p, right, right, false)); p.update(.tick); p.active = 0; - const pane = enterNormal(p); + key(p, ':'); + const pane = p.panes[0].?; key(p, Key.home); key(p, 'l'); - try std.testing.expectEqual(@as(u16, 1), pane.tag_col); + try std.testing.expectEqual(@as(i32, 1), pane.tag.cur_col); key(p, 'h'); key(p, 'k'); - try std.testing.expectEqual(@as(u16, 0), pane.tag_col); + key(p, 'j'); + try std.testing.expectEqual(@as(i32, 0), pane.tag.cur_col); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expect(pane.tag_edit and p.topbar_col == null); - key(p, 'L'); + try std.testing.expect(pane.focus == .tag and p.topbar_col == null); + window(p, 'l'); try std.testing.expectEqual(right, p.active); - try std.testing.expect(!pane.tag_edit and p.panes[right].?.tag_edit); - key(p, 'H'); + try std.testing.expect(pane.focus == .body and p.panes[right].?.focus == .body); + window(p, 'h'); try std.testing.expectEqual(@as(usize, 0), p.active); - key(p, 'K'); - try std.testing.expect(p.topbar_col != null and p.header_column != null); - try std.testing.expect(!pane.tag_edit); - key(p, 'l'); - const column_cursor = p.topbar_col.?; - key(p, 'K'); - try std.testing.expect(p.topbar_col != null and p.header_column == null); - key(p, 'l'); - key(p, 'l'); - const workspace_cursor = p.topbar_col.?; - key(p, 'J'); - try std.testing.expect(p.topbar_col != null and p.header_column != null); - try std.testing.expectEqual(column_cursor, p.topbar_col.?); - key(p, 'K'); - try std.testing.expectEqual(workspace_cursor, p.topbar_col.?); - key(p, 'J'); - key(p, 'J'); - try std.testing.expect(p.topbar_col == null and pane.tag_edit); - key(p, 'j'); - try std.testing.expect(!pane.tag_edit and p.topbar_col == null); - try std.testing.expectEqual(@as(usize, 0), p.active); - _ = enterNormal(p); - key(p, 'K'); - key(p, 'j'); - try std.testing.expect(p.topbar_col == null and !pane.tag_edit); key(p, ':'); key(p, 'i'); key(p, Key.end); - const before = pane.tag_tail_len; - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); - for ("hjklHJKL") |letter| { + const before = Pardes.curTail(pane).len; + try std.testing.expect(pane.focus == .tag and pane.tag.mode == .insert and pane.body.mode == .normal); + for ("hjklHJKL:") |letter| { const text = [_]u8{letter}; p.update(.{ .key = .{ .cp = letter, .text = &text } }); - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); + try std.testing.expect(pane.focus == .tag and pane.tag.mode == .insert); } - try std.testing.expectEqualStrings("hjklHJKL", pane.tag_tail[before..pane.tag_tail_len]); - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert and p.topbar_col == null); + try std.testing.expectEqualStrings("hjklHJKL:", Pardes.curTail(pane)[before..]); + try std.testing.expectEqualStrings("body\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), p.active); } } @@ -1151,32 +1168,26 @@ const TagNameTintTests = struct { } } - test "tag filename tint follows scrolled Unicode staged names and yields to selection" { + test "tag filename tint follows scrolled Unicode drafted names and yields to selection" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 38, .rows = 14 }); defer p.deinit(); const pane = try p.setTestFile("body\n"); - const old = pane.file.?.path.len; configure(p); defer p.custom_theme = null; - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(old - 1); - pane.tag_sel = true; const name = "/a/very/long/directory/that/extends/past/the/tag/界e\u{301}name-with-a-long-tail.zig"; - p.update(.{ .paste = name }); - try std.testing.expectEqualStrings(name, pane.tag_name[0..pane.tag_name_len.?]); - pane.tag_col = @intCast(std.mem.indexOf(u8, name, "界").?); - pane.tag_sel = false; + p.draftName(pane, 0); + redraft(pane, name); + pane.input.cur_col = @intCast(std.mem.indexOf(u8, name, "界").?); try std.testing.expect((try check(p, 0, name)) > 0); try std.testing.expect(pane.tag_scroll > 0); - pane.tag_anchor = pane.tag_col; - pane.tag_sel = true; + // A sweep over the wide glyph wears the selection over the tint. + const col: i32 = @intCast(panes.File.rawDisplayCol(name, @intCast(pane.input.cur_col))); + pane.sel[0] = .{ .state = .done, .c0 = col, .c1 = col + 1, .r0 = 0, .r1 = 0 }; pane.tag_scroll += 4; // bring both cells of the selected wide glyph into view var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const surface = try p.render(arena.allocator()); - const x = p.rects[0].x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.rawDisplayCol(name, pane.tag_col) - pane.tag_scroll)); + const x = p.rects[0].x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(col - pane.tag_scroll)); const y = if (p.settings.tag_bottom) p.rects[0].y + p.rects[0].h - pardes.BOX_H else p.rects[0].y; try std.testing.expectEqual(pardes.Color{ .rgb = p.theme().sel_fg }, surface.at(x, y).style.fg); try std.testing.expectEqual(pardes.Color{ .rgb = p.theme().sel_fg }, surface.at(x + 1, y).style.fg); @@ -1208,32 +1219,46 @@ const TagNameTintTests = struct { } }; -test "pane filename edits stage commit and cancel without changing body or command tail" { +/// Replace a name draft's text, the caret after it, as clearing it and +/// typing would. +fn redraft(pane: *Pane, name: []const u8) void { + if (pane.input.own) |own| pane.gpa.free(own); + pane.input.own = pane.gpa.dupe(u8, name) catch unreachable; + pane.input.cur_col = @intCast(name.len); +} + +/// Click the tagline at the end of the path: a name draft, caret there. +fn clickPathEnd(p: *Pardes, pane: *Pane) void { + const rect = p.rects[p.active]; + const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; + const x = rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(pane.file.?.path) - 1)); + ClickCursorTests.click(p, .left, x, y); + std.debug.assert(pane.prompt == .name); + pane.input.cur_col = @intCast(pane.input.own.?.len); +} + +test "pane filename drafts commit and cancel without changing body or command tail" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 70, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("original body\n"); const original = try p.gpa.dupe(u8, pane.file.?.path); defer p.gpa.free(original); - p.seedTail(pane); - try std.testing.expect(pane.appendTag(" SyntaxBold")); - const tail = try p.gpa.dupe(u8, pane.tagSlice()); + try pane.appendTag(" SyntaxBold"); + const tail = try p.gpa.dupe(u8, Pardes.curTail(pane)); defer p.gpa.free(tail); for ([_]bool{ false, true }) |commit| { - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(original.len - 1); - pane.tag_sel = true; + clickPathEnd(p, pane); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); p.update(.{ .paste = "/new name.zig" }); try std.testing.expectEqualStrings(original, pane.file.?.path); - try std.testing.expectEqualStrings("/new name.zig", pane.tag_name[0..pane.tag_name_len.?]); - try std.testing.expectEqualStrings(tail, pane.tagSlice()); + try std.testing.expectEqualStrings("/new name.zig", pane.input.own.?); + try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); try std.testing.expectEqualStrings("original body\n", pane.file.?.content); p.update(.{ .key = .{ .cp = if (commit) Key.enter else Key.escape } }); - try std.testing.expect(!pane.tag_edit); - try std.testing.expect(pane.tag_name_len == null); + try std.testing.expect(pane.focus == .body); + try std.testing.expect(pane.prompt == .none); try std.testing.expectEqualStrings(if (commit) "/new name.zig" else original, pane.file.?.path); - try std.testing.expectEqualStrings(tail, pane.tagSlice()); + try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); while (p.nextEffect()) |effect| try std.testing.expect(std.meta.activeTag(effect) != .save_file); } try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); @@ -1243,27 +1268,21 @@ test "pane filename grapheme edits and invalid empty commits preserve the buffer const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("untouched\n"); - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(pane.file.?.path.len - 1); - pane.tag_sel = true; + clickPathEnd(p, pane); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); p.update(.{ .paste = "/café界" }); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expectEqualStrings("/café", pane.tag_name[0..pane.tag_name_len.?]); + try std.testing.expectEqualStrings("/café", pane.input.own.?); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expectEqualStrings("/caf", pane.tag_name[0..pane.tag_name_len.?]); - pane.tag_anchor = 0; - pane.tag_col = 3; - pane.tag_sel = true; - p.update(.{ .key = .{ .cp = Key.delete } }); - try std.testing.expectEqual(@as(u16, 0), pane.tag_name_len.?); + try std.testing.expectEqualStrings("/caf", pane.input.own.?); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); + try std.testing.expectEqualStrings("", pane.input.own.?); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.prompt == .name); try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); try std.testing.expectEqualStrings("untouched\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(pane.tag_name_len == null); + try std.testing.expect(pane.prompt == .none); } test "leaving a pane or entering a header cancels an uncommitted filename" { @@ -1273,11 +1292,10 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { for ([_]bool{ false, true }) |header| { p.active = 0; p.topbar_col = null; - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - p.update(.{ .key = .{ .cp = Key.home } }); + p.update(.tick); + clickPathEnd(p, pane); p.update(.{ .paste = "/draft" }); - try std.testing.expect(pane.tag_name_len != null); + try std.testing.expect(pane.prompt == .name); if (header) { p.topbar_col = 0; p.update(.tick); @@ -1285,21 +1303,18 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { try std.testing.expect(p.executeBuiltinLine(0, "New")); p.update(.tick); } - try std.testing.expect(pane.tag_name_len == null); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.prompt == .none); + try std.testing.expect(pane.focus == .body); try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); } } -test "middle clicking Save commits the staged filename before issuing a save" { +test "middle clicking Save commits the drafted filename before issuing a save" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 70, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("untouched\n"); - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(pane.file.?.path.len - 1); - pane.tag_sel = true; + clickPathEnd(p, pane); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); p.update(.{ .paste = "/renamed.txt" }); var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); @@ -1312,7 +1327,7 @@ test "middle clicking Save commits the staged filename before issuing a save" { p.update(.{ .mouse = .{ .col = x, .row = y, .button = config.exec_button, .kind = .press } }); p.update(.{ .mouse = .{ .col = x, .row = y, .button = config.exec_button, .kind = .release } }); try std.testing.expectEqualStrings("/renamed.txt", pane.file.?.path); - try std.testing.expect(pane.tag_name_len == null); + try std.testing.expect(pane.prompt == .none); try std.testing.expectEqualStrings("untouched\n", pane.file.?.content); var saves: usize = 0; while (p.nextEffect()) |effect| if (effect == .save_file) { @@ -1322,24 +1337,19 @@ test "middle clicking Save commits the staged filename before issuing a save" { try std.testing.expectEqual(@as(usize, 1), saves); } -test "oversized filename paste refuses atomically across a selected tag boundary" { +test "an oversized drafted name is refused at commit and the draft stays to correct" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("untouched\n"); - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - const before = try p.tagText(p.gpa, pane); - defer p.gpa.free(before); - pane.tag_anchor = 0; - pane.tag_col = @intCast(before.len - 1); - pane.tag_sel = true; - const excess = try p.gpa.alloc(u8, pane.tag_name.len + 1); + clickPathEnd(p, pane); + const excess = try p.gpa.alloc(u8, 5000); defer p.gpa.free(excess); @memset(excess, 'x'); + excess[0] = '/'; p.update(.{ .paste = excess }); - try std.testing.expect(pane.tag_name_len == null); - try std.testing.expect(pane.tag_sel); - try std.testing.expectEqualStrings(before, try p.tagText(p.scratch.allocator(), pane)); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(pane.prompt == .name); + try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); try std.testing.expectEqualStrings("untouched\n", pane.file.?.content); } @@ -1349,16 +1359,17 @@ test "paste into pane commands and prompts never inserts into the body" { const pane = try p.setTestFile("one two one\n"); p.update(.{ .key = .{ .cp = ':' } }); p.update(.{ .key = .{ .cp = 'A' } }); - p.update(.{ .paste = " Custom\r\nCommand" }); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); + // A tag takes a paste as a body does, newline and all. + p.update(.{ .paste = " Custom\nCommand" }); + try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .search = config.search_marker }); p.update(.{ .paste = "t\r\nwo" }); try std.testing.expectEqualStrings(config.search_marker ++ "two", pane.promptText().?); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); + try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); try std.testing.expectEqualStrings("one two one\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); + try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); } test "long pane tags reveal commands and map visible clicks to whole tag addresses" { @@ -1367,8 +1378,7 @@ test "long pane tags reveal commands and map visible clicks to whole tag address const pane = try p.setTestFile("body\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/an/especially/deep/project/path/with/a/long/component/filename.zig"); - p.seedTail(pane); - try std.testing.expect(pane.appendTag(" SyntaxBold")); + try pane.appendTag(" SyntaxBold"); p.update(.{ .key = .{ .cp = ':' } }); p.update(.{ .key = .{ .cp = 'A' } }); var arena = std.heap.ArenaAllocator.init(p.gpa); @@ -1549,7 +1559,13 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.cur_pinned = true; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; panes.Terminal.pushUndo(p, pane); - pane.body.ed_redo[0] = panes.Terminal.snap(p, pane) orelse return error.SnapshotFailed; + const overlay = pane.ovl.?; + pane.body.ed_redo[0] = .{ + .ovl = .{ .row = overlay.row, .rows = overlay.rows, .text = try gpa.dupe(u8, overlay.text) }, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, + }; pane.body.ed_redo_len = 1; if (action == .hidden_undo) { gpa.free(pane.ovl.?.text); @@ -1663,9 +1679,7 @@ test "a prompt's entry and cancellation leave the tag, the body and its cursor a try pane.setOwnedCwd("/dír space"); const tail = " keep"; for (cases) |case| { - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; + try setTag(pane, tail); pane.body.cur_row = 1; pane.body.cur_col = 2; pane.body.cur_pinned = true; @@ -1677,17 +1691,17 @@ test "a prompt's entry and cancellation leave the tag, the body and its cursor a p.startPrompt(pane, .{ .search = config.search_marker }); } // The answer is typed into the prompt's own line, never the tag. - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); try std.testing.expectEqual(.insert, pane.input.mode); try std.testing.expectEqualStrings(case.marker, pane.promptText().?); try std.testing.expectEqual(@as(i32, @intCast(case.marker.len)), pane.input.cur_col); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expectEqualStrings(tail, pane.tag.own.?); try std.testing.expectEqualDeep(modal.Normal.State{}, pane.body.normal); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); try std.testing.expect(pane.input.own == null); try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expectEqualStrings(tail, pane.tag.own.?); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); try std.testing.expectEqualStrings("one\ntwo\n", pane.file.?.content); @@ -1698,9 +1712,10 @@ test "a prompt opens whatever the tag already holds" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); - @memset(&pane.tag_tail, 'x'); - pane.tag_tail_len = pane.tag_tail.len; - pane.tag_init = true; + const full = try p.gpa.alloc(u8, pardes.memory.limits.max_tag_tail); + defer p.gpa.free(full); + @memset(full, 'x'); + try setTag(pane, full); for (0..3) |case| { switch (case) { 0 => p.startPrompt(pane, .{ .search = config.search_marker }), @@ -1708,8 +1723,7 @@ test "a prompt opens whatever the tag already holds" { else => p.update(.{ .key = .{ .cp = '|' } }), } try std.testing.expect(pane.prompt != .none); - try std.testing.expectEqual(pane.tag_tail.len, pane.tag_tail_len); - for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); + try std.testing.expectEqualStrings(full, pane.tag.own.?); p.update(.{ .key = .{ .cp = Key.escape } }); } } @@ -1723,8 +1737,8 @@ test "generated output refuses every pipe prompt before seeding the tag" { for ([_]Key{ .{ .cp = '|' }, .{ .cp = '|', .alt = true }, .{ .cp = '!' }, .{ .cp = '!', .alt = true } }) |key| { p.update(.{ .key = key }); try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_init); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.tag.own == null); + try std.testing.expect(pane.focus == .body); try std.testing.expectEqualStrings("generated\n", pane.file.?.content); } } @@ -1798,7 +1812,7 @@ test "a prompt that cannot be opened leaves the open one as it was" { try std.testing.expect(pane.prompt == .search); try std.testing.expectEqualStrings(config.search_marker ++ "prior", pane.promptText().?); try std.testing.expectEqualDeep(previous_normal, pane.body.normal); - try std.testing.expect(!pane.tag_init and !pane.tag_edit); + try std.testing.expect(pane.tag.own == null and pane.focus == .body); } } @@ -1830,7 +1844,7 @@ test "a prompt opens with one allocation" { const before = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expectEqual(before + 1, failing.alloc_index); - try std.testing.expect(!pane.tag_edit and pane.input.mode == .insert); + try std.testing.expect(pane.focus == .body and pane.input.mode == .insert); } } @@ -4080,14 +4094,18 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu const rect = p.rects[0]; const tag_y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; const body_y = p.bodyTop(rect); - const x = rect.x + config.GUTTER + @as(u16, @intCast(panes.File.gutterWidth(pane))) + 3; + const x = if (gesture == .tag) + rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(try p.tagPrefix(pane)))) + 3 + else + rect.x + config.GUTTER + @as(u16, @intCast(panes.File.gutterWidth(pane))) + 3; const y = if (gesture == .tag) tag_y else body_y; p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x, .row = y } }); if (gesture == .tag) { - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.focus == .tag); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit); + p.update(.{ .key = .{ .cp = ':' } }); + try std.testing.expect(pane.focus == .body); } }, .focus, .last => { diff --git a/test/pdf.zig b/test/pdf.zig index 5bc271d4..745ecb1a 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -309,8 +309,8 @@ test "PDF dump fallback remains a byte-preserving file" { try std.testing.expect(!hasPdf(pane)); try std.testing.expectEqualStrings(path, pane.file.?.path); try std.testing.expectEqualSlices(u8, source, pane.file.?.content); - try std.testing.expect(pane.tag_init); - try std.testing.expectEqualStrings(" Keep Del", pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expect(pane.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", pane.tag.own.?); } test "PdfSections Look follows the exact owning PDF, not an equal path" { @@ -918,9 +918,8 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(PdfTintMode.full, pane.pdf.?.tint); pane.pdf.?.fit = .height; const custom_tail = " Keep Del"; - @memcpy(pane.tag_tail[0..custom_tail.len], custom_tail); - pane.tag_tail_len = custom_tail.len; - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, custom_tail); try pardes.dump.dumpState(p); const restored = try pardes.dump.initFromDump(gpa, .{}, p.dump_out.?); defer restored.deinit(); @@ -929,10 +928,10 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(PdfFitMode.width, restored.panes[0].?.pdf.?.fit); try std.testing.expectEqual(PdfTintMode.filtered, restored.panes[0].?.pdf.?.tint); const restored_pane = restored.panes[0].?; - try std.testing.expect(restored_pane.tag_init); + try std.testing.expect(restored_pane.tag.own != null); try std.testing.expectEqualStrings( custom_tail, - restored_pane.tag_tail[0..restored_pane.tag_tail_len], + restored_pane.tag.own.?, ); } @@ -1100,20 +1099,20 @@ test "PDF normal adapter consumes unsupported actions and navigates page fallbac try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count); try std.testing.expectEqual(.none, pane.body.normal.prefix); try std.testing.expect(!pane.body.vsel.active and !pane.body.msel.active and pane.body.nsel == 0); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); // Cross-pane BODY-NORMAL actions keep their established shared paths. p.update(.{ .key = .{ .cp = ':' } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.focus == .tag); try std.testing.expectEqual(Mode.normal, pane.body.mode); - p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit); + p.update(.{ .key = .{ .cp = ':' } }); + try std.testing.expect(pane.focus == .body); p.update(.{ .key = .{ .cp = ' ' } }); try std.testing.expect(p.leader_on); p.update(.{ .key = .{ .cp = '!' } }); try std.testing.expect(!p.leader_on); p.update(.{ .key = .{ .cp = '/' } }); - try std.testing.expect(pane.prompt == .search and !pane.tag_edit); + try std.testing.expect(pane.prompt == .search and pane.focus == .body); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); } diff --git a/test/snapshots/cmdword.golden b/test/snapshots/cmdword.golden index e6f470fa..f099464f 100644 --- a/test/snapshots/cmdword.golden +++ b/test/snapshots/cmdword.golden @@ -16,9 +16,9 @@ == snap nested grid=120x31 cursor=4,24 |22: ls |23: cmds.txt p.txt zzmark.txt -== snap execword grid=120x31 cursor=69,17 +== snap execword grid=120x31 cursor=4,24 |17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del Exec -== snap tagcmd grid=120x31 cursor=83,17 +== snap tagcmd grid=120x31 cursor=4,24 |17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del Exec @`echo ZZ''T` |24: echo ZZ''T |25: ZZT diff --git a/test/snapshots/cmdword.snap b/test/snapshots/cmdword.snap index eb0e0ea6..361e37ba 100644 --- a/test/snapshots/cmdword.snap +++ b/test/snapshots/cmdword.snap @@ -57,25 +57,31 @@ wait 10000 zzmark.txt stable 700 15000 snap nested # the same syntax typed into a TAG — the other place the expansion has to know -# about backticks (tagChordText). The look above left the shell focused, so `:` -# opens ITS tag; `i` then End walks to the end of the tail, and the chord runs -# the word under the cursor exactly as the body's does. +# about backticks. The look above left the shell focused, so `:` opens ITS +# tag; `A` appends at the end of it, Esc and `h` put the normal-mode cursor on +# the last character typed, and the execute key runs the word under it +# exactly as the body's does. key : -key i -key end +key A key space text Exec -key left +key esc +settle 100 +key h key tab stable 700 8000 # ...except that word is `Exec` ITSELF, with nothing to execute. This is the # case that must not hang a re-entrant dispatcher: it runs out of argument -# immediately and does nothing at all. +# immediately and does nothing at all. Executing gave the keyboard back to the +# body, and `:` finds the tag's cursor where it was left. snap execword -key end +key : +key A key space text @`echo ZZ''T` -key left +key esc +settle 100 +key h key tab wait 10000 ZZT stable 700 15000 diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 18d24d6b..eaf9bbc3 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -68,8 +68,8 @@ |3: |4: |5: -== 9p tab-collapsed-cursor grid=160x25 cursor=51,2,bar -== snap tab-restored grid=160x25 cursor=51,2 +== 9p tab-collapsed-cursor grid=160x25 cursor=none +== snap tab-restored grid=160x25 cursor=7,3 |3: 1 KEEP-FIRST Collapse |4: 2 KEEP-SECOND |5: 3 KEEP-THIRD diff --git a/test/snapshots/collapse.snap b/test/snapshots/collapse.snap index 64f6bdb8..83872855 100644 --- a/test/snapshots/collapse.snap +++ b/test/snapshots/collapse.snap @@ -1,5 +1,6 @@ # A default pane-tag command collapses to one row and restores the body. -# Exercise real middle clicks twice, then tag editing's Tab execution twice. +# Exercise real middle clicks twice, then the tag's own execute key twice: a +# click types into the tag, Esc is its normal mode, and Tab executes there. file kept.txt KEEP-FIRST\nKEEP-SECOND\nKEEP-THIRD start 25 160 kept.txt wait 8000 KEEP-THIRD @@ -19,12 +20,16 @@ stable 500 8000 snap middle-restored press left @Collapse 3 release left @Collapse 3 +key esc +settle 100 key tab stable 500 8000 snap tab-collapsed snap9p tab-collapsed-cursor press left @Collapse 3 release left @Collapse 3 +key esc +settle 100 key tab wait 8000 KEEP-THIRD stable 500 8000 diff --git a/test/snapshots/tag.snap b/test/snapshots/tag.snap index a545ff9f..4faf6062 100644 --- a/test/snapshots/tag.snap +++ b/test/snapshots/tag.snap @@ -1,7 +1,8 @@ -# a CLICKED tag is insert mode: type straight in (no 'i'; `:` is the normal- -# mode door, see tagcmd); backspace edits; Esc leaves back to the body; Enter -# looks the word at the cursor (Tab executes it). Multi-word execution from -# the tag stays the mouse's job (middle-drag), like anywhere else. +# a CLICKED tag is typed straight into (no 'i'; `:` is the normal-mode door, +# see tagcmd); backspace edits; Esc drops to the tag's normal mode, which is +# the body's normal mode, and `:` there hands the keyboard back to the body; +# Enter looks the word at the cursor (Tab executes it). Multi-word execution +# from the tag stays the mouse's job (middle-drag), like anywhere else. file t.txt ZZLOOKED start 31 150 -n 3 wait 8000 t.txt @@ -29,16 +30,21 @@ snap tag-del send .txt stable 600 8000 stable 400 5000 -# Esc: out of the tag, body back in normal mode, typed tail stays as text +# Esc: the tag's normal mode; `:` then gives the keyboard back to the body, +# which is in normal mode, and the typed text stays key esc settle 100 +key : stable 400 5000 snap tag-exit -# re-enter the tag and look the typed word: Enter opens t.txt as a file pane. -# Click the inserted word itself; filename, separator and commands are compact. +# re-enter the tag and look the typed word: Enter in normal mode opens t.txt +# as a file pane. Click the inserted word itself; filename, separator and +# commands are compact. press left @t.txt 3 release left @t.txt 3 stable 400 5000 +key esc +settle 100 key enter wait 10000 ZZLOOKED stable 700 15000 diff --git a/test/snapshots/tagalign.snap b/test/snapshots/tagalign.snap index 9df22f57..a77415d9 100644 --- a/test/snapshots/tagalign.snap +++ b/test/snapshots/tagalign.snap @@ -22,9 +22,14 @@ press left 12 3 release left 12 3 stable 400 5000 snap clicked -# End reveals the complete command suffix; a scrolled Del still executes. +# The click was on the path, so it drafted a name; Esc drops the draft. `:` +# then `A` puts the caret after the tag's end, which reveals the complete +# command suffix; a scrolled Del still executes. resize 31 70 -key end +key esc +settle 100 +key : +key A stable 400 5000 snap revealed press middle @Del 3 diff --git a/test/snapshots/tagcmd.snap b/test/snapshots/tagcmd.snap index 305ed521..0e9047fb 100644 --- a/test/snapshots/tagcmd.snap +++ b/test/snapshots/tagcmd.snap @@ -1,11 +1,12 @@ # `:` — vim's command line with acme's vocabulary. It focuses the pane's OWN # tag in NORMAL mode (block cursor; the layout box shows the pane's BODY mode, -# which for this file pane is normal either way), parked at the tail's -# START — always the start, so `:w` is the same two keystrokes every time. -# Motions walk the tag's words (w selects the "Save" span, exactly like a body -# word motion), the execute chord runs the one under the cursor and hands the -# body back in normal mode — same keys as the body, so Tab by default (see -# config.look_key/exec_key). Esc backs out instead, leaving the tail as it was. +# which for this file pane is normal either way). The tag remembers where its +# cursor was; the first time there is nothing to remember and it starts on +# Save. The tag's normal mode is the body's: w selects the "Save" span exactly +# as a body word motion does, and the execute key runs the word under the +# cursor and hands the body back — same keys as the body, so Tab by default +# (see config.look_key/exec_key). `:` again backs out instead, leaving the tag +# as it was. lines c.txt 6 start 31 100 c.txt wait 8000 Newcol Joincol @@ -18,7 +19,7 @@ key esc settle 100 stable 400 5000 snap edited -# `:` -> the tag, in normal mode, cursor on the tail's first cell +# `:` -> the tag, in normal mode, cursor on Save key : stable 400 5000 snap colon @@ -32,10 +33,9 @@ stable 600 8000 stable 400 5000 snap saved snapfile written /tmp/pardes-snap/tagcmd/cwd/c.txt -# `:` then Esc: back to the body with the tail untouched, nothing run +# `:` then `:`: back to the body with the tag untouched, nothing run key : stable 400 5000 -key esc -settle 100 +key : stable 400 5000 snap escaped diff --git a/test/snapshots/tagnav.golden b/test/snapshots/tagnav.golden index 52915940..3fdba9f2 100644 --- a/test/snapshots/tagnav.golden +++ b/test/snapshots/tagnav.golden @@ -22,39 +22,20 @@ == snap colon grid=100x31 cursor=28,2 |2: es-snap/tagnav/cwd/w.txt Save Tty Collapse Del /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte |18: ls -== snap right-tag grid=100x31 cursor=29,2 -== snap left-tag grid=100x31 cursor=28,2 -== snap down-tag grid=100x31 cursor=7,3 +== snap word grid=100x31 cursor=32,2 +== snap in-tag grid=100x31 cursor=34,2 +== snap right grid=100x31 cursor=54,5 |2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte -== snap up-tag grid=100x31 cursor=7,3 -== snap column-tag grid=100x31 cursor=7,3 -== snap up-edge grid=100x31 cursor=7,3 -== snap topbar-word grid=100x31 cursor=11,3 -== snap topbar-graphemes grid=100x31 cursor=7,4 -== snap column-down grid=100x31 cursor=7,5 -== snap back-down grid=100x31 cursor=7,5 -== snap arrows-still-motion grid=100x31 cursor=9,5 -== snap back-to-body grid=100x31 cursor=4,20 -|3: 1 alpha Last ls +|3: 1 alpha Right ls +== snap right-tag grid=100x31 cursor=70,2 +|2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll p/tagnav/cwd Tty Save Mode Filter Collapse Del +|3: 1 alpha ls +== snap left-tag grid=100x31 cursor=43,2 +|2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte +== snap back-to-body grid=100x31 cursor=7,3 == snap tty-on grid=100x31 cursor=54,5 |2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll$ /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte |3: 1 alpha $ ls |5: 3 gamma $ -== snap tty-tag grid=100x31 cursor=57,5 -|5: 3 gamma $ h:l -== snap tty-restored grid=100x31 cursor=4,20 -|3: 1 alpha $ ls Last -== snap topbar-dollar grid=100x31 cursor=48,17 -|3: 1 alpha $ ls -|17: p/tagnav/cwd Tty Save Mode Filter Collapse Del -== snap topbar-dump-word grid=100x31 cursor=25,17 -== snap topbar-exec grid=100x31 cursor=4,20 -|17: /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte -|29: /tmp/pardes-snap/tagnav/cwd/+Search Save Tty Co -|30: 1 -== snap topbar-restore-word grid=100x31 cursor=49,17 -|17: p/pardes-snap/tagnav/cwd Tty Save Mode Filter C -== snap topbar-restored grid=100x31 cursor=4,20 -|17: /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte -|27: /tmp/pardes-snap/tagnav/cwd/+Search Save Tty Co -|28: 1 +== snap tty-tag grid=100x31 cursor=90,2 +== snap tty-restored grid=100x31 cursor=54,5 diff --git a/test/snapshots/tagnav.snap b/test/snapshots/tagnav.snap index c375e644..eed808de 100644 --- a/test/snapshots/tagnav.snap +++ b/test/snapshots/tagnav.snap @@ -1,25 +1,22 @@ -# h/j/k/l ON A TAGLINE move focus BETWEEN taglines. A tag is a place in the -# LAYOUT, not just a line of text, so the four letters walk the layout and land -# on the neighbour's TAG (top row of the window), still in normal mode — you -# walk the taglines and never drop through a body. They run the SAME -# Left/Down/Up/Right builtins `SPC w h/j/k/l` and `Ctrl-w h/j/k/l` run: one -# focusDir, three routes to it. The ARROWS keep the in-tag grapheme motion, so -# no capability was traded away. +# A tag's normal mode is the body's: h/l/w move in the tag's own text, and +# moving between panes is the window keys' job from a tag as from a body -- +# there are no tag-only hops. `:` is the one key a tag and a body do not +# share: from the body it focuses the pane's own tag, from the tag it hands the +# keyboard back to the body. Each tag remembers its cursor; the first time +# there is nothing to remember and it starts on Save. # # Evidence is the `cursor=` header (the ACTIVE pane's cursor, which while a tag # is focused sits on THAT pane's tag row) plus each pane's layout box, which -# carries its BODY mode as one character: `•` normal, `^` insert, `$` tty. A -# tag edit parks the body mode rather than overwriting it, so the box keeps -# saying what the pane we left will be when we hop back off its tagline. +# carries its BODY mode as one character: ` ` normal, `^` insert, `$` tty. The +# tag has a mode of its own, so the box never changes while a tag is used. file w.txt alpha\nbeta\ngamma start 31 100 w.txt wait 8000 Newcol Joincol wait 8000 w.txt stable 700 20000 -# A FILE boots alone now, so the shell this script calls "the launch shell" is -# opened here: Alt-n opens it and focuses it, Alt-c puts it in a column of its -# own on the right, SPC w h comes back to the file. (`New`/`Newcol` open an -# empty +New scratch now, not a shell.) +# A FILE boots alone, so the launch shell is opened here: Alt-n opens it and +# focuses it, Alt-c puts it in a column of its own on the right, SPC w h comes +# back to the file. key a-n key a-c stable 700 15000 @@ -32,110 +29,51 @@ stable 700 15000 key space w k stable 400 5000 snap start -# `:` -> the file's OWN tagline, normal mode, parked at the tail's start +# `:` -> the file's OWN tagline, normal mode, on Save key : stable 400 5000 snap colon -# l -> right, onto the launch shell's TAGLINE (not its body) -key l -stable 400 5000 -snap right-tag -# h -> back left onto the file's tagline -key h -stable 400 5000 -snap left-tag -# j -> down onto the tagline of the shell under the file -key j -stable 400 5000 -snap down-tag -# k -> back up onto the file's -key k -stable 400 5000 -snap up-tag -# k visits the column tag first, then the workspace tag. Both stay in normal -# navigation mode; neither hop drops into a pane body. -key k -stable 400 5000 -snap column-tag -key k -stable 400 5000 -snap up-edge -# the bar speaks the tag's own one-line vocabulary: w to the next word start +# w selects in the tag the way it selects in a body key w stable 400 5000 -snap topbar-word -# h/l are plain graphemes up here — row 0 has no window to its left or right to -# walk to — and the arrows still mean what they always did -key l right +snap word +# l is a motion in the tag, not a hop to the next pane +key l l stable 400 5000 -snap topbar-graphemes -# j is the mirror of the k that got you here: back DOWN onto the topmost pane's -# tagline, still in normal mode, so the hop is a round trip -key j +snap in-tag +# the window keys move between panes from a tag as from a body: the tag lets +# go and the neighbour's BODY takes the keyboard +key c-w l +stable 400 5000 +snap right +# `:` there -> that pane's own tag, on its Save the first time +key : stable 400 5000 -snap column-down -key j +snap right-tag +# back left, and `:` finds the file's tag cursor where l left it +key c-w h stable 400 5000 -snap back-down -# the arrows are still in-tag motion: two rights walk two columns of the tail -key right right +key : stable 400 5000 -snap arrows-still-motion -key esc -settle 100 +snap left-tag +# `:` in the tag's normal mode: back to the body +key : stable 400 5000 snap back-to-body -# A TERMINAL MUST NOT LOSE ITS TTY MODE. Put the launch shell in raw tty mode -# (Ctrl-b), come back, then hop onto its tagline and off again: exitTagEdit -# restores the body mode the tag hijacked, and its box reads `$` throughout — -# during the hop too, because the box shows the PARKED mode, not the tag's. +# A TERMINAL KEEPS ITS TTY MODE. Put the launch shell in raw tty mode (Ctrl-b), +# click its tagline and come back: its box reads `$` throughout, because the +# tag's mode is the tag's own. key c-w l stable 400 5000 key c-b stable 700 15000 snap tty-on -key c-w h -stable 400 5000 -key : -key l +press left @Mode 3 +release left @Mode 3 stable 400 5000 snap tty-tag key esc settle 100 -stable 400 5000 -snap tty-restored -# Enter/Tab on the BAR runs the word under the cursor through the very dispatch -# a middle click on it uses, and leaves the bar FIRST — `Kill` lives up here, so -# a builtin that frees the session must never return into a focused topbar (the -# same hazard the pane-tag chord has with `Del`). `$` proves the destructive -# word is exactly last; four long-word steps back land on `Dump`, the visible -# non-destructive action used here. It grows a `Restore ` word, which is -# also the case where the line gets longer than the column you were parked on. -key c-w h -stable 400 5000 -key : -key k k -stable 400 5000 -key $ -stable 400 5000 -snap topbar-dollar -key B B B B -stable 400 5000 -snap topbar-dump-word -key enter -stable 700 15000 -snap topbar-exec -# THE DELETION HAZARD, from the bar itself: `Restore` frees every pane and -# swaps the core out from under the caller. Walk back onto the word the Dump -# just grew — B twice off the tail, because the LONG word motions are the ones -# that step over a path in one go — and run it. The bar drops focus BEFORE the -# builtin, so nothing reaches for state the swap already freed. key : -key k k stable 400 5000 -key $ B B -stable 400 5000 -snap topbar-restore-word -key enter -stable 900 15000 -snap topbar-restored +snap tty-restored diff --git a/test/snapshots/tagpath.golden b/test/snapshots/tagpath.golden index 1b798445..2ba1a2e6 100644 --- a/test/snapshots/tagpath.golden +++ b/test/snapshots/tagpath.golden @@ -8,12 +8,12 @@ | 4 line 4 | 5 == snap colon grid=100x31 cursor=38,2 -== snap col0 grid=100x31 cursor=3,2 -== snap sel-path grid=100x31 cursor=36,2 -== style sel-path grid=100x31 +== snap col0 grid=100x31 cursor=37,2 +== snap drag-cross grid=100x31 cursor=41,2 +== style drag-cross grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, |1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-99 d,#26362d, -|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-36 #f5f7ee,#3c614a, 37-58 #becfc4,#26362d, 59-99 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-10 #becfc4,#26362d, 11-41 #f5f7ee,#3c614a, 42-58 #becfc4,#26362d, 59-99 d,#26362d, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, @@ -42,16 +42,9 @@ |28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, |29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, |30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -== snap yanked-path grid=100x31 cursor=41,3 -|2: /tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del -|3: 1 l/tmp/pardes-snap/tagpath/cwd/c.txtine 1 -== snap drag-cross grid=100x31 cursor=41,2 -== style drag-cross grid=100x31 -|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-10 #becfc4,#26362d, 11-41 #f5f7ee,#3c614a, 42-60 #becfc4,#26362d, 61-99 d,#26362d, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-46 #e5eee5,#0d1410, 47-99 d,#0d1410, == snap name-draft grid=100x31 cursor=11,2 -|2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del -== snap name-cancelled grid=100x31 cursor=41,3 -|2: /tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del -== snap name-committed grid=100x31 cursor=41,3 +|2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del +== snap name-cancelled grid=100x31 cursor=7,3 +|2: /tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del +== snap name-committed grid=100x31 cursor=7,3 |2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del diff --git a/test/snapshots/tagpath.snap b/test/snapshots/tagpath.snap index cf431fa1..b9ef80e6 100644 --- a/test/snapshots/tagpath.snap +++ b/test/snapshots/tagpath.snap @@ -1,5 +1,8 @@ -# Filename drafts share the selectable tag coordinate space with commands. -# Escape cancels; Enter changes buffer identity, never renames a disk file. +# The path is part of the tag's text for the mouse -- a sweep selects across +# the path and the commands after it -- but never for the keyboard: the tag's +# cursor lives in its own text, so `0` goes to the start of that, not of the +# path. A click on the path drafts a new name there instead. Escape cancels; +# Enter changes buffer identity, never renames a disk file. lines c.txt 4 start 31 100 c.txt wait 8000 Newcol Joincol @@ -12,16 +15,6 @@ snap colon key 0 stable 400 5000 snap col0 -key E -stable 400 5000 -snap sel-path -snapstyle sel-path -key y -key esc -settle 100 -key p -stable 400 5000 -snap yanked-path # Sweep across the path / command boundary without injected padding. press left 12 3 drag left 30 3 @@ -33,17 +26,18 @@ snapstyle drag-cross key esc settle 100 key : -key 0 -key i +stable 400 5000 +# a click on the path is a name draft, the caret where it was clicked +press left 4 3 +release left 4 3 text /renamed stable 400 5000 snap name-draft key esc stable 400 5000 snap name-cancelled -key : -key 0 -key i +press left 4 3 +release left 4 3 text /renamed key enter stable 400 5000 diff --git a/test/snapshots/ttyclick.golden b/test/snapshots/ttyclick.golden index 719e3955..14344371 100644 --- a/test/snapshots/ttyclick.golden +++ b/test/snapshots/ttyclick.golden @@ -20,11 +20,7 @@ | ls | probe.txt == snap tty-tagedit grid=100x31 cursor=33,2 -|3: ls ls -|5: == snap tty-tagexit grid=100x31 cursor=4,5 -|3: $ ls ls -|5: $ == snap ins-bodyclick grid=100x31 cursor=11,4 |2: ^ /tmp/pardes-snap/ttyclick/cwd Tty Save Mode Fil /tmp/pardes-snap/ttyclick/cwd Tty Save Mode Fil |3: ls ls diff --git a/test/snapshots/ttyclick.snap b/test/snapshots/ttyclick.snap index 89ed5300..c125a231 100644 --- a/test/snapshots/ttyclick.snap +++ b/test/snapshots/ttyclick.snap @@ -1,7 +1,7 @@ # clicks in a shell pane never change its mode: a body click in raw tty -# keeps tty (before: the press dropped it to normal), a tag-edit round trip -# restores the mode it hijacked, and an insert-mode body click re-pins the -# cursor but stays insert. File panes keep the old behavior (click -> normal). +# keeps tty (before: the press dropped it to normal), a round trip through the +# tag leaves it alone (the tag has a mode of its own), and an insert-mode body +# click re-pins the cursor but stays insert. File panes keep the old behavior (click -> normal). # The mode is the character in each pane's layout box: `•` normal, `^` insert, # `$` tty. file probe.txt marker @@ -15,14 +15,16 @@ press left 10 5 release left 10 5 stable 400 5000 snap tty-bodyclick -# tag edit from tty: the box still reads `$` while the tag is being edited (the -# body mode is PARKED, which is the invariant), and Esc hands it back — a bug -# that lost it would show `•` in one snap or the other +# tag edit from tty: the box still reads `$` while the tag is typed into (the +# tag's mode is its own), and Esc then `:` hands the keyboard back — a bug +# that lost the body's mode would show `•` in one snap or the other press left @Tty 3 release left @Tty 3 stable 400 5000 snap tty-tagedit key esc +settle 100 +key : stable 400 5000 snap tty-tagexit # out of tty, into insert: a body click moves the cursor but keeps INS -- cgit v1.3 From 42748f92b77367db415c8b4d0f2e537a9e1ddde7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:13:11 -0300 Subject: Make the column and workspace tags Texts with the pane tag's keys The headers had their own one-line editor with its own keys: Enter always executed, h/l and J/K moved between headers and panes, Ctrl-c/x/v cut and pasted, and TagLine refused a newline that 9P accepted. They are now Texts like a pane's tag, with no prefix and a default until edited, so normal and insert mode, undo and the look and execute keys are the body's. Moving between them is the window keys' job: Up from a pane with nothing above it reaches its column's tag and then the workspace's, Down comes back, and Left and Right walk the column tags. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 1 + src/Text.zig | 19 +- src/builtins.zig | 37 +++- src/config.zig | 9 - src/dump.zig | 12 +- src/edit.zig | 45 +++-- src/gui/gui.zig | 5 +- src/layout.zig | 29 +-- src/mouse.zig | 44 ++-- src/normal.zig | 23 ++- src/pardes.zig | 471 ++++++++++++++++++------------------------- src/tag_line.zig | 42 ---- test/column_drag.zig | 22 +- test/panes.zig | 12 +- test/snapshots/tagnav.golden | 24 +++ test/snapshots/tagnav.snap | 43 ++++ 16 files changed, 426 insertions(+), 412 deletions(-) delete mode 100644 src/tag_line.zig (limited to 'src/Text.zig') diff --git a/src/File.zig b/src/File.zig index 2bf9f57d..22e3c434 100644 --- a/src/File.zig +++ b/src/File.zig @@ -654,6 +654,7 @@ pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const [] /// Use the file's line index only when `text` is its complete live content. /// Edit-buffer fragments and other temporary text retain modal's scan path. fn contentIndex(t: *Text, text: []const u8) ?[]const usize { + if (t.what != .body) return null; const pane = t.pane(); const f = if (pane.file) |*file| file else return null; if (text.ptr != f.content.ptr or text.len != f.content.len) return null; diff --git a/src/Text.zig b/src/Text.zig index 3e48a42e..d4b6d048 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -1,7 +1,8 @@ //! 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 is the -//! answer typed into a pane's prompt. Where a body's characters come from -- +//! 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 @@ -19,7 +20,7 @@ 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 }; +pub const What = enum { body, tag, input, column, workspace }; /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. pub const LineSel = struct { @@ -74,15 +75,25 @@ ed_undo_len: usize = 0, ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, ed_redo_len: usize = 0, -/// The window this text belongs to (acme's t->w). +/// The window this text belongs to (acme's t->w). A column's or the +/// workspace's tag belongs to no pane; nothing asks it for one. 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 => unreachable, }; } +/// 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.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 }; +} + /// 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. diff --git a/src/builtins.zig b/src/builtins.zig index 743573e4..74645376 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -735,27 +735,56 @@ pub const Grep = struct { // ---- the window group ---- +// The headers are above the panes in the same layout: Up from a pane with +// nothing above it reaches its column's tag, then the workspace's, and Down +// comes back the same way. Left and Right walk the column tags. + pub const Left = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .left); + if (c.p.header_focus) { + if (c.p.header_column) |column| if (column > 0) c.p.enterHeader(column - 1); + return; + } + _ = layout.focusDir(c.p, c.id, .left); } }; pub const Down = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .down); + if (c.p.header_focus) { + const column = layout.findPane(c.p, c.id); + if (c.p.header_column == null and c.p.columnBarHeight() > 0) + return c.p.enterHeader(if (column) |at| at.col else 0); + // Onto the top pane of the column the header stands over. + const col = c.p.header_column orelse if (column) |at| at.col else return; + c.p.exitHeader(); + if (col < c.p.ncol and c.p.col_n[col] > 0) c.p.active = c.p.col_panes[col][0]; + return; + } + _ = layout.focusDir(c.p, c.id, .down); } }; pub const Up = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .up); + if (c.p.header_focus) { + if (c.p.header_column != null and c.p.topBarHeight() > 0) c.p.enterHeader(null); + return; + } + if (layout.focusDir(c.p, c.id, .up)) return; + if (c.p.columnBarHeight() > 0) { + if (layout.findPane(c.p, c.id)) |at| c.p.enterHeader(at.col); + } else if (c.p.topBarHeight() > 0) c.p.enterHeader(null); } }; pub const Right = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .right); + if (c.p.header_focus) { + if (c.p.header_column) |column| if (column + 1 < c.p.ncol) c.p.enterHeader(column + 1); + return; + } + _ = layout.focusDir(c.p, c.id, .right); } }; diff --git a/src/config.zig b/src/config.zig index 38b87011..8c37a7ce 100644 --- a/src/config.zig +++ b/src/config.zig @@ -215,11 +215,6 @@ pub const jump_keys = [_]struct { chord: Chord, cmd: Builtin }{ .{ .chord = .{ .cp = 'i', .ctrl = true }, .cmd = .Forward }, }; -pub const topbar_down: []const Chord = &.{ .{ .cp = 'J' }, .{ .cp = Key.down } }; -pub const topbar_up: []const Chord = &.{ .{ .cp = 'K' }, .{ .cp = Key.up } }; -pub const topbar_left: []const Chord = &.{.{ .cp = 'h' }}; -pub const topbar_right: []const Chord = &.{.{ .cp = 'l' }}; - pub const leave_pane: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; @@ -255,8 +250,6 @@ pub const tag_insert = "^"; pub const tag_tty = "$"; pub const tag_image = "img"; -pub const tag_yank: []const Chord = &.{.{ .cp = 'y' }}; - pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; @@ -458,8 +451,6 @@ pub const line_end: []const Chord = &.{ .{ .cp = '$' }, .{ .cp = Key.end } }; pub const line_first_nonws: []const Chord = &.{.{ .cp = '^' }}; // Bare G does nothing; ge reaches the last line. pub const goto_line: []const Chord = &.{.{ .cp = 'G' }}; -pub const line_move_left: []const Chord = move_left; -pub const line_move_right: []const Chord = move_right; pub const half_page_down: []const Chord = &.{.{ .cp = 'd', .ctrl = true }}; pub const half_page_up: []const Chord = &.{.{ .cp = 'u', .ctrl = true }}; diff --git a/src/dump.zig b/src/dump.zig index 7112e1f0..aeb25a90 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -191,8 +191,10 @@ pub const State = struct { mounts: []const Mount = &.{}, }; +/// A header is a text like any other: it may hold newlines, but not a +/// carriage return or a NUL. fn validateTag(bar: []const u8) !void { - if (bar.len > limits.max_tag_tail or std.mem.indexOfAny(u8, bar, "\r\n\x00") != null or !std.unicode.utf8ValidateSlice(bar)) return error.BadDumpTag; + if (bar.len > limits.max_tag_tail or std.mem.indexOfAny(u8, bar, "\r\x00") != null or !std.unicode.utf8ValidateSlice(bar)) return error.BadDumpTag; } pub fn validate(state: State) !void { @@ -637,7 +639,7 @@ pub fn dumpState(p: *Pardes) !void { }; if (ids_len > 0) { columns[columns_len] = .{ - .tag = if (p.col_tags[c].custom) p.columnTag(c) else null, + .tag = p.col_tags[c].own, .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)), .panes = column_ids[c][0..ids_len], }; @@ -651,7 +653,7 @@ pub fn dumpState(p: *Pardes) !void { .screen = .{ .cols = p.screen_w, .rows = p.screen_h }, .active = slot_to_pane[p.active] orelse 0, .topbar = config.topbar_str, - .topbar_custom = if (p.global_tag.custom) p.global_tag.slice("") else null, + .topbar_custom = p.global_tag.own, .theme = p.theme().name, .locations_config = p.locations_config, .tree_context_tag_style = p.settings.tree_context_tag_style, @@ -788,9 +790,9 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo } p.ncol = @min(st.columns.len, MAX_COLS); p.col_serial = @splat(0); - if (st.topbar_custom) |bar| _ = p.global_tag.set(bar); + if (st.topbar_custom) |bar| p.global_tag.own = try p.gpa.dupe(u8, bar); for (st.columns[0..p.ncol], 0..) |col, c| { - if (col.tag) |bar| _ = p.col_tags[c].set(bar); + if (col.tag) |bar| p.col_tags[c].own = try p.gpa.dupe(u8, bar); const scaled = @as(f64, @floatCast(col.weight)) * @as(f64, @floatFromInt(column_weight_unit)); const bounded = @min(scaled, @as(f64, @floatFromInt(max_column_weight))); p.col_weight[c] = @max(1, @as(u64, @intFromFloat(@round(bounded)))); diff --git a/src/edit.zig b/src/edit.zig index 02e138e8..1822db31 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -72,10 +72,9 @@ pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) voi } pub fn applyPaste(p: *Pardes, bytes: []const u8) void { - if (p.topbar_col != null) { + if (p.focusedHeader()) |t| { p.clip_pending = null; - p.headerReplace(bytes); - return; + return pasteInto(p, t, bytes); } const req = p.clip_pending; p.clip_pending = null; @@ -96,15 +95,23 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - const t = if (pane.focus == .tag) &pane.tag else &pane.body; - if (t.what == .body and pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); + if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes); + if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); switch (if (req) |r| r.mode else .after) { - .after => pasteText(p, t, bytes, false, 1), - .before => pasteText(p, t, bytes, true, 1), - .replace => replaceWithText(p, t, bytes), + .after => pasteText(p, &pane.body, bytes, false, 1), + .before => pasteText(p, &pane.body, bytes, true, 1), + .replace => replaceWithText(p, &pane.body, bytes), } } +/// A paste into a tag or a header: typed at the caret while it is typed +/// into, after the cursor's cell in normal mode, as a body's paste is. +fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void { + if (bytes.len == 0) return; + if (t.mode == .insert) return insertKey(p, t, .{ .cp = bytes[0], .text = bytes }); + pasteText(p, t, bytes, false, 1); +} + pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { if (comptime pdf_enabled) if (pane.pdf) |pv| { if (pv.selection_text.len > 0) setClipboard(p, pv.selection_text); @@ -340,8 +347,12 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { } pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { - if (t.what == .tag) return Pardes.curTail(t.pane()); - if (t.what != .body) return t.own orelse ""; + switch (t.what) { + .body => {}, + .tag => return Pardes.curTail(t.pane()), + .input => return t.own orelse "", + .column, .workspace => return t.own orelse p.headerDefault(t.what), + } const pane = t.pane(); if (pane.file) |f| return f.content; if (pane.hasPdf()) { @@ -362,10 +373,10 @@ pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { /// Route shared edit operations to the characters `t` edits: its own, or /// for a body its file's content or its terminal's overlay. fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { - // A tag nobody has changed shows its default; the first edit makes that - // default its own text. - if (t.what == .tag and t.own == null) - t.own = p.gpa.dupe(u8, Pardes.defaultTail(t.pane())) catch return null; + // A tag or header nobody has changed shows its default; the first edit + // makes that default its own text. + if (t.what != .body and t.what != .input and t.own == null) + t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; @@ -1545,7 +1556,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { if (p.multi_on and !p.multi_first) return; switch (t.what) { .body => {}, - .tag => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), + .tag, .column, .workspace => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), // a prompt's answer is typed once and gone; it keeps no history .input => return, } @@ -1555,7 +1566,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { } pub fn doUndo(p: *Pardes, t: *Text) void { - if (t.what == .tag) return stepOwn(p, t, true); + if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, true); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); @@ -1563,7 +1574,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { } pub fn doRedo(p: *Pardes, t: *Text) void { - if (t.what == .tag) return stepOwn(p, t, false); + if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, false); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 97bbc816..dfd528a3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -7360,7 +7360,7 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard for (surface.cells[0..surface.cols], 0..) |*cell, i| { if (cellCodepoint(cell) != ' ') occupied = i + 1; } - const editing = p.topbar_col != null and p.header_column == null; + const editing = p.header_focus and p.header_column == null; const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); const region = if (occupied >= surface.cols) null else pet.lane( occupied, @@ -7412,8 +7412,7 @@ test "pet overlay stays beyond workspace text and vanishes while its tag is edit try std.testing.expect(x >= 20 * 8 - 0.01); try std.testing.expect(y >= 0 and y < 20); } - core.topbar_col = 0; - core.header_column = null; + core.enterHeader(null); builder.len = 0; appendWorkspacePet(&g, core, &surface, &builder); try std.testing.expectEqual(@as(usize, 0), builder.len); diff --git a/src/layout.zig b/src/layout.zig index 49da0207..54b89081 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -674,7 +674,8 @@ pub const MovePlacement = struct { above_h: u16, }; -pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) void { +/// Move the keyboard to the nearest pane in `dir`; false when there is none. +pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) bool { const a = p.rects[from]; var best: ?usize = null; var best_d: i32 = 0; @@ -701,11 +702,11 @@ pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) vo best_d = d; } } - if (best) |b| { - p.active = b; - // a count typed before the hop was meant for the pane you left - p.panes[b].?.body.normal.clear(); - } + const b = best orelse return false; + p.active = b; + // a count typed before the hop was meant for the pane you left + p.panes[b].?.body.normal.clear(); + return true; } pub fn columnBySerial(p: *const Pardes, serial: u32) ?usize { @@ -935,6 +936,7 @@ pub fn removePane(p: *Pardes, id: usize) void { if (p.col_n[c] == 0) { p.exitHeader(); if (p.ncol > 1) p.col_weight[if (c > 0) c - 1 else c + 1] +|= p.col_weight[c]; + p.col_tags[c].deinit(p.gpa); var j = c; while (j + 1 < p.ncol) : (j += 1) { p.col_panes[j] = p.col_panes[j + 1]; @@ -944,7 +946,7 @@ pub fn removePane(p: *Pardes, id: usize) void { p.col_serial[j] = p.col_serial[j + 1]; } p.ncol -= 1; - p.col_tags[p.ncol] = .{}; + p.col_tags[p.ncol] = .{ .what = .column }; p.col_serial[p.ncol] = 0; } } @@ -958,6 +960,7 @@ pub fn joinCol(p: *Pardes) void { p.col_weight[dst] +|= p.col_weight[c]; for (0..p.col_n[c]) |k| p.col_panes[dst][p.col_n[dst] + k] = p.col_panes[c][k]; p.col_n[dst] += p.col_n[c]; + p.col_tags[c].deinit(p.gpa); var j = c; while (j + 1 < p.ncol) : (j += 1) { p.col_panes[j] = p.col_panes[j + 1]; @@ -967,7 +970,7 @@ pub fn joinCol(p: *Pardes) void { p.col_serial[j] = p.col_serial[j + 1]; } p.ncol -= 1; - p.col_tags[p.ncol] = .{}; + p.col_tags[p.ncol] = .{ .what = .column }; p.col_serial[p.ncol] = 0; } @@ -1017,7 +1020,7 @@ pub fn splitColumn(p: *Pardes, source_id: usize, id: usize, before: bool) bool { p.col_serial[j] = p.col_serial[j - 1]; } p.col_weight[c] = new_weight; - p.col_tags[c] = .{}; + p.col_tags[c] = .{ .what = .column }; p.col_serial[c] = 0; p.col_panes[c][0] = id; p.col_n[c] = 1; @@ -2245,25 +2248,25 @@ test "column reorder moves only crossed state and preserves weights" { p.col_weight[c] = c * 13 + 7; p.col_serial[c] = @intCast(c + 10); p.col_panes[c][0] = c; - p.col_tags[c].saved_col = @intCast(c + 20); + p.col_tags[c].cur_col = @intCast(c + 20); } compute(p); const original_weights = p.col_weight; const outer_x = p.col_x[0]; const outer_w = p.col_w[0]; + p.header_focus = true; p.header_column = 1; - p.topbar_col = 23; p.header_scroll = 9; reorderColumn(p, 1, 3); try std.testing.expectEqual(original_weights[1], p.col_weight[3]); try std.testing.expectEqual(original_weights[2], p.col_weight[1]); try std.testing.expectEqual(@as(u32, 11), p.col_serial[3]); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(@as(?u16, 23), p.topbar_col); + try std.testing.expectEqual(@as(i32, 21), p.focusedHeader().?.cur_col); try std.testing.expectEqual(@as(usize, 9), p.header_scroll); try std.testing.expectEqual(outer_x, p.col_x[0]); try std.testing.expectEqual(outer_w, p.col_w[0]); reorderColumn(p, 3, 1); try std.testing.expectEqualSlices(u64, original_weights[0..4], p.col_weight[0..4]); - try std.testing.expectEqual(@as(?u16, 21), p.col_tags[1].saved_col); + try std.testing.expectEqual(@as(i32, 21), p.col_tags[1].cur_col); } diff --git a/src/mouse.zig b/src/mouse.zig index ae047c58..343051b0 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -292,9 +292,17 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } } if (p.header_drag and m.button == config.select_button and (m.kind == .drag or m.kind == .release)) { + const t = p.focusedHeader() orelse { + p.header_drag = false; + return; + }; const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; - const bar = p.headerText(); - p.topbar_col = @intCast(@min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll))); + const bar = modal.lineSlice(edit.flatSurface(p, t) catch return, 0); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); + // the anchor stays where the press put it + t.cur_row = 0; + t.cur_col = @intCast(at); + t.vsel.active = t.vsel.col != t.cur_col; if (m.kind == .release) p.header_drag = false; return; } @@ -318,25 +326,25 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { }; if (column == null or mcol < x) return; } - if (p.header_column != column) { - p.rememberHeader(); - p.topbar_col = null; - p.header_anchor = null; - p.header_scroll = 0; - } - p.header_column = column; - const bar = p.headerText(); - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); + const t = if (column) |c| &p.col_tags[c] else &p.global_tag; + const focused = p.header_focus and p.header_column == column; + const bar = modal.lineSlice(edit.flatSurface(p, t) catch return, 0); + const scroll = if (focused) p.header_scroll else 0; + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + scroll)); if (m.button == config.select_button) { - p.topbar_col = @intCast(at); - p.header_anchor = @intCast(at); - p.header_insert = true; + // A clicked header is typed straight into, as a clicked tag is. + if (!focused) p.enterHeader(column); + t.mode = .insert; + t.cur_row = 0; + t.cur_col = @intCast(at); + t.vsel = .{ .active = false, .row = 0, .col = @intCast(at) }; p.header_drag = true; } else { - const selected = if (p.topbar_col) |cur| blk: { - const a = p.header_anchor orelse cur; - break :blk if (at >= @min(a, cur) and at < @max(a, cur)) bar[@min(a, cur)..@max(a, cur)] else wordAtCol(bar, at); - } else wordAtCol(bar, at); + const span = if (focused) Pardes.headerSelection(t, bar) else null; + const selected = if (span) |sp| + (if (at >= sp.lo and at < sp.hi) bar[sp.lo..sp.hi] else wordAtCol(bar, at)) + else + wordAtCol(bar, at); const word = p.scratch.allocator().dupe(u8, selected) catch return; p.exitHeader(); if (word.len > 0) { diff --git a/src/normal.zig b/src/normal.zig index e4fa075d..630f7689 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -173,7 +173,9 @@ const Replay = union(enum) { pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { const id = p.active; - const serial = t.pane().serial; + // a header belongs to no pane and cannot go away under the replay + const owner: ?*Pane = if (t.what == .column or t.what == .workspace) null else t.pane(); + const serial = if (owner) |pane| pane.serial else 0; // the whole selection in text coordinates, document order. t.sels // is already ordered, so this only slots the primary into place. var list: [Text.max_selections]Text.SelRange = undefined; @@ -256,8 +258,11 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { p.multi_first = false; if (p.multi_stop) { p.multi_stop = false; - const pn = p.panes[id] orelse return; - if (pn.serial == serial) t.nsel = 0; + if (owner != null) { + const pn = p.panes[id] orelse return; + if (pn.serial != serial) return; + } + t.nsel = 0; return; } const text = edit.flatSurface(p, t) catch return; @@ -284,7 +289,9 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { } fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { - const pane = t.pane(); + // What reaches past the text -- a builtin, a search, a language query -- + // acts for the pane the text belongs to; a header's is the active one. + const pane = if (t.what == .column or t.what == .workspace) p.panes[p.active] orelse return else t.pane(); const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { @@ -547,9 +554,11 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void }, // `:` is the one key a tag and a body do not share: it moves the // keyboard between them. - .command_line => if (t.what == .tag) { - pane.focus = .body; - } else p.enterTag(pane), + .command_line => switch (t.what) { + .tag => pane.focus = .body, + .column, .workspace => p.exitHeader(), + .body, .input => p.enterTag(pane), + }, .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), .search_step => |direction| return look.lookWalk( diff --git a/src/pardes.zig b/src/pardes.zig index ce7c7065..60c41f50 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -258,7 +258,6 @@ const max_column_weight = layout.max_column_weight; pub const MAX_JUMPS = 64; pub const TOPBAR_H: u16 = 1; pub const COLBAR_H: u16 = 1; -pub const TagLine = @import("tag_line.zig").Line; pub const BOX_H: u16 = 1; pub const TAG_GAP: u16 = 1; pub const TAG_TEXT_INSET: u16 = config.GUTTER + TAG_GAP; @@ -2702,17 +2701,19 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = separator, .c1 = separator, .r0 = BOX_H, .r1 = BOX_H }) == null); } -test "editable workspace and column tags replace selections and persist" { +test "editable workspace and column tags are typed into and persist" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("untouched\n"); p.acknowledgePanelPresentation(&.{}); try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); + // a sweep over a header is its selection, the caret where it ended p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 0, .row = 0 } }); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 6, .row = 0 } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 6, .row = 0 } }); - p.update(.{ .key = .{ .cp = 'H', .text = "Help" } }); - try std.testing.expect(std.mem.startsWith(u8, p.global_tag.slice(""), "Help Joincol")); + try std.testing.expect(p.global_tag.vsel.active and p.global_tag.vsel.col == 0 and p.global_tag.cur_col == 6); + p.update(.{ .key = .{ .cp = 'H', .text = " Help" } }); + try std.testing.expect(std.mem.startsWith(u8, p.global_tag.own.?, "Newcol Help Joincol")); p.update(.{ .key = .{ .cp = Key.escape } }); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); @@ -2726,9 +2727,10 @@ test "editable workspace and column tags replace selections and persist" { try dump.dumpState(p); const restored = try dump.restore(p, p.dump_out.?); defer restored.deinit(); - try std.testing.expectEqualStrings(p.global_tag.slice(""), restored.global_tag.slice("")); + try std.testing.expectEqualStrings(p.global_tag.own.?, restored.global_tag.own.?); try std.testing.expectEqualStrings(p.columnTag(0), restored.columnTag(0)); - try std.testing.expect(p.col_tags[0].set("")); + p.gpa.free(p.col_tags[0].own.?); + p.col_tags[0].own = try p.gpa.dupe(u8, ""); try dump.dumpState(p); const empty = try dump.restore(p, p.dump_out.?); defer empty.deinit(); @@ -2739,11 +2741,11 @@ test "column tags follow their column through split and close" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("left\n"); - try std.testing.expect(p.col_tags[0].set("Left Find")); + p.col_tags[0].own = try p.gpa.dupe(u8, "Left Find"); _ = exec.execute(p, 0, "Newcol"); try std.testing.expectEqual(@as(usize, 2), p.ncol); try std.testing.expectEqualStrings("Left Find", p.columnTag(0)); - try std.testing.expect(p.col_tags[1].set("Right Grep")); + p.col_tags[1].own = try p.gpa.dupe(u8, "Right Grep"); p.active = p.col_panes[0][0]; layout.joinCol(p); try std.testing.expectEqual(@as(usize, 1), p.ncol); @@ -2770,7 +2772,7 @@ test "column tags render edit hover and scroll from the column edge" { try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, hovered.at(x, TOPBAR_H).style.bg); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = TOPBAR_H } }); try std.testing.expectEqual(column, p.header_column.?); - try std.testing.expectEqual(@as(u16, 0), p.topbar_col.?); + try std.testing.expectEqual(@as(i32, 0), p.focusedHeader().?.cur_col); const at_start = try p.render(frame.allocator()); try std.testing.expectEqual(x, at_start.cursor.?.x); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = x + 3, .row = TOPBAR_H } }); @@ -2778,13 +2780,15 @@ test "column tags render edit hover and scroll from the column edge" { const selected = try p.render(frame.allocator()); for (0..3) |offset| try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, selected.at(x + @as(u16, @intCast(offset)), TOPBAR_H).style.bg); - p.update(.{ .key = .{ .cp = 'H', .text = "Help" } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(column), "Help Tty")); + p.update(.{ .key = .{ .cp = Key.home } }); + p.update(.{ .key = .{ .cp = 'H', .text = "Help " } }); + try std.testing.expect(std.mem.startsWith(u8, p.columnTag(column), "Help New Tty")); const edited = try p.render(frame.allocator()); - try std.testing.expectEqual(x + 4, edited.cursor.?.x); + try std.testing.expectEqual(x + 5, edited.cursor.?.x); // Only the text viewport participates in caret reveal. const long: [80]u8 = @splat('a'); - try std.testing.expect(p.col_tags[column].set(long[0 .. width - 1])); + if (p.col_tags[column].own) |own| p.gpa.free(own); + p.col_tags[column].own = try p.gpa.dupe(u8, long[0 .. width - 1]); p.update(.{ .key = .{ .cp = Key.end } }); const at_end = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 0), p.header_scroll); @@ -2827,7 +2831,7 @@ test "header clicks beyond text append and long UTF-8 tags reveal their caret" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 12, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("body\n"); - try std.testing.expect(p.col_tags[0].set("New")); + p.col_tags[0].own = try p.gpa.dupe(u8, "New"); p.acknowledgePanelPresentation(&.{}); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 40, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 40, .row = TOPBAR_H } }); @@ -2856,21 +2860,21 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12, .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("unchanged body\n"); - try std.testing.expect(p.col_tags[0].set("New Help")); + p.col_tags[0].own = try p.gpa.dupe(u8, "New Help"); p.acknowledgePanelPresentation(&.{}); const shown = p.rects[0]; try std.testing.expectEqual(TOPBAR_H + COLBAR_H, shown.y); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); - try std.testing.expect(p.header_column != null and p.topbar_col != null); + try std.testing.expect(p.header_focus and p.header_column != null); p.update(.{ .command = "ColumnTags" }); try std.testing.expect(!p.settings.column_tags); try std.testing.expectEqual(@as(u16, 0), p.columnBarHeight()); try std.testing.expectEqual(TOPBAR_H, p.rects[0].y); try std.testing.expectEqual(shown.h + COLBAR_H, p.rects[0].h); - try std.testing.expect(p.header_column == null and p.topbar_col == null); - try std.testing.expect(p.header_anchor == null and !p.header_drag); + try std.testing.expect(!p.header_focus and p.header_column == null); + try std.testing.expect(!p.header_drag); try std.testing.expectEqualStrings("New Help", p.columnTag(0)); p.update(.{ .command = "ColumnTags" }); @@ -2884,25 +2888,63 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin try std.testing.expect(p.settings.column_tags); try std.testing.expectEqual(@as(u16, 0), p.columnBarHeight()); try std.testing.expectEqual(TOPBAR_H, p.rects[0].y); - try std.testing.expect(p.header_column == null and p.topbar_col == null); + try std.testing.expect(!p.header_focus and p.header_column == null); p.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); try std.testing.expectEqual(shown, p.rects[0]); try std.testing.expectEqualStrings("New Help", p.columnTag(0)); try std.testing.expectEqualStrings("unchanged body\n", pane.file.?.content); } -test "normal header Enter executes its command rather than searching for it" { +test "a header's execute key runs the word under its cursor and lets go of the keyboard first" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 12, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("body\n"); - p.topbar_col = @intCast(std.mem.indexOf(u8, config.topbar_str, "Dump").?); - p.header_insert = false; - p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(p.topbar_col == null); + p.enterHeader(null); + p.global_tag.cur_col = @intCast(std.mem.indexOf(u8, config.topbar_str, "Dump").?); + p.update(.{ .key = .{ .cp = Key.tab } }); + try std.testing.expect(!p.header_focus); try std.testing.expect(p.dump_out != null); try std.testing.expectEqual(@as(usize, 1), p.col_n[0]); } +test "window keys walk from a pane up through the column and workspace tags and back" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("body\n"); + p.newScratchColumn(0); + p.sync(); + p.active = p.col_panes[0][0]; + const window = struct { + fn key(core: *Pardes, letter: u21) void { + core.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + core.update(.{ .key = .{ .cp = letter } }); + } + }; + // Up from the top pane: its column's tag, in normal mode; `:` there is + // the way back to the body. + window.key(p, 'k'); + try std.testing.expect(p.header_focus and p.header_column.? == 0); + try std.testing.expectEqual(Text.Mode.normal, p.col_tags[0].mode); + p.update(.{ .key = .{ .cp = 'w' } }); + try std.testing.expect(p.col_tags[0].cur_col > 0); + const remembered = p.col_tags[0].cur_col; + window.key(p, 'l'); + try std.testing.expect(p.header_focus and p.header_column.? == 1); + window.key(p, 'h'); + try std.testing.expectEqual(remembered, p.col_tags[0].cur_col); + window.key(p, 'k'); + try std.testing.expect(p.header_focus and p.header_column == null); + window.key(p, 'j'); + try std.testing.expect(p.header_focus and p.header_column.? == 0); + window.key(p, 'j'); + try std.testing.expect(!p.header_focus); + try std.testing.expectEqual(p.col_panes[0][0], p.active); + window.key(p, 'k'); + p.update(.{ .key = .{ .cp = ':' } }); + try std.testing.expect(!p.header_focus and p.panes[p.active].?.focus == .body); + try std.testing.expectEqualStrings("body\n", p.panes[0].?.file.?.content); +} + pub const Mouse = struct { /// The host has inverted a compact body layer. Physical col/row still /// route pane chrome; these coordinates address the pane's logical text. @@ -3656,10 +3698,12 @@ pub const Pardes = struct { col_weight: [MAX_COLS]u64 = @splat(column_weight_unit), col_panes: [MAX_COLS][MAX_PANES]usize = undefined, col_n: [MAX_COLS]usize = @splat(0), - col_tags: [MAX_COLS]TagLine = @splat(.{}), + /// Each column's tag and the workspace's: Texts like a pane's tag, with + /// no prefix, showing a default until someone edits them. + col_tags: [MAX_COLS]Text = @splat(.{ .what = .column }), col_serial: [MAX_COLS]u32 = @splat(0), next_column_serial: u32 = 1, - global_tag: TagLine = .{}, + global_tag: Text = .{ .what = .workspace }, // derived each sync rects: [MAX_PANES]Rect = @splat(.{}), col_x: [MAX_COLS]u16 = undefined, @@ -3716,10 +3760,11 @@ pub const Pardes = struct { leader_on: bool = false, leader_keys: [4]u8 = undefined, leader_n: u8 = 0, - topbar_col: ?u16 = null, + /// The keyboard is on a header: the column tag `header_column` names, or + /// the workspace's when that is null. + header_focus: bool = false, header_column: ?usize = null, - header_insert: bool = false, - header_anchor: ?u16 = null, + /// A mouse sweep is extending the focused header's selection. header_drag: bool = false, header_scroll: usize = 0, ov_pinch_scale: f32 = 1.0, @@ -3951,6 +3996,8 @@ pub const Pardes = struct { slot.* = null; }; const gpa = p.gpa; + for (&p.col_tags) |*t| t.deinit(gpa); + p.global_tag.deinit(gpa); if (p.yank) |y| gpa.free(y); if (p.dump_out) |d| gpa.free(d); p.fallback.deinit(); @@ -3994,13 +4041,21 @@ pub const Pardes = struct { return a; } - /// the topbar line: the fixed builtins, plus `Restore ` once a dump - /// exists — render and click dispatch must agree on this exact string - fn topbar(p: *Pardes, buf: []u8) []const u8 { - if (p.global_tag.custom) return p.global_tag.slice(""); - if (p.last_dump) |d| - return std.fmt.bufPrint(buf, config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str; - return config.topbar_str; + /// What a column's tag says until someone edits it. + pub const column_tag_default = "New Tty Find Grep Joincol Delcol"; + + /// What a header says until someone edits it: for the workspace the + /// fixed builtins, plus `Restore ` once a dump exists. + pub fn headerDefault(p: *Pardes, what: Text.What) []const u8 { + if (what == .column) return column_tag_default; + const d = p.last_dump orelse return config.topbar_str; + return std.fmt.allocPrint(p.scratch.allocator(), config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str; + } + + /// the topbar line -- render and click dispatch must agree on this exact + /// string + fn topbar(p: *Pardes) []const u8 { + return p.global_tag.own orelse p.headerDefault(.workspace); } /// The workspace tag row's height: `TOPBAR_H` while the setting keeps @@ -4016,43 +4071,32 @@ pub const Pardes = struct { } pub fn columnTag(p: *const Pardes, c: usize) []const u8 { - return p.col_tags[c].slice("New Tty Find Grep Joincol Delcol"); + return p.col_tags[c].own orelse column_tag_default; } - pub fn headerText(p: *Pardes) []const u8 { - if (p.header_column) |c| return if (c < p.ncol) p.columnTag(c) else ""; - var buf: [1200]u8 = undefined; - return p.scratch.allocator().dupe(u8, p.topbar(&buf)) catch ""; + /// The header with the keyboard, when one has it. + pub fn focusedHeader(p: *Pardes) ?*Text { + if (!p.header_focus) return null; + if (p.header_column) |c| return if (c < p.ncol) &p.col_tags[c] else null; + return &p.global_tag; } fn revealHeader(p: *Pardes) void { - const cur = p.topbar_col orelse { + const t = p.focusedHeader() orelse { p.header_scroll = 0; return; }; - const text = p.headerText(); + const text = edit.flatSurface(p, t) catch return; + const line = modal.lineSlice(text, 0); const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w); - const col = panes.File.rawDisplayCol(text, @min(cur, text.len)); + const col = panes.File.rawDisplayCol(line, @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len)); if (col < p.header_scroll) p.header_scroll = col; if (col >= p.header_scroll + width) p.header_scroll = col -| (width -| 1); - var raw = panes.File.rawAtDisplay(text, p.header_scroll); - p.header_scroll = panes.File.rawDisplayCol(text, raw); + var raw = panes.File.rawAtDisplay(line, p.header_scroll); + p.header_scroll = panes.File.rawDisplayCol(line, raw); if (width > 0 and col >= p.header_scroll + width) { - raw = modal.nextGrapheme(text, raw); - p.header_scroll = panes.File.rawDisplayCol(text, raw); - } - } - - pub fn headerReplace(p: *Pardes, bytes: []const u8) void { - const cur = p.topbar_col orelse return; - const anchor = p.header_anchor orelse cur; - const lo = @min(cur, anchor); - const hi = @max(cur, anchor); - const fallback = p.headerText(); - const line = if (p.header_column) |c| &p.col_tags[c] else &p.global_tag; - if (line.replace(fallback, lo, hi, bytes)) { - p.topbar_col = @intCast(lo + bytes.len); - p.header_anchor = null; + raw = modal.nextGrapheme(line, raw); + p.header_scroll = panes.File.rawDisplayCol(line, raw); } } @@ -4109,9 +4153,7 @@ pub const Pardes = struct { if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); if (pane.input.own) |text| p.gpa.free(text); - if (pane.tag.own) |text| p.gpa.free(text); - for (pane.tag.ed_undo[0..pane.tag.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); - for (pane.tag.ed_redo[0..pane.tag.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); + pane.tag.deinit(p.gpa); for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); @@ -4921,165 +4963,34 @@ pub const Pardes = struct { return true; } - fn lineMotion(text: []const u8, cur: usize, key: Key) ?modal.Selection { - const target: ?usize = if (hit(key, config.line_move_left)) - modal.prevGrapheme(text, cur) - else if (hit(key, config.line_move_right)) - modal.nextGrapheme(text, cur) - else if (hit(key, config.line_start)) - 0 - else if (hit(key, config.line_end)) - modal.prevGrapheme(text, text.len) - else if (hit(key, config.line_first_nonws)) - modal.firstNonWs(text) - else - null; - if (target) |t| return .{ .anchor = t, .head = t }; - const wt: ?modal.WordTarget = if (hit(key, config.next_word_start)) - .next_word_start - else if (hit(key, config.prev_word_start)) - .prev_word_start - else if (hit(key, config.next_word_end)) - .next_word_end - else if (hit(key, config.next_long_word_start)) - .next_long_word_start - else if (hit(key, config.prev_long_word_start)) - .prev_long_word_start - else if (hit(key, config.next_long_word_end)) - .next_long_word_end - else - null; - const t = wt orelse return null; - return modal.moveWord(text, .{ .anchor = cur, .head = modal.nextGrapheme(text, cur) }, 1, t); - } - - pub fn rememberHeader(p: *Pardes) void { - const col = p.topbar_col orelse return; - const line = if (p.header_column) |c| &p.col_tags[c] else &p.global_tag; - line.saved_col = col; - } - pub fn exitHeader(p: *Pardes) void { - p.rememberHeader(); - p.topbar_col = null; + p.header_focus = false; p.header_column = null; - p.header_anchor = null; p.header_drag = false; p.header_scroll = 0; } - fn enterHeader(p: *Pardes, column: ?usize) void { - p.rememberHeader(); + /// 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. + pub fn enterHeader(p: *Pardes, column: ?usize) void { + p.exitHeader(); + if (p.panes[p.active]) |pane| pane.focus = .body; + p.header_focus = true; p.header_column = column; - const line = if (column) |c| &p.col_tags[c] else &p.global_tag; - const text = p.headerText(); - p.topbar_col = @intCast(modal.graphemeStart(text, @min(line.saved_col orelse 0, text.len))); - p.header_insert = false; - p.header_anchor = null; - p.header_drag = false; - p.header_scroll = 0; - } - - fn topbarKey(p: *Pardes, key: Key) void { - const bar = p.headerText(); - // the line GROWS a `Restore ` word the moment a dump lands, so - // the column is clamped against the live line on every use - const cur: usize = @min(@as(usize, p.topbar_col orelse return), bar.len); - if (hit(key, config.escape) or (!p.header_insert and hit(key, &.{.{ .cp = 'j' }}))) { - p.exitHeader(); - return; - } - if (hit(key, config.look_key) or hit(key, config.exec_key)) { - const a = p.header_anchor orelse @as(u16, @intCast(cur)); - const word = if (a != cur) bar[@min(a, cur)..@max(a, cur)] else wordAtCol(bar, cur); - p.exitHeader(); - if (word.len > 0) { - if (!p.header_insert) { - // Preserve the workspace tag's keyboard command semantics. - _ = exec.execute(p, p.active, word); - } else exec.runBuiltin(p, if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", word); - } - return; - } - if (p.header_insert) { - if (key.ctrl and key.cp == 'v') { - p.emit(.read_clipboard); - return; - } - if (key.ctrl and (key.cp == 'c' or key.cp == 'x')) { - const anchor = p.header_anchor orelse @as(u16, @intCast(cur)); - if (anchor != cur) { - edit.setClipboard(p, bar[@min(anchor, cur)..@max(anchor, cur)]); - if (key.cp == 'x') p.headerReplace(""); - } - return; - } - if (key.text.len > 0 and !key.ctrl and !key.alt) { - p.headerReplace(key.text); - return; - } - if (key.cp == Key.backspace or key.cp == Key.delete) { - if (p.header_anchor == null or p.header_anchor.? == cur) p.header_anchor = @intCast(if (key.cp == Key.backspace) modal.prevGrapheme(bar, cur) else modal.nextGrapheme(bar, cur)); - p.headerReplace(""); - return; - } - const next: ?usize = switch (key.cp) { - Key.left => modal.prevGrapheme(bar, cur), - Key.right => modal.nextGrapheme(bar, cur), - Key.home => 0, - Key.end => bar.len, - else => null, - }; - if (next) |at| { - if (key.shift) { - if (p.header_anchor == null) p.header_anchor = @intCast(cur); - } else p.header_anchor = null; - p.topbar_col = @intCast(at); - } - return; - } - if (hit(key, config.insert) or hit(key, config.append) or hit(key, config.insert_line_start) or hit(key, config.insert_line_end)) { - p.header_insert = true; - p.topbar_col = @intCast(if (hit(key, config.insert_line_end)) bar.len else if (hit(key, config.insert_line_start)) 0 else if (hit(key, config.append)) modal.nextGrapheme(bar, cur) else cur); - return; - } - if (hit(key, config.topbar_down)) { - if (p.header_column == null and p.columnBarHeight() > 0) { - p.enterHeader(if (layout.findPane(p, p.active)) |f| f.col else 0); - return; - } - var dest: ?usize = null; - for (p.panes, 0..) |slot, i| { - if (slot == null or p.rects[i].y != p.topBarHeight() + p.columnBarHeight()) continue; - if (p.header_column) |c| if (p.rects[i].x != p.col_x[c]) continue; - if (i == p.active) { - dest = i; - break; - } - if (dest == null or p.rects[i].x < p.rects[dest.?].x) dest = i; - } - const d = dest orelse return; - const pane = p.panes[d].?; - p.exitHeader(); - p.active = d; - p.enterTag(pane); - return; - } - if (hit(key, config.topbar_up)) { - p.enterHeader(null); - return; - } - const col: ?usize = if (hit(key, config.topbar_left)) - modal.prevGrapheme(bar, cur) - else if (hit(key, config.topbar_right)) - modal.nextGrapheme(bar, cur) - else if (lineMotion(bar, cur, key)) |r| - modal.selectionCursor(bar, r) - else - null; - // never past the last cell: there is nothing to append up here, so the - // block cursor stays ON a character (which is where `$` already lands) - if (col) |c| p.topbar_col = @intCast(@min(c, modal.prevGrapheme(bar, bar.len))); + const t = p.focusedHeader() orelse return p.exitHeader(); + const text = edit.flatSurface(p, t) catch ""; + 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.msel.active = false; + t.nsel = 0; + t.select = false; + t.append_at = null; + t.mode = .normal; + t.normal.clear(); } /// Cycle only the body modes supported by this pane. @@ -5129,9 +5040,9 @@ pub const Pardes = struct { if (hit(key, config.del_below)) exec.runBuiltin(p, .Del, id, "", "j"); return; } - if (p.topbar_col != null) return p.topbarKey(key); const pane = p.panes[p.active] orelse return; - if (pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { + const header = p.focusedHeader(); + if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) @@ -5169,14 +5080,15 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - const t = if (pane.focus == .tag) &pane.tag else &pane.body; - if (hit(key, config.window_prefix) and t.mode != .insert and pane.prompt == .none) { + const t = header orelse if (pane.focus == .tag) &pane.tag else &pane.body; + if (hit(key, config.window_prefix) and t.mode != .insert and (header != null or pane.prompt == .none)) { p.ctrl_w_pending = true; return; } // global window ops (any mode): Alt-n new terminal below, Alt-c move // the active terminal into a fresh column if (hit(key, config.new_shell_below)) { + p.exitHeader(); const free = p.freeSlot() orelse return; const nt = p.newShell(free, "") catch return; nt.greet = true; @@ -5189,9 +5101,12 @@ pub const Pardes = struct { return; } for (config.jump_keys) |jk| { - if (hit(key, &.{jk.chord})) return exec.runBuiltin(p, jk.cmd, p.active, "", null); + if (!hit(key, &.{jk.chord})) continue; + p.exitHeader(); + return exec.runBuiltin(p, jk.cmd, p.active, "", null); } if (hit(key, config.pane_to_new_column)) { + p.exitHeader(); const f = layout.findPane(p, p.active).?; if (p.ncol < MAX_COLS and p.col_n[f.col] > 1) { _ = layout.splitColumn(p, p.active, p.active, false); @@ -5203,7 +5118,7 @@ pub const Pardes = struct { if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } - if (pane.prompt == .name) { + if (header == null and pane.prompt == .name) { // Enter or the execute key commits the draft and the keyboard // goes back to the body; Esc drops it. if (hit(key, config.look_key) or hit(key, config.exec_key)) { @@ -5218,7 +5133,7 @@ pub const Pardes = struct { edit.handleInsert(p, &pane.input, key); return; } - if (pane.prompt != .none) { + if (header == null and pane.prompt != .none) { if (hit(key, config.search_submit) or hit(key, config.escape)) { const submit = hit(key, config.search_submit); switch (pane.prompt) { @@ -5241,22 +5156,24 @@ pub const Pardes = struct { } if (t.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; - if (pane.focus == .tag) { + if (t.what != .body) { // An explicit selection, else the word under the cursor in the - // tag as it is shown: the prefix is part of what a word is. - const tag = p.tagText(p.scratch.allocator(), pane) catch return; - const tail = curTail(pane); - const range = t.primaryRange(tail, 0); + // text as it is shown: a tag's prefix is part of what a word is. + const arena = p.scratch.allocator(); + const own = arena.dupe(u8, edit.flatSurface(p, t) catch return) catch return; + const shown = if (t.what == .tag) p.tagText(arena, pane) catch return else own; + const range = t.primaryRange(own, 0); const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); const txt = if ((t.vsel.active and t.vsel.explicit) or t.msel.active) - tail[lo..hi] + own[lo..hi] else word: { - const b = config.wordBounds(tag, tag.len - tail.len + modal.selectionCursor(tail, range)); - break :word tag[b.lo..b.hi]; + const b = config.wordBounds(shown, shown.len - own.len + modal.selectionCursor(own, range)); + break :word shown[b.lo..b.hi]; }; - // Out of the tag FIRST: Del frees the pane. - pane.focus = .body; + // Out of the tag or header FIRST: Del frees the pane, Kill + // and Restore the whole session. + if (header != null) p.exitHeader() else pane.focus = .body; if (txt.len > 0) exec.runBuiltin(p, cmd, p.active, "", txt); return; } @@ -5899,7 +5816,7 @@ pub const Pardes = struct { const pane = slot.* orelse continue; // The keyboard is on one pane, or on a header: a tag it has left // hands it back to its body, and a name drafted there is dropped. - if (id != p.active or p.topbar_col != null) { + if (id != p.active or p.header_focus) { pane.focus = .body; if (pane.prompt == .name) pane.closePrompt(); } @@ -6134,9 +6051,8 @@ pub const Pardes = struct { // global tagbar: full width, top row — unless a native shell has // taken its commands over, in which case the row is not ours to draw p.revealHeader(); - var tb_buf: [1200]u8 = undefined; - const global_bar = p.topbar(&tb_buf); - const global_scroll = if (p.topbar_col != null and p.header_column == null) p.header_scroll else 0; + const global_bar = modal.lineSlice(p.topbar(), 0); + const global_scroll = if (p.header_focus and p.header_column == null) p.header_scroll else 0; if (p.settings.workspace_tag) { s.fill(0, 0, s.cols, TOPBAR_H, .{ .bg = .{ .rgb = chrome.tag_bg }, @@ -6149,7 +6065,7 @@ pub const Pardes = struct { }); } if (p.pointer_inside and p.hover_row < p.topBarHeight()) { - const bar = p.topbar(&tb_buf); + const bar = global_bar; if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col + global_scroll))) |bounds| { var col = panes.File.rawDisplayCol(bar, bounds.lo) -| global_scroll; const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| global_scroll; @@ -6161,10 +6077,6 @@ pub const Pardes = struct { } } } - if (p.topbar_col) |c| if (p.header_column == null) { - const col = panes.File.rawDisplayCol(p.topbar(&tb_buf), c) -| global_scroll; - if (col < s.cols) s.cursor = .{ .x = @intCast(col), .y = 0, .bar = p.header_insert }; - }; if (p.columnBarHeight() > 0) for (0..p.ncol) |c| { const grip = @min(config.GUTTER, p.col_w[c]); const inset = @min(TAG_TEXT_INSET, p.col_w[c]); @@ -6185,8 +6097,8 @@ pub const Pardes = struct { s.fill(p.col_x[c] + grip, p.topBarHeight(), inset - grip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); s.fill(x, p.topBarHeight(), w, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - const bar_scroll = if (p.topbar_col != null and p.header_column == c) p.header_scroll else 0; - const tag = p.columnTag(c); + const bar_scroll = if (p.header_focus and p.header_column == c) p.header_scroll else 0; + const tag = modal.lineSlice(p.columnTag(c), 0); _ = s.print(x, p.topBarHeight(), w, tag[panes.File.rawAtDisplay(tag, bar_scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, @@ -6194,7 +6106,7 @@ pub const Pardes = struct { }); // A carried column's pointer is aiming at a place, not a word. if (p.pointer_inside and p.drag != .column_move and p.hover_row == p.topBarHeight() and p.hover_col >= x and p.hover_col < x + w) { - const bar = p.columnTag(c); + const bar = tag; if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col - x + bar_scroll))) |bounds| { var col = panes.File.rawDisplayCol(bar, bounds.lo) -| bar_scroll; const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| bar_scroll; @@ -6206,21 +6118,24 @@ pub const Pardes = struct { } } }; - if (p.topbar_col) |cur| { - const bar = p.headerText(); + if (p.focusedHeader()) |t| { + const bar = modal.lineSlice(try edit.flatSurface(p, t), 0); const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; const w = if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else s.cols; const y: u16 = if (p.header_column != null) p.topBarHeight() else 0; - const anchor = p.header_anchor orelse cur; - var col = panes.File.rawDisplayCol(bar, @min(cur, anchor)) -| p.header_scroll; - const hi = panes.File.rawDisplayCol(bar, @max(cur, anchor)) -| p.header_scroll; - while (col < hi and col < w) : (col += 1) { - const cell = s.at(x + @as(u16, @intCast(col)), y); - cell.style.fg = .{ .rgb = th.sel_fg }; - cell.style.bg = .{ .rgb = th.sel_bg }; + if (headerSelection(t, bar)) |span| { + var col = panes.File.rawDisplayCol(bar, span.lo) -| p.header_scroll; + const hi = panes.File.rawDisplayCol(bar, span.hi) -| p.header_scroll; + while (col < hi and col < w) : (col += 1) { + const cell = s.at(x + @as(u16, @intCast(col)), y); + cell.style.fg = .{ .rgb = th.sel_fg }; + cell.style.bg = .{ .rgb = th.sel_bg }; + } + } + if (t.cur_row == 0) { + const caret = panes.File.rawDisplayCol(bar, @min(@as(usize, @intCast(@max(0, t.cur_col))), bar.len)) -| p.header_scroll; + if (caret < w) s.cursor = .{ .x = x + @as(u16, @intCast(caret)), .y = y, .bar = t.mode == .insert }; } - const caret = panes.File.rawDisplayCol(bar, @min(cur, bar.len)) -| p.header_scroll; - if (caret < w) s.cursor = .{ .x = x + @as(u16, @intCast(caret)), .y = y, .bar = p.header_insert }; } try p.renderTagLayers(arena); @@ -6489,13 +6404,12 @@ pub const Pardes = struct { layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = if (p.settings.tag_bottom) r.y + r.h - BOX_H else r.y, .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; layer.cols = columns; layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - layer.cursor = if (p.topbar_col == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; + layer.cursor = if (!p.header_focus and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; } - var text_buf: [1200]u8 = undefined; // With the workspace tag row handed to native chrome there is no // workspace layer to render; the menu bar carries its commands. if (p.settings.workspace_tag) - try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, p.topbar(&text_buf), chrome.tag_bg, chrome.tag_fg); + try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, modal.lineSlice(p.topbar(), 0), chrome.tag_bg, chrome.tag_fg); // Each notice is its own tagline-shaped chip over the top of the body. // Going through the same layer machinery the pane and column tags use // is what gives it the tagline's height, its small-font metrics, the @@ -6558,10 +6472,21 @@ pub const Pardes = struct { if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { if (p.col_w[column] == 0) continue; const active = if (layout.findPane(p, p.active)) |found| found.col == column and p.settings.focus_tint else false; - try p.renderHeaderLayer(arena, MAX_PANES + column, .column, @intCast(column), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight(), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, p.columnTag(column), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); + try p.renderHeaderLayer(arena, MAX_PANES + column, .column, @intCast(column), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight(), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, modal.lineSlice(p.columnTag(column), 0), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); }; } + /// The span a header's selection covers on its first line: up to the + /// caret while typing, and over the cursor's own cell in normal mode, + /// where a cursor is a cell. + pub fn headerSelection(t: *const Text, line: []const u8) ?struct { lo: usize, hi: usize } { + if (!t.vsel.active or t.vsel.row != 0 or t.cur_row != 0) return null; + const anchor = @min(@as(usize, @intCast(@max(0, t.vsel.col))), line.len); + const cursor = @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len); + if (t.mode == .insert) return .{ .lo = @min(anchor, cursor), .hi = @max(anchor, cursor) }; + return .{ .lo = @min(anchor, cursor), .hi = modal.nextGrapheme(line, @max(anchor, cursor)) }; + } + fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: TagKind, id: u16, viewport: Rect, text: []const u8, bg: [3]u8, fg: [3]u8) !void { _ = arena; const layer = &p.surface.tag_layers[index]; @@ -6584,25 +6509,25 @@ pub const Pardes = struct { // A notice band carries a PANE id, not a column index, so it must not // answer to the column being edited -- that would scroll and select // its text with the column tag's offsets and give it a second caret. - const editing = p.topbar_col != null and switch (kind) { + const editing: ?*Text = if (p.header_focus and switch (kind) { .workspace => p.header_column == null, .column => p.header_column == id, .pane, .notice => false, - }; - const scroll = if (editing) p.header_scroll else 0; + }) p.focusedHeader() else null; + const scroll = if (editing != null) p.header_scroll else 0; surface.fill(0, 0, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); _ = surface.print(0, 0, columns, text[panes.File.rawAtDisplay(text, scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); - if (editing) { - const cursor = p.topbar_col.?; - const anchor = p.header_anchor orelse cursor; - var col = panes.File.rawDisplayCol(text, @min(cursor, anchor)) -| scroll; - const end = panes.File.rawDisplayCol(text, @max(cursor, anchor)) -| scroll; - while (col < end and col < columns) : (col += 1) { - surface.at(@intCast(col), 0).style.bg = .{ .rgb = p.theme().sel_bg }; - surface.at(@intCast(col), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + if (editing) |t| { + if (headerSelection(t, text)) |span| { + var col = panes.File.rawDisplayCol(text, span.lo) -| scroll; + const end = panes.File.rawDisplayCol(text, span.hi) -| scroll; + while (col < end and col < columns) : (col += 1) { + surface.at(@intCast(col), 0).style.bg = .{ .rgb = p.theme().sel_bg }; + surface.at(@intCast(col), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + } } - const caret = panes.File.rawDisplayCol(text, cursor) -| scroll; - if (caret < columns) layer.cursor = .{ .col = @intCast(caret), .bar = p.header_insert }; + const caret = panes.File.rawDisplayCol(text, @min(@as(usize, @intCast(@max(0, t.cur_col))), text.len)) -| scroll; + if (t.cur_row == 0 and caret < columns) layer.cursor = .{ .col = @intCast(caret), .bar = t.mode == .insert }; } else if (p.pointer_inside) { const tag_hit = p.pointer_tag_hit; const col: ?usize = if (tag_hit) |pointer| diff --git a/src/tag_line.zig b/src/tag_line.zig deleted file mode 100644 index d3bdf59c..00000000 --- a/src/tag_line.zig +++ /dev/null @@ -1,42 +0,0 @@ -//! Bounded, single-line editable chrome. Offsets are UTF-8 byte offsets. -const std = @import("std"); -const modal = @import("modal.zig"); -pub const Line = struct { - text: [@import("memory.zig").limits.max_tag_tail]u8 = undefined, - len: usize = 0, - custom: bool = false, - saved_col: ?u16 = null, - - pub fn slice(self: *const Line, fallback: []const u8) []const u8 { - return if (self.custom) self.text[0..self.len] else fallback; - } - pub fn set(self: *Line, bytes: []const u8) bool { - if (bytes.len > self.text.len or std.mem.indexOfAny(u8, bytes, "\r\n\x00") != null or !std.unicode.utf8ValidateSlice(bytes)) return false; - @memcpy(self.text[0..bytes.len], bytes); - self.len = bytes.len; - self.custom = true; - return true; - } - pub fn replace(self: *Line, fallback: []const u8, lo: usize, hi: usize, bytes: []const u8) bool { - const current = self.slice(fallback); - if (lo > hi or hi > current.len) return false; - var next: [@import("memory.zig").limits.max_tag_tail]u8 = undefined; - const size = lo + bytes.len + current.len - hi; - if (size > next.len) return false; - @memcpy(next[0..lo], current[0..lo]); - @memcpy(next[lo..][0..bytes.len], bytes); - @memcpy(next[lo + bytes.len ..][0 .. current.len - hi], current[hi..]); - return self.set(next[0..size]); - } -}; - -test "tag replacement is atomic and keeps UTF-8 intact" { - var line: Line = .{}; - try std.testing.expect(line.replace("New Find", 4, 8, "Grep")); - try std.testing.expectEqualStrings("New Grep", line.slice("")); - try std.testing.expect(!line.replace("", 0, 0, "bad\nline")); - try std.testing.expectEqualStrings("New Grep", line.slice("")); - try std.testing.expect(line.set("é界")); - try std.testing.expect(line.replace("", 0, modal.nextGrapheme(line.slice(""), 0), "")); - try std.testing.expectEqualStrings("界", line.slice("")); -} diff --git a/test/column_drag.zig b/test/column_drag.zig index b2b8f35d..f128aa61 100644 --- a/test/column_drag.zig +++ b/test/column_drag.zig @@ -26,7 +26,7 @@ const Snapshot = struct { serial: u32, panes: [pardes.MAX_PANES]usize = undefined, count: usize, - tag: pardes.TagLine, + tag: []const u8, }; fn expectOrder(p: *Pardes, before: []const Snapshot, order: []const usize) !void { @@ -37,7 +37,7 @@ fn expectOrder(p: *Pardes, before: []const Snapshot, order: []const usize) !void try std.testing.expectEqual(saved.serial, p.col_serial[column]); try std.testing.expectEqual(saved.count, p.col_n[column]); try std.testing.expectEqualSlices(usize, saved.panes[0..saved.count], p.col_panes[column][0..p.col_n[column]]); - try std.testing.expectEqualStrings(saved.tag.slice(""), p.col_tags[column].slice("")); + try std.testing.expectEqualStrings(saved.tag, p.columnTag(column)); } } @@ -59,7 +59,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu try std.testing.expectEqual(@as(usize, 2), p.col_n[1]); for ([_]u64{ 2, 3, 5, 7 }, 0..) |weight, column| { p.col_weight[column] = weight; - try std.testing.expect(p.col_tags[column].set(([_][]const u8{ "zero column header", "one column header", "two column header", "three column header" })[column])); + p.col_tags[column].own = try p.gpa.dupe(u8, ([_][]const u8{ "zero column header", "one column header", "two column header", "three column header" })[column]); } p.update(.tick); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -67,7 +67,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu _ = try p.render(frame.allocator()); var before: [4]Snapshot = undefined; for (&before, 0..) |*saved, column| { - saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = p.col_tags[column] }; + saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = p.columnTag(column) }; @memcpy(saved.panes[0..saved.count], p.col_panes[column][0..saved.count]); } const layer = try tagLayer(p, 1); @@ -75,8 +75,8 @@ test "column grip drag moves only its interval and keeps tag caret with the colu p.update(.{ .mouse = headerMouse(layer, 10, .press) }); p.update(.{ .mouse = headerMouse(layer, 10, .release) }); try std.testing.expectEqual(@as(?usize, 1), p.header_column); - const caret = p.topbar_col; - const anchor = p.header_anchor; + const caret = p.focusedHeader().?.cur_col; + const anchor = p.focusedHeader().?.vsel; const scroll = p.header_scroll; const target = p.col_x[3] + p.col_w[3] - 2; const last_rect = p.rects[p.col_panes[3][0]]; @@ -93,14 +93,14 @@ test "column grip drag moves only its interval and keeps tag caret with the colu try expectOrder(p, &before, &.{ 0, 2, 3, 1 }); try std.testing.expectEqual(active, p.active); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(caret, p.topbar_col); - try std.testing.expectEqual(anchor, p.header_anchor); + try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); + try std.testing.expectEqual(anchor, p.focusedHeader().?.vsel); try std.testing.expectEqual(scroll, p.header_scroll); // The old tag envelope must not edit the new occupant of its old index, // including the interval before hosts request another rendered frame. p.update(.{ .mouse = stale }); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(caret, p.topbar_col); + try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); _ = try p.render(frame.allocator()); try std.testing.expectEqual(before[1].serial, (try tagLayer(p, 3)).serial); try std.testing.expectEqual(p.col_w[3] - pardes.TAG_TEXT_INSET, (try tagLayer(p, 3)).viewport.w); @@ -110,7 +110,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu mouse(p, .release, back); try expectOrder(p, &before, &.{ 0, 1, 2, 3 }); try std.testing.expectEqual(@as(?usize, 1), p.header_column); - try std.testing.expectEqual(caret, p.topbar_col); + try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); try std.testing.expectEqual(active, p.active); // A structural change between press and release must not retarget the // in-flight drag to whichever column now occupies the original index. @@ -165,7 +165,7 @@ test "column grip is separate from compact text and the resize seam" { try std.testing.expect(p.drag != .column_move); try std.testing.expect(p.header_drag); p.update(.{ .mouse = headerMouse(layer, 0, .release) }); - try std.testing.expectEqual(@as(?u16, 0), p.topbar_col); + try std.testing.expectEqual(@as(i32, 0), p.focusedHeader().?.cur_col); mouse(p, .press, p.col_x[1] + config.GUTTER - 1); try std.testing.expect(p.drag == .column_move); mouse(p, .release, p.col_x[1] + config.GUTTER - 1); diff --git a/test/panes.zig b/test/panes.zig index a391dba2..b9fa9a88 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -152,8 +152,8 @@ const TagLayerTests = struct { try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); const long = "a" ** 60 ++ "界END"; - try std.testing.expect(p.global_tag.set(long)); - for (p.col_tags[0..p.ncol]) |*tag| try std.testing.expect(tag.set(long)); + p.global_tag.own = try p.gpa.dupe(u8, long); + for (p.col_tags[0..p.ncol]) |*tag| tag.own = try p.gpa.dupe(u8, long); _ = try p.render(frame.allocator()); for ([_]Kind{ .workspace, .column }) |kind| { const id: usize = if (kind == .column) 1 else 0; @@ -161,7 +161,7 @@ const TagLayerTests = struct { const x = @as(f32, @floatFromInt(header.viewport.x)) * 10 + 62.5 * 5; p.update(.{ .mouse = mouse(header, x, .press) }); p.update(.{ .mouse = mouse(header, x, .release) }); - try std.testing.expectEqual(@as(?u16, 63), p.topbar_col); + try std.testing.expectEqual(@as(i32, 63), p.focusedHeader().?.cur_col); if (kind == .column) try std.testing.expectEqual(@as(?usize, 1), p.header_column) else try std.testing.expect(p.header_column == null); p.update(.{ .key = .{ .cp = Key.escape } }); } @@ -334,7 +334,7 @@ const TagNavigationTests = struct { key(p, 'j'); try std.testing.expectEqual(@as(i32, 0), pane.tag.cur_col); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expect(pane.focus == .tag and p.topbar_col == null); + try std.testing.expect(pane.focus == .tag and !p.header_focus); window(p, 'l'); try std.testing.expectEqual(right, p.active); try std.testing.expect(pane.focus == .body and p.panes[right].?.focus == .body); @@ -1291,13 +1291,13 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { const pane = try p.setTestFile("untouched\n"); for ([_]bool{ false, true }) |header| { p.active = 0; - p.topbar_col = null; + p.exitHeader(); p.update(.tick); clickPathEnd(p, pane); p.update(.{ .paste = "/draft" }); try std.testing.expect(pane.prompt == .name); if (header) { - p.topbar_col = 0; + p.enterHeader(null); p.update(.tick); } else { try std.testing.expect(p.executeBuiltinLine(0, "New")); diff --git a/test/snapshots/tagnav.golden b/test/snapshots/tagnav.golden index 3fdba9f2..45d64b42 100644 --- a/test/snapshots/tagnav.golden +++ b/test/snapshots/tagnav.golden @@ -39,3 +39,27 @@ |5: 3 gamma $ == snap tty-tag grid=100x31 cursor=90,2 == snap tty-restored grid=100x31 cursor=54,5 +== snap column-tag grid=100x31 cursor=3,1 +|2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte +|3: 1 alpha Up ls +|5: 3 gamma +== snap column-word grid=100x31 cursor=6,1 +|3: 1 alpha ls +== snap workspace-tag grid=100x31 cursor=0,0 +|3: 1 alpha Up ls +== snap topbar-dollar grid=100x31 cursor=70,0 +|3: 1 alpha ls +== snap topbar-dump-word grid=100x31 cursor=46,0 +== snap topbar-exec grid=100x31 cursor=7,3 +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill Restore /tmp/pardes-snap/tag +|3: 1 alpha Dump ls +== snap topbar-restore-word grid=100x31 cursor=72,0 +|3: 1 alpha ls +== snap topbar-restored grid=100x31 cursor=7,3 +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +|3: 1 alpha $ ls +|5: 3 gamma $ +|6: ── restored history ── +|18: $ ls +|20: $ +|21: ── restored history ── diff --git a/test/snapshots/tagnav.snap b/test/snapshots/tagnav.snap index eed808de..c9ac9605 100644 --- a/test/snapshots/tagnav.snap +++ b/test/snapshots/tagnav.snap @@ -77,3 +77,46 @@ settle 100 key : stable 400 5000 snap tty-restored +# The column and workspace tags are Texts in the same layout, with the same +# keys: Up from a pane with nothing above it reaches its column's tag, in +# normal mode, then the workspace's; Down comes back the same way. +key c-b +stable 700 15000 +key c-w h +stable 400 5000 +key c-w k +stable 400 5000 +snap column-tag +key w +stable 400 5000 +snap column-word +key c-w k +stable 400 5000 +snap workspace-tag +# `$` is the last cell; four long-word steps back land on `Dump`, and the +# execute key runs it and gives the keyboard back to the body FIRST -- `Kill` +# lives up here too, so a builtin that frees the session must never return +# into a focused header. Dump grows a `Restore ` word, which is also the +# case where the line gets longer than the column you were parked on. +key $ +stable 400 5000 +snap topbar-dollar +key B B B B +stable 400 5000 +snap topbar-dump-word +key tab +stable 700 15000 +snap topbar-exec +# THE DELETION HAZARD, from the bar itself: `Restore` frees every pane and +# swaps the core out from under the caller. Walk back up onto the word the +# Dump just grew -- B twice off the tail, because the LONG word motions are the +# ones that step over a path in one go -- and run it. +key c-w k +key c-w k +stable 400 5000 +key $ B B +stable 400 5000 +snap topbar-restore-word +key tab +stable 900 15000 +snap topbar-restored -- cgit v1.3 From f48ab559a4d257137a3aae987a4962f9d74ede23 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 01:09:05 -0300 Subject: Have Text.pane return nothing for a header instead of trapping A column's or the workspace's tag has no pane, and asking one for it hit unreachable; every caller guarded against that by checking `what` first. An optional makes each caller say what it does without a pane, so a forgotten guard no longer compiles into a crash. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 2 +- src/Text.zig | 30 +++++++++++++++++------------- src/edit.zig | 37 +++++++++++++++++++------------------ src/normal.zig | 4 ++-- 4 files changed, 39 insertions(+), 34 deletions(-) (limited to 'src/Text.zig') diff --git a/src/File.zig b/src/File.zig index 262f3ebb..af538385 100644 --- a/src/File.zig +++ b/src/File.zig @@ -655,7 +655,7 @@ pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const [] /// Edit-buffer fragments and other temporary text retain modal's scan path. fn contentIndex(t: *Text, text: []const u8) ?[]const usize { if (t.what != .body) return null; - const pane = t.pane(); + const pane = t.pane() orelse return null; const f = if (pane.file) |*file| file else return null; if (text.ptr != f.content.ptr or text.len != f.content.len) return null; return lineIndex(pane.gpa, f) catch null; diff --git a/src/Text.zig b/src/Text.zig index d4b6d048..61f238ae 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -76,13 +76,14 @@ ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, ed_redo_len: usize = 0, /// The window this text belongs to (acme's t->w). A column's or the -/// workspace's tag belongs to no pane; nothing asks it for one. -pub fn pane(t: *Text) *Pane { +/// 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 => unreachable, + .column, .workspace => null, }; } @@ -98,7 +99,7 @@ pub fn deinit(t: *Text, gpa: std.mem.Allocator) void { /// 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) t.pane().ensureCursorVisible(); + if (t.what == .body) if (t.pane()) |w| w.ensureCursorVisible(); } pub fn toModalCursor(t: *Text) modal.Cursor { @@ -526,8 +527,9 @@ pub fn visualMove( pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bool) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; - const half: i32 = @max(1, @divTrunc(@as(i32, t.pane().rows), 2)); - t.pane().scrollBy(if (down) half else -half); + const w = t.pane() orelse return; + const half: i32 = @max(1, @divTrunc(@as(i32, w.rows), 2)); + w.scrollBy(if (down) half else -half); verticalMove(t, text, range, down, @intCast(half)); } @@ -536,9 +538,10 @@ pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bo 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 margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); - t.pane().scrollBy(delta); - const top = t.pane().scroll(); + 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) { @@ -548,7 +551,7 @@ pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: 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, t.pane().rows) - margin - 1, last_row)); + 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; @@ -560,10 +563,11 @@ pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: pub fn gotoWindow(t: *Text, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; - const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); - const top = t.pane().scroll(); + const w = t.pane() orelse return; + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2)); + const top = w.scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); - const last_vis: i32 = @min(@as(i32, t.pane().rows) - 1, last_row - top); + const last_vis: i32 = @min(@as(i32, w.rows) - 1, last_row - top); const n: i32 = @intCast(cnt - 1); var vline: i32 = switch (which) { .top => top + margin + n, diff --git a/src/edit.zig b/src/edit.zig index 42032168..837a22c6 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -315,7 +315,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { for (lines) |*line| line.* = it.next().?; return lines; } - const pane = t.pane(); + const pane = t.pane() orelse return &.{}; if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.hasPdf()) { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); @@ -325,8 +325,8 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { - if (t.what == .body and t.pane().file != null) - return panes.File.byteAtRowDisplay(t.pane(), row, from_raw, display_col); + if (t.what == .body) if (t.pane()) |pane| if (pane.file != null) + return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col); const local = row; if (local < 0 or @as(usize, @intCast(local)) >= lines.len) @@ -347,7 +347,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { t.cur_pinned = true; return; } - const pane = t.pane(); + const pane = t.pane() orelse return; pane.pinCursor(); if (pane.file == null and !pane.hasPdf()) t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); @@ -356,11 +356,11 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { switch (t.what) { .body => {}, - .tag => return tagline.curTail(t.pane()), + .tag => return if (t.pane()) |pane| tagline.curTail(pane) else "", .input => return t.own orelse "", .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what), } - const pane = t.pane(); + const pane = t.pane() orelse return ""; if (pane.file) |f| return f.content; if (pane.hasPdf()) { if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); @@ -372,7 +372,7 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { if (t.what != .body) return 0; - const pane = t.pane(); + const pane = t.pane() orelse return 0; if (pane.file == null) return 0; return panes.File.wrapWidth(pane, p.settings.wrap); } @@ -385,7 +385,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { if (t.what != .body and t.what != .input and t.own == null) t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; - const pane = t.pane(); + const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; return panes.Terminal.editText(p, pane, lo, hi, col); @@ -406,7 +406,7 @@ fn setEditText(p: *Pardes, t: *Text, new: []u8) void { t.own = new; return; } - const pane = t.pane(); + const pane = t.pane() orelse return p.gpa.free(new); if (pane.file) |*f| return panes.File.setContent(p, f, new); panes.Terminal.setEditText(p, pane, new); } @@ -417,7 +417,7 @@ pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_a /// Terminal overlays can materialize virtual rows/columns, so keep those. pub fn clampFileCursor(t: *Text) bool { if (t.what != .body) return false; - const pane = t.pane(); + const pane = t.pane() orelse return false; const file = if (pane.file) |*file| file else return false; const old_row = t.cur_row; const old_col = t.cur_col; @@ -429,7 +429,7 @@ pub fn clampFileCursor(t: *Text) bool { } pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { - if (t.what == .body and t.pane().hasPdf()) return; + if (t.what == .body) if (t.pane()) |pane| if (pane.hasPdf()) return; pinPaneCursor(p, t); _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so @@ -563,7 +563,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const flat = flatSurface(p, t) catch return; const range = t.primaryRange(flat, 0); if (t.what != .body) return; - const step: i32 = @intCast(@max(1, t.pane().rows)); + const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows)); t.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); return; }, @@ -710,7 +710,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const ln = modal.lineSlice(text, c.row); if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { if (t.what != .body) break :dot; - const f = t.pane().file orelse break :dot; + const f = (t.pane() orelse break :dot).file orelse break :dot; if (f.output != null or !lsp.speaks(f.path)) break :dot; const seq = p.lsp_seq; p.lspRequest(p.active, .completion, ""); @@ -849,7 +849,7 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { pub fn normalYank(p: *Pardes, t: *Text) void { t.select = false; - if (t.what == .body) if (t.pane().rawPointerText(t.pane().sel[sel_slot])) |text| { + if (t.what == .body) if (t.pane()) |pane| if (pane.rawPointerText(pane.sel[sel_slot])) |text| { setYank(p, text); return; }; @@ -1324,7 +1324,8 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { } next = @max(next, end); } - const ext = if (t.what != .body) "" else if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; + const file = if (t.what != .body) null else if (t.pane()) |pane| pane.file else null; + const ext = if (file) |f| std.fs.path.extension(f.path) else ""; var token: []const u8 = config.comment_token_default; lang: for (config.comment_tokens) |row| { for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { @@ -1567,7 +1568,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { // a prompt's answer is typed once and gone; it keeps no history .input => return, } - const pane = t.pane(); + const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } @@ -1575,7 +1576,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { pub fn doUndo(p: *Pardes, t: *Text) void { if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, true); if (t.what != .body) return; - const pane = t.pane(); + const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undo(p, pane); panes.Terminal.undo(p, pane); } @@ -1583,7 +1584,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { pub fn doRedo(p: *Pardes, t: *Text) void { if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, false); if (t.what != .body) return; - const pane = t.pane(); + const pane = t.pane() orelse return; if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); } diff --git a/src/normal.zig b/src/normal.zig index 29d6d620..c7e75d70 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -175,7 +175,7 @@ const Replay = union(enum) { pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { const id = p.active; // a header belongs to no pane and cannot go away under the replay - const owner: ?*Pane = if (t.what == .column or t.what == .workspace) null else t.pane(); + const owner = t.pane(); const serial = if (owner) |pane| pane.serial else 0; // the whole selection in text coordinates, document order. t.sels // is already ordered, so this only slots the primary into place. @@ -292,7 +292,7 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { // What reaches past the text -- a builtin, a search, a language query -- // acts for the pane the text belongs to; a header's is the active one. - const pane = if (t.what == .column or t.what == .workspace) p.panes[p.active] orelse return else t.pane(); + const pane = t.pane() orelse p.panes[p.active] orelse return; const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { -- cgit v1.3 From a9de2b51ab76a43250a4d6c41a0ddd54e6970049 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 09:16:36 -0300 Subject: Let the keyboard reach a tag's path, read-only The tag's computed path, dirty marker and page were out of the keyboard's reach: its cursor lived in the text after them. It now lives in the tag as shown, as in acme where the name is ordinary text at the start of the tag, so `0` goes to the line's start and motions select and yank the path. The path stays read-only: an edit that would change it is refused and leaves the cursor where it was, and typing into a file's path drafts a new name as a click on it does. Sync moves the tag's positions when the prefix changes length, so a rename or the dirty marker still never moves the cursor off the text after it. Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 15 +++++--- docs/helix-keys.md | 2 +- docs/tags.md | 15 +++++--- src/Text.zig | 4 ++ src/body_layer.zig | 16 ++++---- src/edit.zig | 30 +++++++++++++-- src/mouse.zig | 21 ++++++---- src/ninep/pane.zig | 7 ++-- src/panes.zig | 5 +++ src/pardes.zig | 35 ++++++++++++++--- src/tagline.zig | 90 ++++++++++++++++++++++++++++++------------- test/panes.zig | 75 ++++++++++++++++++++++++++---------- test/snapshots/tagpath.golden | 23 +++++++---- test/snapshots/tagpath.snap | 33 ++++++++++------ 14 files changed, 263 insertions(+), 108 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/design.typ b/docs/design.typ index 8e5f7e6e..234c3692 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -790,12 +790,15 @@ A tag holds any number of lines; a pane's tag takes a row per line up to A pane's tag shows a live prefix (path, dirty marker, PDF page) before the text it owns, and that prefix is computed at every read, never stored -(`tagline.tagPrefix`). The Text's coordinates are offsets into its own text -alone, so a rename or a save never moves its cursor. The one translation -point is the whole line as shown: render, the mouse, Look, Exec and the 9P -`tag` file see prefix ++ text, while keyboard motions and edits see only the -text. Editing the path is a separate draft (`Pane.prompt = .name`) committed -by Enter, since a buffer's name is not text it owns. +(`tagline.tagPrefix`). Everything sees the whole line as shown, prefix ++ +text: render, the mouse, Look, Exec, the 9P `tag` file and the keyboard, +whose motions reach the path as acme's do. The prefix is read-only: an edit +installs only what follows it, and one that would change it is refused +(`edit.setEditText`, `Text.refused`). Because the prefix is computed, sync +moves the tag's positions with it when its length changes (`Pane.tag_lead`). +Editing the path is a separate draft (`Pane.prompt = .name`) committed by +Enter, since a buffer's name is not text it owns; a click or a key typed +into it starts one. The tag's text is bounded by `limits.max_tag_tail`: the 9P `tag` file and a dump reader refuse input that does not fit rather than truncating it. diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 5edaccce..f46f5234 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -117,7 +117,7 @@ language-backend queries, and the shell pipe. | `Esc` (insert) | back to normal mode, cursor right after the insertion (no vim left-step) | | helix-verified | | `Enter` (normal) | acme **look** chord: EXPLICIT selection, else file-ish word under cursor | pardes-specific, keep (helix normal-mode Enter unbound). Covers helix `gf`. Implicit motion residue falls back to the cursor word | pardes-specific | | `Tab` (normal) | acme **execute** chord | pardes-specific, keep; explicit-selection rule as Enter | pardes-specific | -| `:` (normal, body or tag) | in the body, focuses the pane's tag in normal mode at its remembered cursor (the first time, on `Save`); in the tag, goes back to the body; in a column or workspace tag, back to the active pane. The tag's normal and insert modes ARE the body's: every motion, selection, edit and undo works there, `0` meaning the start of the editable text. Tab runs the word under the cursor or the selection and Enter looks it up (in a column or workspace tag Enter runs it too), and either hands the keyboard back to the body first. Clicks choose a new cursor position and type into the tag. | Each tag keeps its own cursor during the session. Cursor, selections and undo are offsets in the tag's own text; the computed path/marker/page before it is seen by the mouse, Look and Exec but not by keyboard motions. File-name changes are staged as described in [editable tags](tags.md). | pardes-specific | +| `:` (normal, body or tag) | in the body, focuses the pane's tag in normal mode at its remembered cursor (the first time, on `Save`); in the tag, goes back to the body; in a column or workspace tag, back to the active pane. The tag's normal and insert modes ARE the body's: every motion, selection, edit and undo works there, and `0` goes to the line's start, the path's. Tab runs the word under the cursor or the selection and Enter looks it up (in a column or workspace tag Enter runs it too), and either hands the keyboard back to the body first. Clicks choose a new cursor position and type into the tag. | Each tag keeps its own cursor during the session. The computed path/marker/page is reachable and yankable but read-only: an edit into it is refused, and typing into a file's path drafts a new name. File-name changes are staged as described in [editable tags](tags.md). | pardes-specific | | `Ctrl-w k` / `SPC w k` (pane with nothing above) | focuses its column's tag, then the workspace tag; with `ColumnTags` disabled it goes directly to the workspace. `Ctrl-w j` walks back to the panes, `Ctrl-w h`/`l` walk the column tags. Headers edit exactly as a pane tag does. | Column commands target that column's active pane, or its first pane when coming from elsewhere. Workspace and column text are independently editable and persist in dumps. See [editable tags](tags.md). | pardes-specific | | `Ctrl-w` + `h/j/k/l`/arrows | directional pane focus prefix — editor normal mode only | pardes' own window handling (helix window mode skipped, section C). Runs the SAME `Left`/`Down`/`Up`/`Right` builtins `SPC w h/j/k/l` runs; Raw **tty** mode forwards Ctrl-w to the child. Insert mode owns `Ctrl-w` = delete-word-back, so a tag being TYPED into swallows it; from a tag in normal mode it moves focus to the neighbour's BODY, as from a body, and from the top pane `Up` reaches the column and workspace tags | pardes-specific | | `Alt-n` | new terminal below (outside raw tty) | shadows helix `Alt-n` TS sibling-select — skipped anyway (tree-sitter) | pardes-specific | diff --git a/docs/tags.md b/docs/tags.md index 7c385c08..810ae010 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -51,11 +51,13 @@ a row per line, up to eight: a pane's tag leaves its body at least one row and a collapsed pane shows only the first line; the column and workspace tags take no more than a third of the screen, and the panes below move down to make room. The path, the dirty marker and a PDF's page at the start of a -pane tag are computed, never stored: the tag's cursor, selections and undo -live in the text after them, so a rename or a save never moves the cursor. -The mouse still sees the whole line -- a sweep selects across the path and -the commands, and Look and Exec work on either -- but the keyboard moves only -in the tag's own text: `0` goes to its start, not the path's. +pane tag are computed, never stored, and read-only. The keyboard reaches +them as the mouse does: `0` goes to the line's start, the path's, as in +acme, and motions select and yank across the path and the commands. An edit +that would change them is refused and leaves the cursor where it was; typing +into a file's path instead drafts a new name, as clicking it does. When they +grow or shrink (a rename, the dirty marker, a PDF's page) the cursor keeps +its place in the text after them. Left-click a tag or a header to type into it at the click, in insert mode; tags reveal the caret horizontally when text is wider than their column. @@ -93,7 +95,8 @@ generated right-alignment padding. Intentionally customized spacing is kept. ## File names -Clicking a file pane's name starts a draft of it, typed into at the click. +Clicking a file pane's name, or typing into it from the tag, starts a draft +of it, typed into where it was clicked or typed. Enter or Tab confirms the new buffer name; Escape or leaving the pane cancels the draft. Confirmation changes the buffer's save target and marks it unsaved. It does **not** rename, create or diff --git a/src/Text.zig b/src/Text.zig index 61f238ae..43dd8a95 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -74,6 +74,10 @@ 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 diff --git a/src/body_layer.zig b/src/body_layer.zig index ff1f903c..f9e26b10 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -925,8 +925,7 @@ pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, .{ .row = 0, .at = @min(lines[0].len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) } else if (pane.focus == .tag and pane.prompt == .none and pane.tag.cur_row >= top and pane.tag.cur_row < top + rows) caret: { const row: usize = @intCast(pane.tag.cur_row - top); - const lead: usize = if (row + top == 0) prefix_len else 0; - break :caret .{ .row = row, .at = @min(lines[row].len, lead + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) }; + break :caret .{ .row = row, .at = @min(lines[row].len, @as(usize, @intCast(@max(0, pane.tag.cur_col)))) }; } else null; if (caret) |at| { const line = lines[at.row]; @@ -968,19 +967,18 @@ pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, // time. A range of one grapheme is the block cursor, not a selection. if (pane.focus == .tag) { var ranges: [Text.max_selections]modal.Selection = undefined; - const got = pane.tag.ranges(tail, 0, &ranges); + const got = pane.tag.ranges(whole, 0, &ranges); for (ranges[0..got.n]) |range| { const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); - if (modal.nextGrapheme(tail, lo) >= hi) continue; - const first = modal.positionAt(tail, lo); - const last = modal.positionAt(tail, hi); + if (modal.nextGrapheme(whole, lo) >= hi) continue; + const first = modal.positionAt(whole, lo); + const last = modal.positionAt(whole, hi); var row = @max(first.row, top); while (row <= last.row and row < top + rows) : (row += 1) { const line = lines[row - top]; - const lead: usize = if (row == 0) prefix_len else 0; - const from = lead + if (row == first.row) first.col else 0; - const to = @min(line.len, lead + if (row == last.row) last.col else modal.lineSlice(tail, row).len); + const from = if (row == first.row) first.col else 0; + const to = @min(line.len, if (row == last.row) last.col else line.len); var col = panes.File.rawDisplayCol(line, from) -| pane.tag_scroll; const end = panes.File.rawDisplayCol(line, to); const y = tag_y + @as(u16, @intCast(row - top)); diff --git a/src/edit.zig b/src/edit.zig index e21352e1..b2d71ed2 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -112,8 +112,12 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { /// into, after the cursor's cell in normal mode, as a body's paste is. fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void { if (bytes.len == 0) return; - if (t.mode == .insert) return insertKey(p, t, .{ .cp = bytes[0], .text = bytes }); - pasteText(p, t, bytes, false, 1); + const typed: pardes.Key = .{ .cp = bytes[0], .text = bytes }; + if (t.what == .tag and t.mode == .insert) if (t.pane()) |pane| if (tagline.typedIntoName(p, pane, typed)) return; + const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel }; + t.refused = false; + if (t.mode == .insert) insertKey(p, t, typed) else pasteText(p, t, bytes, false, 1); + if (t.refused) t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel = kept; } pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { @@ -358,7 +362,8 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { switch (t.what) { .body => {}, - .tag => return if (t.pane()) |pane| tagline.curTail(pane) else "", + // the tag as it is shown: the keyboard reaches its prefix too + .tag => return if (t.pane()) |pane| try tagline.tagText(p, p.scratch.allocator(), pane) else "", .input => return t.own orelse "", .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what), } @@ -384,6 +389,10 @@ pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { // A tag or header nobody has changed shows its default; the first edit // makes that default its own text. + if (t.what == .tag) { + const pane = t.pane() orelse return null; + return .{ .text = tagline.tagText(p, p.scratch.allocator(), pane) catch return null, .row0 = 0 }; + } if (t.what != .body and t.what != .input and t.own == null) t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; @@ -403,6 +412,21 @@ fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { /// install a rewritten editable text (frees the old one) pub fn setEditText(p: *Pardes, t: *Text, new: []u8) void { + if (t.what == .tag) { + // A tag is edited as it is shown, but only what follows its + // prefix is its own: an edit that changed the prefix is refused. + defer p.gpa.free(new); + const pane = t.pane() orelse return; + const prefix = tagline.pathPrefix(p.scratch.allocator(), pane) catch return; + if (!std.mem.startsWith(u8, new, prefix)) { + t.refused = true; + return; + } + const tail = p.gpa.dupe(u8, new[prefix.len..]) catch return; + if (t.own) |old| p.gpa.free(old); + t.own = tail; + return; + } if (t.what != .body) { if (t.own) |old| p.gpa.free(old); t.own = new; diff --git a/src/mouse.zig b/src/mouse.zig index 69feea29..beb2e624 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -827,11 +827,14 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { if (sl.r0 < pane.tag_rows) { // On the tag the caret goes where the button came up. A // click on the path, if it can be renamed, drafts a name. - const at = tagline.tagOffsetAt(p, pane, @intCast(@max(0, sl.r1)), @intCast(@max(0, sl.c1))); - if (at) |cursor| { + const row: usize = @intCast(@max(0, sl.r1)); + const col: usize = @intCast(@max(0, sl.c1)); + if (!dragged and tagline.onName(pane, row, col)) { + tagline.draftName(p, pane, col); + } else if (tagline.tagOffsetAt(p, pane, row, col)) |cursor| { pane.tag.cur_row = @intCast(cursor.row); pane.tag.cur_col = @intCast(cursor.col); - } else if (!dragged) tagline.draftName(p, pane, @intCast(@max(0, sl.c1))); + } return; } if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; @@ -932,7 +935,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { }; if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) { // A sweep over the tag cuts from and pastes into the tag's own text; - // the part of it over the prefix is not the tag's to cut. + // the part of it over the prefix is not the tag's to cut, so the + // sweep starts after it. const t = &pane.tag; if (!s.chorded) { s.chorded = true; @@ -941,9 +945,12 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { const forward = sl.r0 < sl.r1 or (sl.r0 == sl.r1 and sl.c0 <= sl.c1); const start = if (forward) .{ sl.r0, sl.c0 } else .{ sl.r1, sl.c1 }; const end = if (forward) .{ sl.r1, sl.c1 } else .{ sl.r0, sl.c0 }; - const origin: modal.Cursor = .{ .row = 0, .col = 0 }; - const from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; - const to = tagline.tagOffsetAt(p, pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; + const lead = pane.tag_lead; + const origin: modal.Cursor = .{ .row = 0, .col = lead }; + var from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; + var to = tagline.tagOffsetAt(p, pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; + if (from.row == 0) from.col = @max(from.col, lead); + if (to.row == 0) to.col = @max(to.col, lead); t.cur_row = @intCast(to.row); t.cur_col = @intCast(to.col); t.cur_pinned = true; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 80dd97cd..64355e0e 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -613,8 +613,9 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { pane.tag.remember(p.gpa, if (pane.tag.own) |own| .{ .text = own } else null); if (pane.tag.own) |own| p.gpa.free(own); pane.tag.own = empty; + // what is left is the prefix; the cursor goes after it pane.tag.cur_row = 0; - pane.tag.cur_col = 0; + pane.tag.cur_col = if (tagline.pathPrefix(p.scratch.allocator(), pane)) |prefix| @intCast(prefix.len) else |_| 0; pane.tag.vsel.active = false; pane.tag.nsel = 0; }, @@ -910,9 +911,9 @@ test "truncating the tag clears its editable tail" { try testing.expectEqualStrings("/test.txt Get", whole); const word = config.wordBounds(whole, whole.len - "Get".len); try testing.expectEqualStrings("Get", whole[word.lo..word.hi]); - // and the keyboard's first column of the text is the G + // and a click on the G puts the tag's cursor on it const at = tagline.tagOffsetAt(p, pane, 0, "/test.txt ".len).?; - try testing.expectEqual(@as(usize, 0), at.col); + try testing.expectEqualStrings("Get", whole[at.col..]); } test "name reads the file name and writing it promotes a scratch without touching its body" { diff --git a/src/panes.zig b/src/panes.zig index a67aa8ac..ab4f5072 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -133,6 +133,11 @@ pub const Pane = struct { /// scrolls to keep its caret in view while it has the keyboard; pointer /// rows count from this line, not the tag's first. tag_top: u16 = 0, + /// How long the tag's computed prefix was when its positions were last + /// placed. They count from the start of the prefix, so when it grows or + /// shrinks (a rename, the dirty marker, a PDF's page) what follows it + /// moves with it. + tag_lead: usize = 0, cwd: Cwd = .none, hscroll: i32 = 0, // Visible rows map to source lines and raw/display column origins. diff --git a/src/pardes.zig b/src/pardes.zig index 65f3aebb..321a6b3c 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4976,16 +4976,14 @@ pub const Pardes = struct { if (t.what != .body) { // An explicit selection, else the word under the cursor in the // text as it is shown: a tag's prefix is part of what a word is. - const arena = p.scratch.allocator(); - const own = arena.dupe(u8, edit.flatSurface(p, t) catch return) catch return; - const shown = if (t.what == .tag) tagline.tagText(p, arena, pane) catch return else own; - const range = t.primaryRange(own, 0); + const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p, t) catch return) catch return; + const range = t.primaryRange(shown, 0); const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); const txt = if ((t.vsel.active and t.vsel.explicit) or t.msel.active) - own[lo..hi] + shown[lo..hi] else word: { - const b = config.wordBounds(shown, shown.len - own.len + modal.selectionCursor(own, range)); + const b = config.wordBounds(shown, modal.selectionCursor(shown, range)); break :word shown[b.lo..b.hi]; }; // Out of the tag or header FIRST: Del frees the pane, Kill @@ -5013,6 +5011,14 @@ pub const Pardes = struct { return; } if (t.mode == .normal and t.what == .body and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); + if (t.what == .tag and t.mode == .insert and tagline.typedIntoName(p, pane, key)) return; + // A tag's prefix is read-only: a key whose edit reached into it + // changes nothing, not even where the cursor is. + const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel }; + t.refused = false; + defer if (t.refused) { + t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel = kept; + }; switch (t.mode) { .normal => normal.handleNormal(p, t, key), .insert => { @@ -5597,6 +5603,23 @@ pub const Pardes = struct { const r = p.rects[id]; // The tag takes a row per line, leaving the body one row if it // had any; a folded pane shows its first line only. + // Measured on the stack: this runs on every event, and not + // every event may take from the scratch arena. + var room: [2 * limits.host_path_cap + 256]u8 = undefined; + var measure = std.heap.FixedBufferAllocator.init(&room); + const lead = if (tagline.prefixIn(measure.allocator(), pane)) |prefix| prefix.len else |_| pane.tag_lead; + if (lead != pane.tag_lead) { + const t = &pane.tag; + const old: i32 = @intCast(pane.tag_lead); + const new: i32 = @intCast(lead); + if (t.cur_row == 0 and t.cur_col >= old) t.cur_col += new - old; + if (t.vsel.row == 0 and t.vsel.col >= old) t.vsel.col += new - old; + for (t.sels[0..t.nsel]) |*sel| { + if (sel.row == 0 and sel.col >= old) sel.col += new - old; + if (sel.arow == 0 and sel.acol >= old) sel.acol += new - old; + } + pane.tag_lead = lead; + } const lines = std.mem.count(u8, tagline.curTail(pane), "\n") + 1; pane.tag_rows = @intCast(@min(lines, MAX_TAG_ROWS, @max(BOX_H, r.h -| 1))); if (pane.collapsed) pane.tag_rows = BOX_H; diff --git a/src/tagline.zig b/src/tagline.zig index 8bd8000a..92c18510 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -102,20 +102,29 @@ pub fn revealHeader(p: *Pardes) void { } } +/// The computed start of a pane's tag -- its path and dirty marker, a +/// PDF's page, a terminal's directory -- without the space that parts it +/// from the tag's own text. It is never stored, and never edited. +pub fn pathPrefix(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + if (comptime pdf_enabled) if (pane.pdf) |pv| + return std.fmt.allocPrint(arena, "{s} [{d}/{d}]", .{ pv.path, pv.page + 1, pv.page_count }); + if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); + if (pane.file) |f| { + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; + if (panes.Output.fileTraits(f.output).saves and f.revision != f.saved_revision) + return std.fmt.allocPrint(arena, "{s}{s}", .{ name, dirty_marker }); + return name; + } + return pane.cwdSlice(); +} + pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { - const arena = p.scratch.allocator(); - const prefix = prefix: { - if (comptime pdf_enabled) if (pane.pdf) |pv| - break :prefix try std.fmt.allocPrint(arena, "{s} [{d}/{d}]", .{ pv.path, pv.page + 1, pv.page_count }); - if (pane.image) |*state| break :prefix try panes.Image.tagPrefix(arena, state); - if (pane.file) |f| { - const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; - if (panes.Output.fileTraits(f.output).saves and f.revision != f.saved_revision) - break :prefix try std.fmt.allocPrint(arena, "{s}{s}", .{ name, dirty_marker }); - break :prefix name; - } - break :prefix pane.cwdSlice(); - }; + return prefixIn(p.scratch.allocator(), pane); +} + +/// The prefix as the tag shows it, built in `arena`. +pub fn prefixIn(arena: std.mem.Allocator, pane: *Pane) ![]u8 { + const prefix = try pathPrefix(arena, pane); // The space between the prefix and the tag's own text is the text's // (every default starts with one), but the prefix is computed, so it // cannot trust the text to keep it: with it deleted, Look and Exec @@ -159,21 +168,23 @@ pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { /// it starts on Save, so that `:` and the execute key write the file. pub fn enterTag(p: *Pardes, pane: *Pane) void { const t = &pane.tag; - const tail = curTail(pane); + const whole = tagText(p, p.scratch.allocator(), pane) catch return; if (!t.cur_pinned) { + // Save is looked for in the tag's own text, after the prefix. + const lead = whole.len - curTail(pane).len; + const tail = whole[lead..]; var words = std.mem.tokenizeAny(u8, tail, " \t\n"); - const at = while (words.next()) |word| { + const at = lead + while (words.next()) |word| { if (std.mem.eql(u8, word, "Save")) break @intFromPtr(word.ptr) - @intFromPtr(tail.ptr); } else tail.len - std.mem.trimStart(u8, tail, " ").len; - const cursor = modal.positionAt(tail, @min(at, 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; // Reveal the suffix together with its commands, not merely the // first command letter at the viewport's far right edge. if (p.paneIdOf(pane)) |id| { - const tag = tagText(p, p.scratch.allocator(), pane) catch return; - const line = tag[0 .. std.mem.indexOfScalar(u8, tag, '\n') orelse tag.len]; + const line = whole[0 .. std.mem.indexOfScalar(u8, whole, '\n') orelse whole.len]; const width = p.tagCapacity(p.rects[id].w -| TAG_TEXT_INSET); pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); } @@ -181,9 +192,9 @@ pub fn enterTag(p: *Pardes, pane: *Pane) void { // The text may have changed since (a 9P write, a rename), so the // remembered cursor is pulled back inside it. It is the cursor that // is remembered, not a selection. - const rows = modal.cursorLineCount(tail); + const rows = modal.cursorLineCount(whole); t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); - const line = modal.lineSlice(tail, @intCast(t.cur_row)); + const line = modal.lineSlice(whole, @intCast(t.cur_row)); t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); t.vsel.active = false; t.msel.active = false; @@ -196,15 +207,40 @@ pub fn enterTag(p: *Pardes, pane: *Pane) void { pane.focus = .tag; } -/// Where display column `col` of tag line `row` (tag scroll included) -/// lands in the tag's own text, or null when it is on the prefix, which -/// only the first line has. +/// Where display column `col` of the tag's shown row `row` (tag scroll +/// included) puts its cursor: the tag as shown, prefix and all. pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Cursor { const at = row + pane.tag_top; - const width = if (at == 0) panes.File.displayWidth(tagPrefix(p, pane) catch return null) else 0; - if (col < width) return null; - const line = modal.lineSlice(curTail(pane), at); - return .{ .row = at, .col = modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)) }; + const line = modal.lineSlice(tagText(p, p.scratch.allocator(), pane) catch return null, at); + return .{ .row = at, .col = modal.graphemeStart(line, panes.File.rawAtDisplay(line, col)) }; +} + +/// Whether display column `col` of the tag's shown row `row` is on a name +/// a click drafts: a saving file's path. +pub fn onName(pane: *Pane, row: usize, col: usize) bool { + if (row + pane.tag_top != 0) return false; + const f = pane.file orelse return false; + if (!panes.Output.fileTraits(f.output).saves) return false; + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; + return col < panes.File.displayWidth(name); +} + +/// 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; + const at: usize = @intCast(@max(0, pane.tag.cur_col)); + 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(f.path[0..at])); + edit.handleInsert(p, &pane.input, key); + return true; } /// Start a name draft for a file that can take one, its caret at display diff --git a/test/panes.zig b/test/panes.zig index d8ed517f..d0551cfc 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -12,12 +12,6 @@ const image = pardes.image; const syntax = pardes.syntax; const filesystem = pardes.filesystem; -/// The tag's caret as a byte offset into the tag as it is shown, prefix -/// included. -fn tagCaret(p: *Pardes, pane: *Pane) !usize { - return (try pardes.tagline.tagPrefix(p, pane)).len + @as(usize, @intCast(pane.tag.cur_col)); -} - fn setTag(pane: *Pane, text: []const u8) !void { if (pane.tag.own) |own| pane.gpa.free(own); pane.tag.own = try pane.gpa.dupe(u8, text); @@ -67,7 +61,7 @@ const TagLayerTests = struct { p.update(.{ .mouse = mouse(layer, x, .press) }); p.update(.{ .mouse = mouse(layer, x, .release) }); try std.testing.expect(pane.focus == .tag); - try std.testing.expectEqual(at, try tagCaret(p, pane)); + try std.testing.expectEqual(at, @as(usize, @intCast(pane.tag.cur_col))); p.update(.{ .key = .{ .cp = 'X', .text = "X" } }); _ = try p.render(frame.allocator()); const edited = try pardes.tagline.tagText(p, frame.allocator(), pane); @@ -99,7 +93,7 @@ const TagLayerTests = struct { event.row = @intFromFloat(painted_y); p.update(.{ .mouse = event }); } - try std.testing.expectEqual(at, try tagCaret(p, pane)); + try std.testing.expectEqual(at, @as(usize, @intCast(pane.tag.cur_col))); } } @@ -148,7 +142,7 @@ const TagLayerTests = struct { p.update(.{ .mouse = mouse(layer, beyond_x, .release) }); try std.testing.expectEqual(@as(usize, 0), p.active); const end_col = left_layer.capacity(p.row_metrics) - 1; - try std.testing.expectEqual(panes.File.rawAtDisplay(left_text, end_col), try tagCaret(p, left)); + try std.testing.expectEqual(panes.File.rawAtDisplay(left_text, end_col), @as(usize, @intCast(left.tag.cur_col))); try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); const long = "a" ** 60 ++ "界END"; @@ -320,6 +314,44 @@ const TagNavigationTests = struct { try std.testing.expect(pane.prompt == .none and pane.focus == .body); } + test "the keyboard reaches a tag's path, which it can select and yank but not edit" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("body\n"); + p.update(.tick); + key(p, ':'); + // `0` is the line's start, as in acme, where the name is ordinary text + key(p, '0'); + try std.testing.expectEqual(@as(i32, 0), pane.tag.cur_col); + key(p, 'E'); + key(p, 'y'); + try std.testing.expectEqualStrings("/test.txt", p.yank.?); + // an edit that reaches into it is refused, the cursor with it + const before = try std.testing.allocator.dupe(u8, try pardes.edit.flatSurface(p, &pane.tag)); + defer std.testing.allocator.free(before); + const cursor = pane.tag.cur_col; + key(p, 'd'); + try std.testing.expectEqualStrings(before, try pardes.edit.flatSurface(p, &pane.tag)); + try std.testing.expectEqual(cursor, pane.tag.cur_col); + try std.testing.expect(pane.tag.vsel.active); + // typed into, the path drafts a name there, as a click on it does + key(p, ';'); + key(p, '0'); + key(p, 'i'); + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + try std.testing.expect(pane.prompt == .name); + try std.testing.expectEqualStrings("x/test.txt", pane.input.own.?); + key(p, Key.escape); + try std.testing.expect(pane.prompt == .none); + try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); + // after the path, the text is the tag's own to edit + key(p, ':'); + key(p, 'A'); + p.update(.{ .key = .{ .cp = '!', .text = "!" } }); + try std.testing.expect(std.mem.endsWith(u8, pardes.tagline.curTail(pane), "!")); + try std.testing.expectEqualStrings("body\n", pane.file.?.content); + } + fn window(p: *Pardes, letter: u21) void { p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); key(p, letter); @@ -339,8 +371,9 @@ const TagNavigationTests = struct { // Nothing to remember yet: `:` lands on Save, in normal mode. key(p, ':'); try std.testing.expect(first.focus == .tag and first.tag.mode == .normal); - const tail = pardes.tagline.curTail(first); - try std.testing.expectEqualStrings("Save", tail[@intCast(first.tag.cur_col)..][0..4]); + const shown = try pardes.edit.flatSurface(p, &first.tag); + try std.testing.expectEqualStrings("Save", shown[@intCast(first.tag.cur_col)..][0..4]); + // Home is the line's start, the path's: the keyboard reaches it. key(p, Key.home); for (0..3) |_| key(p, Key.right); try std.testing.expectEqual(@as(i32, 3), first.tag.cur_col); @@ -369,13 +402,13 @@ const TagNavigationTests = struct { ClickCursorTests.click(p, .left, rect.x + pardes.TAG_TEXT_INSET + prefix + 6, y); try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expect(first.focus == .tag and first.tag.mode == .insert); - try std.testing.expectEqual(@as(i32, 6), first.tag.cur_col); + try std.testing.expectEqual(@as(i32, prefix + 6), first.tag.cur_col); key(p, Key.escape); key(p, ':'); p.startPrompt(first, &first.body, .{ .search = config.search_marker }); key(p, Key.escape); key(p, ':'); - try std.testing.expectEqual(@as(i32, 6), first.tag.cur_col); + try std.testing.expectEqual(@as(i32, prefix + 6), first.tag.cur_col); key(p, ':'); try std.testing.expectEqualStrings("body\n", first.file.?.content); } @@ -403,26 +436,28 @@ const TagNavigationTests = struct { try std.testing.expectEqual(chord == Key.tab, saved); // ...and the tag still knows where it was. key(p, ':'); - try std.testing.expectEqualStrings("Save", pardes.tagline.curTail(pane)[@intCast(pane.tag.cur_col)..][0..4]); + try std.testing.expectEqualStrings("Save", (try pardes.edit.flatSurface(p, &pane.tag))[@intCast(pane.tag.cur_col)..][0..4]); } } - test "a renamed path never moves the tag's cursor and a shorter tag pulls it back" { + test "a renamed path moves the tag's cursor with the text after it and a shorter tag pulls it back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 14 }); defer p.deinit(); const pane = try p.setTestFile("body\n"); - key(p, ':'); - key(p, Key.home); - for (0..3) |_| key(p, Key.right); + key(p, ':'); // on Save key(p, ':'); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/界.zig"); + p.update(.tick); key(p, ':'); - try std.testing.expectEqual(@as(i32, 3), pane.tag.cur_col); + const shown = try pardes.edit.flatSurface(p, &pane.tag); + try std.testing.expectEqualStrings("Save", shown[@intCast(pane.tag.cur_col)..][0..4]); key(p, ':'); try setTag(pane, "é"); + p.update(.tick); key(p, ':'); - try std.testing.expectEqual(@as(i32, 2), pane.tag.cur_col); + // `/界.zig é`: the cursor is pulled back onto the last character + try std.testing.expectEqual(@as(i32, "/界.zig ".len), pane.tag.cur_col); try std.testing.expectEqualStrings("body\n", pane.file.?.content); } diff --git a/test/snapshots/tagpath.golden b/test/snapshots/tagpath.golden index 2ba1a2e6..a2ea32fc 100644 --- a/test/snapshots/tagpath.golden +++ b/test/snapshots/tagpath.golden @@ -8,12 +8,12 @@ | 4 line 4 | 5 == snap colon grid=100x31 cursor=38,2 -== snap col0 grid=100x31 cursor=37,2 -== snap drag-cross grid=100x31 cursor=41,2 -== style drag-cross grid=100x31 +== snap col0 grid=100x31 cursor=3,2 +== snap sel-path grid=100x31 cursor=36,2 +== style sel-path grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, |1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-99 d,#26362d, -|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-10 #becfc4,#26362d, 11-41 #f5f7ee,#3c614a, 42-58 #becfc4,#26362d, 59-99 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-36 #f5f7ee,#3c614a, 37-58 #becfc4,#26362d, 59-99 d,#26362d, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, @@ -42,9 +42,16 @@ |28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, |29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, |30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, +== snap yanked-path grid=100x31 cursor=41,3 +|2: /tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del +|3: 1 l/tmp/pardes-snap/tagpath/cwd/c.txtine 1 +== snap drag-cross grid=100x31 cursor=41,2 +== style drag-cross grid=100x31 +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-10 #becfc4,#26362d, 11-41 #f5f7ee,#3c614a, 42-60 #becfc4,#26362d, 61-99 d,#26362d, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-7 #e5eee5,#0d1410, 8-41 #f5f7ee,#3c614a, 42-46 #e5eee5,#0d1410, 47-99 d,#0d1410, == snap name-draft grid=100x31 cursor=11,2 -|2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del -== snap name-cancelled grid=100x31 cursor=7,3 -|2: /tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del -== snap name-committed grid=100x31 cursor=7,3 +|2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del +== snap name-cancelled grid=100x31 cursor=41,3 +|2: /tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del +== snap name-committed grid=100x31 cursor=41,3 |2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del diff --git a/test/snapshots/tagpath.snap b/test/snapshots/tagpath.snap index b9ef80e6..f02769d9 100644 --- a/test/snapshots/tagpath.snap +++ b/test/snapshots/tagpath.snap @@ -1,8 +1,7 @@ -# The path is part of the tag's text for the mouse -- a sweep selects across -# the path and the commands after it -- but never for the keyboard: the tag's -# cursor lives in its own text, so `0` goes to the start of that, not of the -# path. A click on the path drafts a new name there instead. Escape cancels; -# Enter changes buffer identity, never renames a disk file. +# The path is part of the tag's text for the keyboard as for the mouse: `0` +# goes to its start, `E` selects it and `y` yanks it. It is read-only, but +# typing into it drafts a new name there, as a click on it does. Escape +# cancels; Enter changes buffer identity, never renames a disk file. lines c.txt 4 start 31 100 c.txt wait 8000 Newcol Joincol @@ -15,6 +14,16 @@ snap colon key 0 stable 400 5000 snap col0 +key E +stable 400 5000 +snap sel-path +snapstyle sel-path +key y +# `:` gives the keyboard back to the body, and `p` puts the path there +key : +key p +stable 400 5000 +snap yanked-path # Sweep across the path / command boundary without injected padding. press left 12 3 drag left 30 3 @@ -23,21 +32,21 @@ release left 42 3 stable 400 5000 snap drag-cross snapstyle drag-cross +# Esc is the tag's normal mode; typed at the path's start, `/renamed` drafts +# a name key esc settle 100 -key : -stable 400 5000 -# a click on the path is a name draft, the caret where it was clicked -press left 4 3 -release left 4 3 +key 0 +key i text /renamed stable 400 5000 snap name-draft key esc stable 400 5000 snap name-cancelled -press left 4 3 -release left 4 3 +key : +key 0 +key i text /renamed key enter stable 400 5000 -- cgit v1.3 From 767aefd1e1cfd79e2a240a59d2d16bfb326f062d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 15:59:00 -0300 Subject: Registers hold a value per range, and " names one Registers.zig replaces the one yank buffer: every register keeps a value per range, y fills them in document order, and p, P, R and insert Ctrl-r put value i at range i, repeating the last (helix paste_impl). " names the register for the next command; _ swallows, # numbers the ranges, . is each range's text, % the file's name, / the last s/S pattern, and + and * are the system clipboard through the ClipYank and ClipPaste paths. SPC y now writes + alone, as helix's does. The acme chords and a paste into a terminal take the default register joined by newlines. The msel-yank-paste waiver is gone. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 21 +++++---- docs/selections.md | 15 +++--- src/Registers.zig | 106 ++++++++++++++++++++++++++++++++++++++++++ src/Text.zig | 2 + src/config.zig | 2 + src/edit.zig | 112 +++++++++++++++++++++++++++++++++++++-------- src/gui/gui.zig | 2 +- src/look.zig | 6 ++- src/modal.zig | 13 ++++++ src/mouse.zig | 12 ++--- src/normal.zig | 17 +++++-- src/pardes.zig | 22 ++++++--- test/hxcases/cases.jsonl | 13 ++++++ test/hxcases/goldens.jsonl | 13 ++++++ test/hxcases/waivers.jsonl | 1 - test/panes.zig | 20 ++++---- 16 files changed, 312 insertions(+), 65 deletions(-) create mode 100644 src/Registers.zig (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 972ef0d2..90efc463 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -110,9 +110,9 @@ language-backend queries, and the shell pipe. | `x` / `x` | select current line / extend one (n) line(s) down, char-range through the newline, cursor ON the `\n` | col-0 vim-ism removed (phase 5); matches `extend_line_below`, mode stays normal | helix-verified | | `d` | delete selection (implicit or explicit); bare cursor = the 1-wide selection | always yanks (`Alt-d` noyank in B); terminals: drops typed runs only | helix-verified | | `c` | change (delete + insert mode); linewise selections open a fresh indented line | same shape as `d` | helix-verified | -| `y` | yank selection; bare cursor yanks the 1-wide selection (char under cursor) | line-yank vim-ism removed (phase 5); yank keeps selection AND cursor (helix). Writes the DEFAULT REGISTER and nothing else — the system clipboard is `SPC y`, which is helix's own split and so moves this row TOWARDS helix, not away: a `d` of one character can no longer clobber what the desktop was holding | helix-verified | +| `y` | yank each range's text into the register (`"` names one, else `"`), one value per range | line-yank vim-ism removed (phase 5); yank keeps selection AND cursor (helix). The system clipboard is `"+y` / `SPC y`, helix's own split: a `d` of one character never clobbers what the desktop holds | helix-verified | | `u` / `U` | undo / redo | restores the pre-edit selection (helix); snapshot granularity, no `Alt-u`/`Alt-U` history walking (skipped) | helix-verified | -| `p` (normal) | paste the core's yank register after the selection | helix default-register semantics, and only the register — nothing on this path reads or writes the system clipboard. `SPC p` is the word that does, and on a tty its read is OSC 52, which most terminals refuse: an honest no-op there rather than a paste of the wrong text | helix-verified | +| `p` (normal) | paste the register after each range: value i at range i, the last value repeated when there are fewer | helix `paste_impl`. `"+p` asks the system clipboard (`SPC p`); on a tty that read is OSC 52, which most terminals refuse: an honest no-op rather than a paste of the wrong text | helix-verified | | `Esc` (body normal) | clear a pending modal prefix / exit select mode, keeping the selection, then run `Last`: hop to the pane you were in before this one, whichever kind it was, exactly like `SPC j j` — so held down it alternates between two panes, two files as readily as a file and its shell. A PDF pane is the ONE exception: there Esc is the document's own cancel (drop the mouse selection and the search overlay, stay where you are reading) and `Shift-Esc` is the hop out, while raw tty only intercepts unmodified Esc at a detected shell prompt | Pardes-specific focus binding layered on helix's cleanup. A leader path, tag, topbar or search owns Esc while it is active; raw tty forwards it | pardes-specific (cleanup helix-verified) | | `Esc` (insert) | back to normal mode, cursor right after the insertion (no vim left-step) | | helix-verified | | `Enter` (normal) | acme **look** chord: EXPLICIT selection, else file-ish word under cursor | pardes-specific, keep (helix normal-mode Enter unbound). Covers helix `gf`. Implicit motion residue falls back to the cursor word | pardes-specific | @@ -123,7 +123,7 @@ language-backend queries, and the shell pipe. | `Alt-n` | new terminal below (outside raw tty) | shadows helix `Alt-n` TS sibling-select — skipped anyway (tree-sitter) | pardes-specific | | `Alt-c` | move active terminal to a fresh column (outside raw tty) | helix `Alt-c` is change-noyank; the pardes window op wins (do-not-touch contract). `Alt-d` + `i` covers the behavior | waived (`alt-c-window-op`) | | `Space` (normal, body) | starts the pardes LEADER: a key path runs the same builtin words used by tags and the topbar. The main groups are `f` files, `h` docs, `c` columns, `t` toggles/effects, `a` panel animations, `s` session, `j` jumps, `l` language, and `w` directional focus; `SPC ?` lists every path and ` ?` lists one group in `+Help`. Neither `Exit` (quits the editor, acme's Exit) nor `Kill` (stops the commands pardes typed into terminals, acme's Kill) has a leader path: both are the topbar's and the root `ctl`'s. The pending path appears on the active pane's transient body/message row. Esc or an unmapped key abandons it. Paths, Help rows, and dispatch are all generated from the builtin registry at comptime; the leader applies only to a BODY in normal mode because tags and tty programs own their input | pardes-specific; helix spends Space on pickers/LSP (section C), while pardes uses acme-style executable words | -| `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the ONLY five words in pardes that touch the desktop's clipboard — `y`/`d`/`c`/`p`/`P`/`R` and the acme cut/paste chords are the internal register alone. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. One divergence: pardes keeps a single register VALUE where helix keeps one per range, so `SPC y` at N cursors joins them with newlines (`Pardes.setYank`, the divergence `msel-yank-paste` already waives). On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | +| `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the same as `"+y`, `"+p`, `"+P`, `"+R`: register `+` (and `*`) IS the desktop's clipboard, the only register that reaches it. `SPC y` writes `+` alone, as helix's does, not the default register too. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. The clipboard holds one text, so N values go out joined by newlines, as helix sends them. On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | | a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tty shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | | `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the pattern is typed on a line of its own on the pane's notice band, Enter fills the buffer, and its rows are ordinary look targets. Enter also GOES to the first row — the buffer is focused and then the step `n` is and the look Enter is run in it (`Pardes.lookFirstHit`), so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | KEEP, do not touch; not in the corpus (helix `/` is regex search). Find and Grep answer with OTHER files and deliberately do NOT jump. The stepping half is the next row | pardes-specific | | `n` / `N` (any pane) | MOTION, not a jump: move the SELECTION to the next / previous look-able text and open NOTHING. Enter — the look chord — on what it leaves selected is what opens it | KEEP, do not touch; not in the corpus (helix's `n`/`N` walk regex search hits). What a step selects is the pane's GRAIN (`output_pane.Grain`, read in `Pardes.lookSpanIn`): in FREE TEXT — a terminal, a file, a PDF, a prose answer buffer — the largest whitespace-delimited run `look.resolve` can act on (`look.lookableSpan`, wrapper punctuation peeled off both ends), several to a line; in a RESULTS BUFFER one stop per ROW, the largest run its head resolves as (`look.lookableLineSpan`), because a row there IS one location and the words after it are the match rather than a second place to go; in a COMMAND list the whole line. The walk is a RING across PANES: every pane that has performed a Look, most recent first (`Pardes.look_src`), then the output buffers that have not, newest first, and only when both are empty the active pane. Exhausting a pane enters the next at its first (forward) / last (backward) span and the end wraps to the start, so `N` is the exact inverse of `n`. What it lands on becomes an EXPLICIT `vsel` with the cursor on its FIRST column, in the pane the walk focuses. ONE motion in every pane kind and every buffer kind — a PDF steps the `+Search` buffer its own search filled, `n` to select the row and Enter to jump. The single thing a buffer may change is that grain, and it changes it by BEING a kind of buffer rather than by a branch: `output_pane.Traits.steps` (a list of locations) makes a step take one row at a time, and `Traits.commands` makes it take the WHOLE LINE, because a command list (`ThemeSel`/`FontSel`) holds words to run and there is no path inside `Theme gruvbox` to pick out. Tab on what `n` selected wears the theme, which is the same middle click on the row is. `]d`/`[d` are helix's diagnostic motions, a different binding, and they do still jump to each diagnostic (`docs/lsp.md`) | pardes-specific | @@ -224,7 +224,9 @@ grew `sels` + `primary`, emitted only when there is more than one range. | `_` | trim whitespace off both ends of every range | empty and all-whitespace ranges drop; nothing left = collapse + keep primary (helix) | helix-verified | | `o` / `O` | open n lines, one cursor per line | helix `open` with a count; this is why the `o-count` golden gained a `sels` field | helix-verified | | every motion/operator | acts at every cursor | replayed last-range-first, so an edit never disturbs a range still waiting; each pass's result is remembered as a distance from the END of the text, which an earlier edit cannot move | helix-verified (56 msel-* cases) | -| `y` with several ranges | joins the ranges' text with newlines into the ONE register | helix keeps a register VALUE per range and pastes value[i] at range[i]. Waived (`msel-yank-paste`) | waived | +| `y` with several ranges | one value per range, pasted back value i at range i by `p`/`P`/`R` and insert `Ctrl-r`; the acme cut/paste chords and a paste into a terminal take the values joined by newlines | `Registers.zig` | helix-verified | +| `"` | the next command's register: any character names one of its own. Computed ones: `_` swallows writes and reads nothing (`"_d`), `#` is each range's number from 1, `.` each range's text, `%` the file's name, `/` the last `s`/`S` pattern; `+`/`*` the system clipboard. A count typed before `"` stays the command's | helix `select_register` | helix-verified | +| insert `Ctrl-r ` | type this range's value of the register (`Ctrl-r #` numbers the cursors). Esc after `Ctrl-r` only cancels it. `Ctrl-r +` reads what pardes last put on the clipboard, not the desktop's | helix `insert_register` | helix-verified | | `a` … `Esc` with several ranges | the primary's appended-over span is restored; the others collapse to bare cursors | `Pane.append_at` is a single field. Waived (`msel-append`) | waived | | `&` | align selections into columns: the k-th range of each line is column k, and spaces go in before each range until its head reaches the column's widest head, in display cells (`File.rawDisplayCol`) | helix `align_selections` as of the harness's helix (25.07.1 grouped columns differently). A range over several lines refuses. A TAB counts as `tab_width` cells, not up to the next stop | helix-verified | | `Alt-)` / `Alt-(` / `Alt-)` | rotate the CONTENTS of the selections forward / back by one range (n ranges), in one edit; each range comes back over the text it now holds and the primary moves with its text | helix `rotate_selection_contents_*` as of the harness's helix: 25.07.1 read the count as a GROUP size instead (rotate by one within each run of n ranges) and left the primary where it was, which is what helix-golf's `invert_dictionary_2` relies on | helix-verified | @@ -342,7 +344,6 @@ text. | `]f [f ]t [t ]a [a ]c [c ]e [e ]T [T ]x [x` | TS unimpaired jumps | tree-sitter | | `]g [g ]G [G` | git change jumps | needs VCS diff state | | insert `Ctrl-x` | completion menu | completion exists, but not as a popup: insert-mode Tab straight after a `.` opens a buffer of candidate DECLARATIONS (section A). helix's menu itself is skipped | -| `"` ``, insert `Ctrl-r` | register select / insert | registers — one yank register and no way to name a second; the system clipboard is not spelled as a register here either, it is the five `SPC` commands in A | | `Q` / `q` | record / replay macro | macros — needs replayable input log | | `Ctrl-s` (normal) | save jumplist position | jumplist itself is implemented (`Ctrl-o`/`Ctrl-i`, section A); only the explicit save point is skipped | | `Alt-u` / `Alt-U` | undo-history earlier/later | history timeline — linear snapshot u/U covers pardes | @@ -388,12 +389,12 @@ Files (all in `test/hxcases/`): (runs the `hx-harness` binary from the helix checkout; override with `$HX_HARNESS`). Only needed when cases change — the diff itself runs offline. -- `waivers.jsonl` — named exemptions, each with a reason. Four live ones: +- `waivers.jsonl` — named exemptions, each with a reason. Three live ones: `wiX-edit-drops-sel` and `msel-append` (helix maps selections through - insert-mode edits, pardes does not), `alt-c-window-op` (the pardes - window op deliberately shadows helix change-noyank) and `msel-yank-paste` - (one yank register, not one value per range). `sel-regex-caret` and - `sel-regex-dot-newline` went when `s`/`S` began searching line by line. + insert-mode edits, pardes does not) and `alt-c-window-op` (the pardes + window op deliberately shadows helix change-noyank). `msel-yank-paste` + went with registers of one value per range; `sel-regex-caret` and + `sel-regex-dot-newline` when `s`/`S` began searching line by line. - `parity.jsonl` — 80 further cases, used only by the parity gate below. - `parity-waivers.jsonl` — 14 named exemptions for the parity gate, in three classes: one deliberate pardes binding (`ctrl-b-page`, since `Ctrl-b` IS the diff --git a/docs/selections.md b/docs/selections.md index 5b992cc4..0f000e2c 100644 --- a/docs/selections.md +++ b/docs/selections.md @@ -74,19 +74,18 @@ A parsed action has a scope (`modal.Normal.Action.scope`). - An undo snapshot (`File.Snapshot`) holds the content and the PRIMARY range. Undo puts the primary back and leaves the other ranges where they were; helix restores the whole selection of that revision. -- There is ONE register, `Pardes.yank`, written by `y`, `d` and `c` and read - by `p`, `P` and `R`. A yank at several ranges joins their texts with - newlines into it, and a paste puts that whole value at every range. +- Registers (`Registers.zig`) hold one value per range. A yank under the + replay fills slot `Pardes.multi_index` of `multi_count`, and `p`, `P`, `R` + and insert `Ctrl-r` read slot i at range i, the last value standing in + for missing ones. `"` names the register (`Pardes.register` for the + length of one command); `_ # . % /` are computed or special and `+`/`*` + is the system clipboard. The acme chords and a paste into a terminal read + the default register joined by newlines. - `Alt-.` repeats the last `f`/`t`/`F`/`T`. There is no `.` and there are no macros. ## Where it differs from helix -- Registers: helix keeps one value PER RANGE and pastes value `i` at range - `i`; it has named registers (`"a`), special ones (`#` range indices, - `.` the selection, `/` the search, `_` the black hole) and inserts a - register in insert mode with `Ctrl-r`. None exist here (waiver - `msel-yank-paste`). - Insert mode: helix maps every range through each keystroke's edit, so a range an `i`/`a` started from stretches over what is typed and keeps its anchor. Here only the cursor cells move, and after Esc only the primary's diff --git a/src/Registers.zig b/src/Registers.zig new file mode 100644 index 00000000..d2a42434 --- /dev/null +++ b/src/Registers.zig @@ -0,0 +1,106 @@ +//! helix's registers: named stores of text, each holding one VALUE PER RANGE +//! of the selection that wrote it. `"` is the default, `+` the one the +//! system clipboard is copied from, `/` the last s/S pattern, `@` the last +//! macro; any other character names a register of its own. The registers +//! computed from the editor rather than stored (`_`, `#`, `.`, `%`) and the +//! clipboard's paste side are read in edit.zig, which has the pane at hand. +const std = @import("std"); + +const Registers = @This(); + +list: std.ArrayList(Reg) = .empty, + +pub const Reg = struct { + name: u21, + /// gpa-owned, one per range, in document order + values: [][]u8, + /// the values joined by newlines, for the readers that take one text + /// (the acme chords, a paste into a terminal, the clipboard); gpa-owned, + /// made on first read + joined: ?[]u8 = null, +}; + +pub const default = '"'; + +pub fn deinit(r: *Registers, gpa: std.mem.Allocator) void { + for (r.list.items) |*reg| freeReg(gpa, reg); + r.list.deinit(gpa); + r.* = .{}; +} + +fn freeReg(gpa: std.mem.Allocator, reg: *Reg) void { + for (reg.values) |v| gpa.free(v); + gpa.free(reg.values); + if (reg.joined) |j| gpa.free(j); +} + +pub fn get(r: *Registers, name: u21) ?*Reg { + for (r.list.items) |*reg| if (reg.name == name) return reg; + return null; +} + +/// Value `i` of register `name`: a register holding fewer values than there +/// are ranges repeats its last (helix paste_impl). +pub fn value(r: *Registers, name: u21, i: usize) ?[]const u8 { + const reg = r.get(name) orelse return null; + if (reg.values.len == 0) return null; + return reg.values[@min(i, reg.values.len - 1)]; +} + +/// Store value `i` of `n`. `fresh` starts the register over with `n` empty +/// values; the replay across ranges passes it on its first pass only, so +/// every range fills its own slot. +pub fn put(r: *Registers, gpa: std.mem.Allocator, name: u21, bytes: []const u8, i: usize, n: usize, fresh: bool) void { + const copy = gpa.dupe(u8, bytes) catch return; + const reg = r.get(name) orelse blk: { + r.list.append(gpa, .{ .name = name, .values = &.{} }) catch { + gpa.free(copy); + return; + }; + break :blk &r.list.items[r.list.items.len - 1]; + }; + if (fresh or reg.values.len != n) { + const values = gpa.alloc([]u8, n) catch { + gpa.free(copy); + return; + }; + for (values) |*v| v.* = &.{}; + freeReg(gpa, reg); + reg.* = .{ .name = name, .values = values }; + } + gpa.free(reg.values[i]); + reg.values[i] = copy; + if (reg.joined) |j| gpa.free(j); + reg.joined = null; +} + +/// The whole register as one text: its values joined by newlines, no +/// newline added after a value that already ends in one. +pub fn text(r: *Registers, gpa: std.mem.Allocator, name: u21) ?[]const u8 { + const reg = r.get(name) orelse return null; + if (reg.joined) |j| return j; + var out: std.ArrayList(u8) = .empty; + for (reg.values, 0..) |v, i| { + if (i > 0 and !std.mem.endsWith(u8, reg.values[i - 1], "\n")) out.append(gpa, '\n') catch return null; + out.appendSlice(gpa, v) catch return null; + } + reg.joined = out.toOwnedSlice(gpa) catch return null; + return reg.joined; +} + +test "a register holds a value per range and joins them for one-text readers" { + const gpa = std.testing.allocator; + var r: Registers = .{}; + defer r.deinit(gpa); + try std.testing.expect(r.value(default, 0) == null); + // a replay fills the last range first + r.put(gpa, default, "two", 1, 2, true); + r.put(gpa, default, "one\n", 0, 2, false); + try std.testing.expectEqualStrings("one\n", r.value(default, 0).?); + try std.testing.expectEqualStrings("two", r.value(default, 1).?); + try std.testing.expectEqualStrings("two", r.value(default, 5).?); + try std.testing.expectEqualStrings("one\ntwo", r.text(gpa, default).?); + r.put(gpa, 'a', "x", 0, 1, true); + try std.testing.expectEqualStrings("x", r.text(gpa, 'a').?); + try std.testing.expectEqualStrings("one\ntwo", r.text(gpa, default).?); +} diff --git a/src/Text.zig b/src/Text.zig index 43dd8a95..7ad243a1 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -66,6 +66,8 @@ select: bool = false, /// non-vertical range write resets it to -1. sticky_col: i32 = -1, append_at: ?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: u8 = 0, diff --git a/src/config.zig b/src/config.zig index 85a6bc59..4412ef0d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -492,6 +492,7 @@ pub const match_around = 'a'; pub const surround_add = 's'; pub const surround_replace = 'r'; pub const surround_delete = 'd'; +pub const register_prefix = '"'; pub const goto_paragraph: []const Chord = &.{.{ .cp = 'p' }}; pub const add_newline: []const Chord = &.{.{ .cp = ' ' }}; @@ -557,6 +558,7 @@ pub const escape: []const Chord = &.{.{ .cp = Key.escape }}; pub const insert_backspace_alias: []const Chord = &.{.{ .cp = 'h', .ctrl = true }}; pub const insert_enter_alias: []const Chord = &.{.{ .cp = 'j', .ctrl = true }}; pub const insert_delete_alias: []const Chord = &.{.{ .cp = 'd', .ctrl = true }}; +pub const insert_register: []const Chord = &.{.{ .cp = 'r', .ctrl = true }}; pub const delete_word_backward: []const Chord = &.{ .{ .cp = 'w', .ctrl = true }, .{ .cp = Key.backspace, .alt = true } }; pub const delete_word_forward: []const Chord = &.{ .{ .cp = 'd', .alt = true }, .{ .cp = Key.delete, .alt = true } }; pub const kill_to_line_start: []const Chord = &.{.{ .cp = 'u', .ctrl = true }}; diff --git a/src/edit.zig b/src/edit.zig index 24354df8..14d8b7ed 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -26,23 +26,75 @@ const hit = pardes.hit; const sel_slot = pardes.sel_slot; const Effect = pardes.Effect; const Pardes = pardes.Pardes; +const Registers = pardes.Registers; +/// Write `text` as this range's value of the register the running command +/// names (`"`), the default one otherwise. `_` swallows it, and the +/// registers computed from the editor (`#`, `.`, `%`) cannot be written. +/// `+` and `*` are the system clipboard: the value is sent there too. pub fn setYank(p: *Pardes, text: []const u8) void { - if (p.multi_on and !p.multi_first) { - const old = p.yank orelse ""; - const sep: []const u8 = if (text.len > 0 and text[text.len - 1] == '\n') "" else "\n"; - const joined = std.fmt.allocPrint(p.gpa, "{s}{s}{s}", .{ text, sep, old }) catch return; - if (p.yank) |y| p.gpa.free(y); - p.yank = joined; - return; + var name: u21 = if (p.register != 0) p.register else Registers.default; + switch (name) { + '_', '#', '.', '%' => return, + '*' => name = '+', + else => {}, } - if (p.yank) |y| p.gpa.free(y); - p.yank = p.gpa.dupe(u8, text) catch null; + const one = !p.multi_on; + p.registers.put(p.gpa, name, text, if (one) 0 else p.multi_index, if (one) 1 else p.multi_count, one or p.multi_first); + if (name == '+' and (one or p.multi_first)) p.emit(.{ .set_clipboard = {} }); } pub fn setClipboard(p: *Pardes, text: []const u8) void { + const named = p.register; + p.register = '+'; + defer p.register = named; setYank(p, text); - if (!p.multi_on or p.multi_first) p.emit(.{ .set_clipboard = {} }); +} + +/// Value `i` of register `name` as the command at range `i` reads it, the +/// computed registers included: `#` is the range's number from 1, `.` its +/// text, `%` the file's name, `_` nothing. Scratch- or register-owned. +pub fn registerValue(p: *Pardes, t: *Text, name: u21) ?[]const u8 { + const i = if (p.multi_on) p.multi_index else 0; + return switch (name) { + '_' => null, + '#' => std.fmt.allocPrint(p.scratch.allocator(), "{d}", .{i + 1}) catch null, + '.' => selText(p, t), + '%' => if (t.what == .body) if (t.pane()) |pane| (if (pane.file) |f| f.path else null) else null else null, + else => p.registers.value(name, i), + }; +} + +/// the text of the range under the cursor: the selection, or the cursor's +/// own character +fn selText(p: *Pardes, t: *Text) []const u8 { + if (t.msel.active) return yankRows(p, t, @min(t.msel.r0, t.msel.r1), @max(t.msel.r0, t.msel.r1)); + const save = t.vsel; + defer t.vsel = save; + if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false }; + return vselText(p, t); +} + +/// `p` / `P` / `R` from the register the command names: this range's value +/// of it. The clipboard's is asked of the shell and pasted when it answers, +/// once, at the primary. +pub fn pasteRegister(p: *Pardes, t: *Text, how: enum { after, before, replace }, count: usize) void { + const name: u21 = if (p.register != 0) p.register else Registers.default; + if (name == '+' or name == '*') { + if (!normal.multiOnce(p)) return; + const pane = t.pane() orelse return; + return clipRequest(p, p.paneIdOf(pane) orelse return, switch (how) { + .after => .after, + .before => .before, + .replace => .replace, + }); + } + const y = registerValue(p, t, name) orelse return; + switch (how) { + .after => pasteText(p, t, y, false, count), + .before => pasteText(p, t, y, true, count), + .replace => replaceWithText(p, t, y), + } } /// Where a `SPC p` / `SPC P` / `SPC R` goes once the shell answers. @@ -125,6 +177,10 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { if (pv.selection_text.len > 0) setClipboard(p, pv.selection_text); return; }; + // helix's `"+y`: the clipboard register, and only it + const named = p.register; + p.register = '+'; + defer p.register = named; if (pane.body.nsel > 0 and !main_only) { normal.replaySels(p, &pane.body, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); } else { @@ -133,7 +189,6 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { normalYank(p, &pane.body); pane.body.nsel = others; } - p.emit(.{ .set_clipboard = {} }); } /// tag + '\n' + body: the full selectable pane text, a row to a screen row @@ -286,6 +341,7 @@ pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { pub fn exitInsert(p: *Pardes, t: *Text) void { t.mode = .normal; + t.reg_wait = false; t.msel.active = false; t.normal.clear(); if (t.append_at) |aa| { @@ -565,6 +621,19 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace }); if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter }); if (hit(key, config.insert_delete_alias)) return insertKey(p, t, .{ .cp = Key.delete }); + // Ctrl-r : type this range's value of the register (helix + // insert_register) + if (t.reg_wait) { + t.reg_wait = false; + if (key.ctrl or key.alt or key.cp >= 0xF0000) return; + const y = registerValue(p, t, key.cp) orelse return; + if (y.len > 0) insertKey(p, t, .{ .cp = key.cp, .text = y }); + return; + } + if (hit(key, config.insert_register)) { + t.reg_wait = true; + return; + } t.vsel.active = false; if (!t.cur_pinned) pinPaneCursor(p, t); _ = clampFileCursor(t); @@ -1132,8 +1201,9 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) void { /// `R`: replace the selection (or the cursor char) with the DEFAULT /// register. `SPC R` is the same verb over the system clipboard. -pub fn normalReplaceYank(p: *Pardes, t: *Text) void { - replaceWithText(p, t, p.yank orelse return); +/// The acme chords' replace: the default register as one text. +pub fn chordReplace(p: *Pardes, t: *Text) void { + replaceWithText(p, t, p.registers.text(p.gpa, Registers.default) orelse return); } /// The pasted text becomes the selection, in the direction the replaced one @@ -1957,16 +2027,20 @@ test "only the SPC clipboard commands cross to the system clipboard" { _ = drainedEffect(p, .set_clipboard); p.update(.{ .key = .{ .cp = 'y' } }); - try std.testing.expect(p.yank != null and p.yank.?.len > 0); + const plain = p.registers.text(gpa, Registers.default) orelse return error.MissingYank; + try std.testing.expect(plain.len > 0); try std.testing.expect(!drainedEffect(p, .set_clipboard)); p.update(.{ .key = .{ .cp = 'd' } }); try std.testing.expect(!drainedEffect(p, .set_clipboard)); - // `SPC y` is the one that does, and it puts the SAME text there that `y` - // put in the register — it is the ordinary yank path plus the mirror. + // `SPC y` is the one that does: helix's `"+y`, the ordinary yank into + // the clipboard register instead of the default one. p.update(.{ .key = .{ .cp = ' ' } }); p.update(.{ .key = .{ .cp = 'y' } }); - const yanked = p.yank orelse return error.MissingYank; + const yanked = try gpa.dupe(u8, p.registers.text(gpa, Registers.default) orelse ""); + defer gpa.free(yanked); + const clip: []const u8 = p.registers.text(gpa, '+') orelse ""; + try std.testing.expect(clip.len > 0); try std.testing.expect(drainedEffect(p, .set_clipboard)); const before = pane.file.?.content.len; @@ -1980,14 +2054,14 @@ test "only the SPC clipboard commands cross to the system clipboard" { try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "PASTED") != null); // ...and it did NOT land in the register on its way past, nor echo back // out to the clipboard it came from. - try std.testing.expectEqualStrings(yanked, p.yank orelse ""); + try std.testing.expectEqualStrings(yanked, p.registers.text(gpa, Registers.default) orelse ""); try std.testing.expect(!drainedEffect(p, .set_clipboard)); // An UNSOLICITED paste — the outer terminal's bracketed paste, a Cmd-V — // is the same event with no request behind it, and means paste after. p.update(.{ .paste = "UNASKED" }); try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "UNASKED") != null); - try std.testing.expectEqualStrings(yanked, p.yank orelse ""); + try std.testing.expectEqualStrings(yanked, p.registers.text(gpa, Registers.default) orelse ""); // A request the shell never answers dies at the next keystroke rather // than firing late into whatever pane is focused by then. diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 46bd5ffc..8f6248ce 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -4385,7 +4385,7 @@ test "the headless grid host round-trips a yank back as a paste" { core.update(.{ .key = .{ .cp = ' ' } }); core.update(.{ .key = .{ .cp = 'y' } }); while (core.nextEffect()) |e| core.perform(e); - const yanked = core.yank orelse return error.MissingYank; + const yanked = core.registers.text(core.gpa, '+') orelse return error.MissingYank; try std.testing.expect(yanked.len > 0); const before = pane.file.?.content.len; diff --git a/src/look.zig b/src/look.zig index d7e763d3..5e2d6068 100644 --- a/src/look.zig +++ b/src/look.zig @@ -502,7 +502,11 @@ const SearchStart = enum { top, cursor }; pub fn submitSearch(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - if (normal.selRegexArmed(pane)) |a| return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.split); + if (normal.selRegexArmed(pane)) |a| { + // helix keeps the pattern in `/` + if (a.pat.len > 0) p.registers.put(p.gpa, '/', a.pat, 0, 1, true); + return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.split); + } const armed = pane.promptText() orelse return; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; if (std.mem.startsWith(u8, armed, config.rename_marker)) return p.lspRequest(id, .rename, armed[slash + 1 ..]); diff --git a/src/modal.zig b/src/modal.zig index aadaab00..aec1c579 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -15,6 +15,7 @@ pub const Normal = struct { prefix_replace, prefix_next, prefix_prev, + prefix_register, goto_file_start, goto_last_line, @@ -160,6 +161,7 @@ pub const Normal = struct { replace, next, prev, + register, }; pub const MatchSub = enum(u8) { @@ -176,6 +178,8 @@ pub const Normal = struct { prefix: Prefix = .none, match_sub: MatchSub = .none, held_char: u21 = 0, + /// `"`: the register the next command names, 0 for none + register: u21 = 0, pub fn clear(state: *State) void { state.* = .{}; @@ -491,6 +495,14 @@ pub const Normal = struct { if (key.has(.goto_diagnostic_end)) return resultAction(.{ .diagnostic = .{ .direction = direction, .endpoint = true } }); return .ignored; }, + .register => { + state.prefix = .none; + const char = key.literal() orelse return .ignored; + state.register = char; + // the count typed before `"` is still the command's + state.count = if (counted.explicit) count else 0; + return .pending; + }, .none => {}, } @@ -505,6 +517,7 @@ pub const Normal = struct { if (key.has(.prefix_next)) return armPrefix(state, .next, if (counted.explicit) count else 0); if (key.has(.prefix_prev)) return armPrefix(state, .prev, if (counted.explicit) count else 0); if (key.has(.prefix_match)) return armPrefix(state, .match, 0); + if (key.has(.prefix_register)) return armPrefix(state, .register, if (counted.explicit) count else 0); if (key.has(.move_left)) return resultAction(.{ .move = .{ .motion = .left, .count = count } }); if (key.has(.move_right)) return resultAction(.{ .move = .{ .motion = .right, .count = count } }); diff --git a/src/mouse.zig b/src/mouse.zig index f222b5da..91ec41a6 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -963,8 +963,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut) { if (t.vsel.active) edit.normalDelete(p, t, true); } else if (t.vsel.active) { - edit.normalReplaceYank(p, t); - } else edit.pasteText(p, t, p.yank orelse return, true, 1); + edit.chordReplace(p, t); + } else edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); return; } if (pane.body.mode == .tty) { @@ -973,7 +973,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { pane.sel[sel_slot].state = .none; // drop the sweep highlight } if (cut) return; - const y = p.yank orelse return; + const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; if (panes.Terminal.reportsMouse(pane)) { const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); @@ -1016,11 +1016,11 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut) { if (pane.body.vsel.active) edit.normalDelete(p, &pane.body, true); } else if (pane.body.vsel.active) { - edit.normalReplaceYank(p, &pane.body); + edit.chordReplace(p, &pane.body); } else if (pane.file) |*f| { // bare cursor: splice the register in literally (no linewise // magic) so a paste right after a cut restores the text exactly - const y = p.yank orelse return; + const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }; edit.pushUndo(p, &pane.body); @@ -1039,7 +1039,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { pane.body.cur_pinned = true; pane.body.sticky_col = -1; pane.ensureCursorVisible(); - } else edit.pasteText(p, &pane.body, p.yank orelse return, true, 1); + } else edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); } test "plain left click clears explicit modal selection" { diff --git a/src/normal.zig b/src/normal.zig index 5a6c1cd5..f5e868a4 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -35,6 +35,7 @@ fn roleBindingName(comptime role: modal.Normal.Role) []const u8 { .prefix_replace => "replace_prefix", .prefix_next => "next_prefix", .prefix_prev => "prev_prefix", + .prefix_register => "register_prefix", else => @tagName(role), }; } @@ -149,6 +150,7 @@ const KeyState = struct { find_op: u8, find_ch: u21, append_at: @FieldType(Text, "append_at"), + reg_wait: bool, fn of(t: *Text) KeyState { return .{ @@ -158,6 +160,7 @@ const KeyState = struct { .find_op = t.find_op, .find_ch = t.find_ch, .append_at = t.append_at, + .reg_wait = t.reg_wait, }; } @@ -168,6 +171,7 @@ const KeyState = struct { t.find_op = s.find_op; t.find_ch = s.find_ch; t.append_at = s.append_at; + t.reg_wait = s.reg_wait; } }; @@ -227,6 +231,8 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { while (i > 0) { i -= 1; p.multi_first = passes == 0; + p.multi_index = i; + p.multi_count = n; passes += 1; saved.into(t); t.nsel = 0; // the handler underneath sees ONE selection @@ -284,11 +290,16 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { } pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { + // `"` is held by the parser until the command it names arrives + const named = t.normal.register; const parsed = modal.Normal.parse(&t.normal, normalInput(key)); const semantic = switch (parsed) { .pending, .ignored, .unbound => return, .action => |value| value, }; + t.normal.register = 0; + p.register = named; + defer p.register = 0; if (t.nsel == 0 or semantic.scope() == .once) return executeNormalAction(p, t, semantic); replaySels(p, t, .{ .normal = semantic }); @@ -534,9 +545,9 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .delete_noyank => return edit.normalDelete(p, t, false), .change => return edit.normalChange(p, t), .yank => return edit.normalYank(p, t), - .replace_with_yank => return edit.normalReplaceYank(p, t), - .paste_after => return edit.pasteText(p, t, p.yank orelse return, false, op.count), - .paste_before => return edit.pasteText(p, t, p.yank orelse return, true, op.count), + .replace_with_yank => return edit.pasteRegister(p, t, .replace, op.count), + .paste_after => return edit.pasteRegister(p, t, .after, op.count), + .paste_before => return edit.pasteRegister(p, t, .before, op.count), .switch_case => return edit.normalCase(p, t, .toggle), .lowercase => return edit.normalCase(p, t, .lower), .uppercase => return edit.normalCase(p, t, .upper), diff --git a/src/pardes.zig b/src/pardes.zig index 9821839f..e4645d70 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -17,6 +17,7 @@ pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); pub const body_layer = @import("body_layer.zig"); pub const Messages = @import("Messages.zig"); +pub const Registers = @import("Registers.zig"); pub const Pipe = @import("Pipe.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; @@ -453,6 +454,7 @@ test { _ = @import("regexp.zig"); _ = @import("edit.zig"); _ = @import("Messages.zig"); + _ = @import("Registers.zig"); _ = @import("selection_pipe.zig"); _ = @import("Pipe.zig"); _ = @import("colors.zig"); @@ -2326,7 +2328,7 @@ test "a host with no methods at all is a complete in-process pardes" { try std.testing.expectEqual(before, p.panes[0].?.terminal.?.vt.screens.active.cursor.y); // the clipboard round-trips through the in-process one - p.yank = try gpa.dupe(u8, "copied"); + p.registers.put(gpa, '+', "copied", 0, 1, true); p.perform(.set_clipboard); try std.testing.expectEqualStrings("copied", p.fallback.clipboard.items); @@ -4003,6 +4005,14 @@ pub const Pardes = struct { multi_on: bool = false, multi_first: bool = false, multi_stop: bool = false, + /// While a key is replayed across the ranges: which range this pass is, + /// in document order, and how many there are. A register value belongs + /// to its range by this index. + multi_index: usize = 0, + multi_count: usize = 1, + /// The register the running normal command names (`"`); 0 for the + /// default one. + register: u21 = 0, leader_on: bool = false, leader_keys: [4]u8 = undefined, leader_n: u8 = 0, @@ -4085,7 +4095,7 @@ pub const Pardes = struct { in_head: usize = 0, in_len: usize = 0, - yank: ?[]u8 = null, + registers: Registers = .{}, clip_pending: ?edit.ClipRequest = null, /// the last serialized dump (gpa-owned), read by the write_dump effect dump_out: ?[]u8 = null, @@ -4256,7 +4266,7 @@ pub const Pardes = struct { const gpa = p.gpa; for (&p.col_tags) |*t| t.deinit(gpa); p.global_tag.deinit(gpa); - if (p.yank) |y| gpa.free(y); + p.registers.deinit(gpa); if (p.dump_out) |d| gpa.free(d); p.fallback.deinit(); if (p.last_dump) |d| gpa.free(d); @@ -4826,7 +4836,7 @@ pub const Pardes = struct { } }, .set_clipboard => { - const text = p.yank orelse ""; + const text = p.registers.text(p.gpa, '+') orelse ""; if (v.set_clipboard) |f| f(p.host.ctx, text) else p.fallback.setClipboard(text); }, // No desktop to ask: answer from the in-process clipboard at once, @@ -5162,7 +5172,7 @@ pub const Pardes = struct { // in it the chord is the program's -- vim's visual block, // readline's quoted-insert -- and swallowing it would make // Ctrl-V a black hole in every full-screen application. - if (p.yank) |text| return edit.typeToTty(p, p.active, pane, text); + if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.active, pane, text); } return panes.Terminal.forwardKey(p, p.active, key); } @@ -5310,7 +5320,7 @@ pub const Pardes = struct { switch (t.mode) { .normal => normal.handleNormal(p, t, key), .insert => { - if (hit(key, config.escape)) return edit.exitInsert(p, t); + if (hit(key, config.escape) and !t.reg_wait) return edit.exitInsert(p, t); edit.handleInsert(p, t, key); }, .tty => panes.Terminal.forwardKey(p, p.active, key), diff --git a/test/hxcases/cases.jsonl b/test/hxcases/cases.jsonl index 487cd445..7ba44f09 100644 --- a/test/hxcases/cases.jsonl +++ b/test/hxcases/cases.jsonl @@ -442,6 +442,19 @@ {"name": "msel-collapse", "pane": "file", "text": "abcd\nabcd\n", "keys": "vllC;"} {"name": "msel-flip", "pane": "file", "text": "abcd\nabcd\n", "keys": "vllC"} {"name": "msel-yank-paste", "pane": "file", "text": "ab\ncd\n", "keys": "Cyp"} +{"name": "reg-named-yank-paste", "pane": "file", "text": "ab cd\n", "keys": "\"ayw\"ap"} +{"name": "reg-named-keeps-default", "pane": "file", "text": "ab cd\n", "keys": "yw\"ay\"_dp"} +{"name": "reg-blackhole-delete", "pane": "file", "text": "ab cd\n", "keys": "yw\"_dP"} +{"name": "msel-reg-paste-per-range", "pane": "file", "text": "ab\ncd\n", "keys": "Cyl2Pp"} +{"name": "msel-reg-fewer-values", "pane": "file", "text": "ab\ncd\nef\n", "keys": "yCCp"} +{"name": "msel-reg-replace-per-range", "pane": "file", "text": "ab\ncd\n", "keys": "CyRy"} +{"name": "msel-reg-more-values-one-range", "pane": "file", "text": "ab\ncd\n", "keys": "Cy,p"} +{"name": "reg-index-insert", "pane": "file", "text": "x\nx\nx\n", "keys": "%i#"} +{"name": "reg-search-paste", "pane": "file", "text": "ab\n", "keys": "%sb\"/p"} +{"name": "reg-count-before-quote", "pane": "file", "text": "ab\n", "keys": "y2\"ap"} +{"name": "reg-count-after-quote", "pane": "file", "text": "ab\n", "keys": "\"ay\"a3p"} +{"name": "reg-ctrl-r-named", "pane": "file", "text": "ab\n", "keys": "\"aylia"} +{"name": "reg-ctrl-r-esc", "pane": "file", "text": "ab\n", "keys": "ix"} {"name": "msel-esc-keeps", "pane": "file", "text": "aa\nbb\n", "keys": "C"} {"name": "msel-select-mode", "pane": "file", "text": "abcd\nabcd\n", "keys": "Cvl"} {"name": "msel-open-count", "pane": "file", "text": "ab\n", "keys": "2O"} diff --git a/test/hxcases/goldens.jsonl b/test/hxcases/goldens.jsonl index 006524e8..f6a6aada 100644 --- a/test/hxcases/goldens.jsonl +++ b/test/hxcases/goldens.jsonl @@ -442,6 +442,19 @@ {"name":"msel-collapse","text":"abcd\nabcd\n","mode":"select","cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}},{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2}}],"primary":1} {"name":"msel-flip","text":"abcd\nabcd\n","mode":"select","cursor":{"row":1,"col":0},"anchor":{"row":1,"col":2},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":2}},{"cursor":{"row":1,"col":0},"anchor":{"row":1,"col":2}}],"primary":1} {"name":"msel-yank-paste","text":"aab\nccd\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}}],"primary":1} +{"name":"reg-named-yank-paste","text":"ab acd\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}} +{"name":"reg-named-keeps-default","text":"cad\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}} +{"name":"reg-blackhole-delete","text":"acd\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}} +{"name":"msel-reg-paste-per-range","text":"aaaab\nccccd\n","mode":"normal","cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}}],"primary":1} +{"name":"msel-reg-fewer-values","text":"aab\ncad\neaf\n","mode":"normal","cursor":{"row":2,"col":1},"anchor":{"row":2,"col":1},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}},{"cursor":{"row":2,"col":1},"anchor":{"row":2,"col":1}}],"primary":2} +{"name":"msel-reg-replace-per-range","text":"ab\ncd\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0}}],"primary":0} +{"name":"msel-reg-more-values-one-range","text":"ab\ncad\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}} +{"name":"reg-index-insert","text":"1x\n2x\n3x\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}},{"cursor":{"row":2,"col":1},"anchor":{"row":2,"col":1}}],"primary":0} +{"name":"reg-search-paste","text":"abb\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}} +{"name":"reg-count-before-quote","text":"ab\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}} +{"name":"reg-count-after-quote","text":"aaaab\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":1}} +{"name":"reg-ctrl-r-named","text":"aab\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}} +{"name":"reg-ctrl-r-esc","text":"xab\n","mode":"insert","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}} {"name":"msel-esc-keeps","text":"aa\nbb\n","mode":"normal","cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0}}],"primary":1} {"name":"msel-select-mode","text":"abcd\nabcd\n","mode":"select","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1} {"name":"msel-open-count","text":"\n\nab\n","mode":"insert","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0}}],"primary":0} diff --git a/test/hxcases/waivers.jsonl b/test/hxcases/waivers.jsonl index 01e6cfa7..8ac3bd9c 100644 --- a/test/hxcases/waivers.jsonl +++ b/test/hxcases/waivers.jsonl @@ -1,4 +1,3 @@ {"name":"wiX-edit-drops-sel","reason":"Insert edits clear the selection instead of tracking its anchor.","reference":{"name":"wiX-edit-drops-sel","text":"Xalpha beta\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":6}},"expected":{"name":"wiX-edit-drops-sel","text":"Xalpha beta\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}}} {"name":"alt-c-window-op","reason":"Alt-c moves a pane to a new column instead of Helix's change-noyank.","reference":{"name":"alt-c-window-op","text":"bc def\n","mode":"insert","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},"expected":{"name":"alt-c-window-op","text":"abc def\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}}} {"name":"msel-append","reason":"Append-mode selection origins are tracked only for the primary selection.","reference":{"name":"msel-append","text":"aza\nbzb\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1},"expected":{"name":"msel-append","text":"aza\nbzb\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1}} -{"name":"msel-yank-paste","reason":"Pardes has one combined yank register, not one value per selection.","reference":{"name":"msel-yank-paste","text":"aab\nccd\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}}],"primary":1},"expected":{"name":"msel-yank-paste","text":"aa\ncb\nca\ncd\n","mode":"normal","cursor":{"row":3,"col":0},"anchor":{"row":2,"col":1},"sels":[{"cursor":{"row":1,"col":0},"anchor":{"row":0,"col":1}},{"cursor":{"row":3,"col":0},"anchor":{"row":2,"col":1}}],"primary":1}} diff --git a/test/panes.zig b/test/panes.zig index d0551cfc..cbf9d097 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -325,7 +325,7 @@ const TagNavigationTests = struct { try std.testing.expectEqual(@as(i32, 0), pane.tag.cur_col); key(p, 'E'); key(p, 'y'); - try std.testing.expectEqualStrings("/test.txt", p.yank.?); + try std.testing.expectEqualStrings("/test.txt", p.registers.text(p.gpa, '"').?); // an edit that reaches into it is refused, the cursor with it const before = try std.testing.allocator.dupe(u8, try pardes.edit.flatSurface(p, &pane.tag)); defer std.testing.allocator.free(before); @@ -848,12 +848,12 @@ const TtySelectionTests = struct { const x = rect.x + config.GUTTER; const y = p.bodyTop(pane, rect); JumpSelectionTests.drag(p, x + 1, y, x + 3, y); - try std.testing.expectEqualStrings("lph", p.yank orelse return error.MissingAutomaticTtyYank); + try std.testing.expectEqualStrings("lph", p.registers.text(p.gpa, '"') orelse return error.MissingAutomaticTtyYank); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); p.update(.{ .key = .{ .cp = 'l' } }); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); p.update(.{ .key = .{ .cp = 'y' } }); - try std.testing.expectEqualStrings("a", p.yank.?); + try std.testing.expectEqualStrings("a", p.registers.text(p.gpa, '"').?); try noChildInput(p); } @@ -881,7 +881,7 @@ const TtySelectionTests = struct { const expected = if (prompt) "$ ab" else "lph\nrav"; try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); - try std.testing.expectEqualStrings(expected, p.yank orelse return error.MissingAutomaticTtyYank); + try std.testing.expectEqualStrings(expected, p.registers.text(p.gpa, '"') orelse return error.MissingAutomaticTtyYank); try noChildInput(p); try std.testing.expect(p.executeBuiltinLine(0, "ClipYank")); @@ -897,7 +897,7 @@ const TtySelectionTests = struct { } try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); p.update(.{ .key = .{ .cp = 'y' } }); - try std.testing.expectEqualStrings(expected, p.yank.?); + try std.testing.expectEqualStrings(expected, p.registers.text(p.gpa, '"').?); try noChildInput(p); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); @@ -908,7 +908,7 @@ const TtySelectionTests = struct { _ = try p.render(frame.allocator()); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); - try std.testing.expectEqualStrings(expected, p.yank.?); + try std.testing.expectEqualStrings(expected, p.registers.text(p.gpa, '"').?); try noChildInput(p); } } @@ -940,7 +940,7 @@ const TtySelectionTests = struct { const sx = source.x + config.GUTTER; const sy = if (p.settings.tag_bottom) source.y else source.y + pardes.BOX_H; JumpSelectionTests.drag(p, sx + 1, sy, sx + 3, sy + 1); - try std.testing.expectEqualStrings("lph\nrav", p.yank orelse return error.MissingAutomaticTtyYank); + try std.testing.expectEqualStrings("lph\nrav", p.registers.text(p.gpa, '"') orelse return error.MissingAutomaticTtyYank); try noChildInput(p); const target = p.rects[1]; @@ -1001,7 +1001,7 @@ const TtySelectionTests = struct { try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); - p.yank = try p.gpa.dupe(u8, "one\ntwo"); // what a `y` anywhere left behind + p.registers.put(p.gpa, '"', "one\ntwo", 0, 1, true); // what a `y` anywhere left behind var buf: [256]u8 = undefined; _ = childInput(p, &buf); @@ -1033,7 +1033,7 @@ const TtySelectionTests = struct { ); } // ...and neither chord put the clipboard in the register on its way. - try std.testing.expectEqualStrings("one\ntwo", p.yank orelse ""); + try std.testing.expectEqualStrings("one\ntwo", p.registers.text(p.gpa, '"') orelse ""); } } }; @@ -4242,7 +4242,7 @@ test "an empty counted paste leaves no count for the next motion" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("abcdefgh\n"); - if (empty_register) p.yank = try p.gpa.dupe(u8, ""); + if (empty_register) p.registers.put(p.gpa, '"', "", 0, 1, true); for ("3p") |cp| p.update(.{ .key = .{ .cp = cp } }); try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); p.update(.{ .key = .{ .cp = 'l' } }); -- cgit v1.3 From c811c34ed3bcd23954414125b45c7cac67307d5d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:04:12 -0300 Subject: Every range lives through insert mode, carried through each edit Insert mode dropped the selection on the first key and restored only the primary's appended-over span on Esc. Now each insert-mode edit is made at the bare cursor as before, and the range is then carried through it with helix's Range::map rules: typing slides an i range and stretches an a range, Enter (which now also drops the blanks before the cursor, as helix does) slides or stretches by what the cursor moved, and an arrow collapses. The replay gives every other range the same. Esc after a pulls each range's end back by one (helix restore_cursor), which replaces Text.append_at. The wiX-edit-drops-sel and msel-append waivers are gone. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 36 ++++++++----- docs/selections.md | 22 +++++--- src/Output.zig | 2 +- src/Terminal.zig | 8 +-- src/Text.zig | 4 +- src/edit.zig | 127 ++++++++++++++++++++++++++++++++++++--------- src/look.zig | 2 +- src/mouse.zig | 4 +- src/normal.zig | 6 +-- src/tagline.zig | 4 +- test/hxcases/cases.jsonl | 15 ++++++ test/hxcases/goldens.jsonl | 15 ++++++ test/hxcases/waivers.jsonl | 2 - test/mode.zig | 6 +-- test/panes.zig | 4 +- transactions.txt | 15 ++---- 16 files changed, 194 insertions(+), 78 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 90efc463..35f62765 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -7,10 +7,17 @@ checkout (`~/05-genizah/helix`); that checkout now sits on the local `pardes-harness` branch, whose three commits add only the harness, so `book/src/keymap.md` is byte-identical at its tip (694e7dfd). As of phase 5 every helix-equivalent row in A and B is differentially verified against real -helix (see "Differential testing" at the bottom). Five of the six waivers are -named in the row they belong to; the sixth, `wiX-edit-drops-sel`, belongs to no -single key — it is the anchor-only divergence every insert-mode edit shares — -and is described in the Files list at the bottom instead. +helix (see "Differential testing" at the bottom). Every waiver is named in the +row it belongs to. + +**The reference helix is fixed at one commit:** the `hx-harness` built from +`694e7dfdd` on the genizah checkout's `pardes-harness` branch, which is upstream +`278b24389` (2026-06-29, `25.07-905`) plus the three harness commits. "helix" +in this document means that build, not the 25.07.1 release, which differs on +counted `Alt-(`/`Alt-)` and on `&`. Upstream master was 82 commits further on +2026-09-28 (`079a789e`); of those only `416a0e09` (continuing a comment in an +injected `comment` layer) touches the editing code, and it needs tree-sitter, +which the harness runs without. Code map, by SYMBOL — line numbers rot, names do not. Body-normal key RECOGNITION is `modal.Normal` in `src/modal.zig`: a state machine over `Role` (one @@ -227,7 +234,7 @@ grew `sels` + `primary`, emitted only when there is more than one range. | `y` with several ranges | one value per range, pasted back value i at range i by `p`/`P`/`R` and insert `Ctrl-r`; the acme cut/paste chords and a paste into a terminal take the values joined by newlines | `Registers.zig` | helix-verified | | `"` | the next command's register: any character names one of its own. Computed ones: `_` swallows writes and reads nothing (`"_d`), `#` is each range's number from 1, `.` each range's text, `%` the file's name, `/` the last `s`/`S` pattern; `+`/`*` the system clipboard. A count typed before `"` stays the command's | helix `select_register` | helix-verified | | insert `Ctrl-r ` | type this range's value of the register (`Ctrl-r #` numbers the cursors). Esc after `Ctrl-r` only cancels it. `Ctrl-r +` reads what pardes last put on the clipboard, not the desktop's | helix `insert_register` | helix-verified | -| `a` … `Esc` with several ranges | the primary's appended-over span is restored; the others collapse to bare cursors | `Pane.append_at` is a single field. Waived (`msel-append`) | waived | +| insert mode with a selection | every range is carried through each edit as helix maps it (`Range::map`): typing at the head of an `i` range slides it, typing at the end of an `a` range stretches it, Enter slides or stretches it by what the cursor moved, and an arrow key collapses it. Esc after `a` pulls each range's end back one character (helix `restore_cursor`) | `edit.insertKey`, `Text.restore_cursor` | helix-verified | | `&` | align selections into columns: the k-th range of each line is column k, and spaces go in before each range until its head reaches the column's widest head, in display cells (`File.rawDisplayCol`) | helix `align_selections` as of the harness's helix (25.07.1 grouped columns differently). A range over several lines refuses. A TAB counts as `tab_width` cells, not up to the next stop | helix-verified | | `Alt-)` / `Alt-(` / `Alt-)` | rotate the CONTENTS of the selections forward / back by one range (n ranges), in one edit; each range comes back over the text it now holds and the primary moves with its text | helix `rotate_selection_contents_*` as of the harness's helix: 25.07.1 read the count as a GROUP size instead (rotate by one within each run of n ranges) and left the primary where it was, which is what helix-golf's `invert_dictionary_2` relies on | helix-verified | @@ -389,11 +396,11 @@ Files (all in `test/hxcases/`): (runs the `hx-harness` binary from the helix checkout; override with `$HX_HARNESS`). Only needed when cases change — the diff itself runs offline. -- `waivers.jsonl` — named exemptions, each with a reason. Three live ones: - `wiX-edit-drops-sel` and `msel-append` (helix maps selections through - insert-mode edits, pardes does not) and `alt-c-window-op` (the pardes - window op deliberately shadows helix change-noyank). `msel-yank-paste` - went with registers of one value per range; `sel-regex-caret` and +- `waivers.jsonl` — named exemptions, each with a reason. One live one: + `alt-c-window-op` (the pardes window op deliberately shadows helix + change-noyank). `wiX-edit-drops-sel` and `msel-append` went when insert + mode began carrying every range through its edits, `msel-yank-paste` with + registers of one value per range, `sel-regex-caret` and `sel-regex-dot-newline` when `s`/`S` began searching line by line. - `parity.jsonl` — 80 further cases, used only by the parity gate below. - `parity-waivers.jsonl` — 14 named exemptions for the parity gate, in three @@ -412,10 +419,11 @@ Files (all in `test/hxcases/`): tested when an earlier one misses. The goldens are `hx-harness test/hxcases/golf.jsonl`; `zig build hxgolf` runs them. All ten examples reproduce their published result in hx 25.07.1 under the site's own conditions (a file of the example's language, auto-pairs - on). Under the harness pins two do not: `csv_to_sql` needs auto-pairs to - close its `VALUES (`, and `invert_dictionary_2` needs 25.07's - `Alt-(` (rotate within groups of count) where the harness's newer - helix rotates by count. + on). Under the harness two do not, and their goldens are the harness's + anyway, which pardes follows: `csv_to_sql` needs auto-pairs (off in the + harness and absent in pardes) to close its `VALUES (`, and + `invert_dictionary_2` needs 25.07.1's `Alt-(` (rotate within groups + of count) where the reference helix rotates by count. - `smoke.jsonl` — 20 cases referenced by nothing in the tree: no build step, no script. Either wire it up or delete it. diff --git a/docs/selections.md b/docs/selections.md index 0f000e2c..c08ccb14 100644 --- a/docs/selections.md +++ b/docs/selections.md @@ -3,6 +3,8 @@ How normal mode holds and changes its selections, and where that differs from helix's `Selection` (a list of ranges over gap offsets, with a primary index). Key-by-key behaviour is in docs/helix-keys.md; this is the model underneath. +"helix" here is the reference build docs/helix-keys.md names: `hx-harness` +at `694e7dfdd`, upstream `278b24389`. ## What a selection is @@ -25,8 +27,9 @@ plus up to 63 others. `s`, `n`/`N`, ...) rather than left behind by a motion. Only pardes reads it: the look (Enter) and execute (Tab) chords act on explicit selections and on the word under the cursor otherwise. -- `select` is `v` extend mode. `append_at` remembers where an `a` began, so - Esc can give back the range it appended over. +- `select` is `v` extend mode. `restore_cursor` says the insert session + began with `a`, so Esc gives each range back the character it was + stretched by. `Text.setRanges` is the one writer of a whole selection: it sorts by start, merges ranges that overlap or share a start (helix `normalize`), follows the @@ -67,6 +70,17 @@ A parsed action has a scope (`modal.Normal.Action.scope`). look) runs once from the primary and drops back to one cursor (`normal.multiOnce`). +## Insert mode + +Each range lives on through insert mode. Every insert-mode edit happens at +the cursor, so `edit.insertKey` runs it on the bare cursor and then carries +the range through what it did to the text, with helix's `Range::map` rules: +at an insertion, a backward range's head and an empty range move past it +and a forward range's head stays before it, so typing slides an `i` range +and stretches an `a` range. Enter slides or stretches the range by what the +cursor moved; an arrow key collapses it. The other ranges get the same by +the replay. + ## Undo, registers, repeat - One keystroke is one undo step however many ranges it edited: only the @@ -86,10 +100,6 @@ A parsed action has a scope (`modal.Normal.Action.scope`). ## Where it differs from helix -- Insert mode: helix maps every range through each keystroke's edit, so a - range an `i`/`a` started from stretches over what is typed and keeps its - anchor. Here only the cursor cells move, and after Esc only the primary's - `append_at` span comes back (waivers `wiX-edit-drops-sel`, `msel-append`). - Direction of a one-character range: both of its cells are the same cell, so it has none. helix can flip one (`Alt-;`) and the commands that read the head (`&`, the next extend) see the difference. diff --git a/src/Output.zig b/src/Output.zig index 6e1765a7..201b5491 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -749,7 +749,7 @@ pub fn resetBody(p: *Pardes, pane: *Pane) void { pane.body.select = false; pane.sel = @splat(.{}); pane.body.sticky_col = -1; - pane.body.append_at = null; + pane.body.restore_cursor = false; pane.body.normal.clear(); pane.look_at = null; if (p.look_hover_wait) |wait| if (wait.serial == pane.serial) { diff --git a/src/Terminal.zig b/src/Terminal.zig index e204b44c..e3378007 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -717,7 +717,7 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { if (comptime !enabled) return; if (pane.terminal == null) return; const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or - pane.body.msel.active or pane.body.nsel > 0 or pane.body.append_at != null or pane.look_at != null or + pane.body.msel.active or pane.body.nsel > 0 or pane.look_at != null or pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; // Sticky bottom, as every other terminal does it: output drags the // viewport down only when the viewport was already on the last row, so @@ -843,10 +843,6 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { extra[nextra + 1] = &selection.arow; nextra += 2; } - if (pane.body.append_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } if (pane.look_at) |*at| { extra[nextra] = &at.row; nextra += 1; @@ -1124,7 +1120,7 @@ pub fn enterTty(p: *Pardes, id: usize) void { // keeps its modal endpoint for the next return to editor mode. pane.body.cur_pinned = selected; pane.body.select = false; - pane.body.append_at = null; + pane.body.restore_cursor = false; pane.body.sticky_col = -1; pane.body.normal.clear(); } diff --git a/src/Text.zig b/src/Text.zig index 7ad243a1..764b8a6a 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -65,7 +65,9 @@ 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, -append_at: ?struct { row: i32, col: i32 } = null, +/// 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, /// insert `Ctrl-r` was pressed: the next key names the register to insert reg_wait: bool = false, normal: modal.Normal.State = .{}, diff --git a/src/edit.zig b/src/edit.zig index 14d8b7ed..8f6f09c6 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -344,28 +344,20 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { t.reg_wait = false; t.msel.active = false; t.normal.clear(); - if (t.append_at) |aa| { - t.append_at = null; - const text = flatSurface(p, t) catch return; - const gap = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); - const a_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, aa.row)), .col = @intCast(@max(0, aa.col)) }); - const back = @max(a_off, modal.prevGrapheme(text, gap)); - const bc = modal.positionAt(text, back); - t.cur_row = @intCast(bc.row); - t.cur_col = @intCast(bc.col); - t.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; - t.cur_pinned = true; - t.show(); - for (t.sels[0..t.nsel]) |*s| { - const sgap = modal.offsetAt(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) }); - const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap); - const bp = modal.positionAt(text, b2); - s.row = @intCast(bp.row); - s.col = @intCast(bp.col); - s.arow = s.row; - s.acol = s.col; - } + if (!t.restore_cursor) return; + t.restore_cursor = false; + // helix enter_normal_mode: every range, from its start to the char + // before its end when it points forward, else to its end + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + const text = flatSurface(p, t) catch return; + var rs: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, 0, &rs); + for (rs[0..got.n]) |*r| { + const from = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + r.* = .{ .anchor = from, .head = if (r.head > r.anchor) @max(from, modal.prevGrapheme(text, to)) else to }; } + t.setRanges(text, rs[0..got.n], &.{}, got.pri, expl); } pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { @@ -518,7 +510,7 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { // `u` undoes the whole session and restores what was selected pushUndo(p, t); t.select = false; - t.append_at = null; + t.restore_cursor = false; t.sticky_col = -1; const text = flatSurface(p, t) catch { t.mode = .insert; @@ -544,12 +536,14 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { const lo_col = if (b) |bb| bb.lo_col else t.cur_col; const hi_row = if (b) |bb| bb.hi_row else t.cur_row; const hi_col = if (b) |bb| bb.hi_col else t.cur_col; - t.append_at = .{ .row = lo_row, .col = lo_col }; + t.restore_cursor = true; const gap = modal.nextGrapheme(text, modal.offsetAt(text, .{ .row = @intCast(@max(0, hi_row)), .col = @intCast(@max(0, hi_col)) })); const gc = modal.positionAt(text, gap); t.cur_row = @intCast(gc.row); t.cur_col = @intCast(gc.col); - t.vsel = .{ .active = b != null, .row = lo_row, .col = lo_col, .explicit = false }; + // helix append_mode: the range reaches one past its end, which + // is where typing goes; a bare cursor becomes a range too + t.vsel = .{ .active = true, .row = lo_row, .col = lo_col, .explicit = false }; t.cur_pinned = true; }, .line_start => { @@ -634,6 +628,72 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.reg_wait = true; return; } + // helix maps every range through each insert-mode edit (Range::map): + // the edits below work on the bare cursor, and the range the cursor + // heads is carried through what they did to the text afterwards + if (!t.vsel.active) return insertEdit(p, t, key); + const old = flatSurface(p, t) catch return insertEdit(p, t, key); + const r = t.primaryRange(old, 0); + const c = modal.selectionCursor(old, r); + const old_len = old.len; + const explicit = t.vsel.explicit; + t.vsel.active = false; + insertEdit(p, t, key); + if (t.mode != .insert) return; + const new = flatSurface(p, t) catch return; + const c2 = modal.offsetAt(new, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); + // every insert-mode edit happens at the cursor: an insertion there, or + // a deletion that ends there (backward) or starts there (forward) + if (key.cp == Key.enter) { + // helix insert_newline: an appending range stretches by what the + // cursor moved, any other slides by it + const d = @as(isize, @intCast(c2)) - @as(isize, @intCast(c)); + const head: usize = @intCast(@as(isize, @intCast(r.head)) + d); + const anchor: usize = if (c > r.anchor) r.anchor else @intCast(@as(isize, @intCast(r.anchor)) + d); + return setInsertRange(t, new, .{ .anchor = anchor, .head = head }, explicit); + } + var at: usize = c; + var del: usize = 0; + var ins: usize = 0; + if (new.len > old_len and c2 == c + (new.len - old_len)) { + ins = new.len - old_len; + } else if (new.len < old_len and c2 + (old_len - new.len) == c) { + at = c2; + del = old_len - new.len; + } else if (new.len < old_len and c2 == c) { + del = old_len - new.len; + } else if (new.len != old_len or c2 != c) { + return; // a motion: the range collapses onto the cursor (helix) + } + // helix Assoc: the head sticks after an insertion at it when the range + // points backward or is empty, the anchor when it points forward + const fwd = r.anchor < r.head; + setInsertRange(t, new, .{ + .anchor = mapThroughEdit(r.anchor, at, del, ins, !fwd and r.anchor != r.head), + .head = mapThroughEdit(r.head, at, del, ins, fwd), + }, explicit); +} + +fn setInsertRange(t: *Text, new: []const u8, mapped: modal.Selection, explicit: bool) void { + const cells = Text.rangeCells(new, mapped); + const cc = modal.positionAt(new, cells.cur); + const ac = modal.positionAt(new, cells.anc); + t.cur_row = @intCast(cc.row); + t.cur_col = @intCast(cc.col); + t.vsel = .{ .active = cells.anc != cells.cur, .row = @intCast(ac.row), .col = @intCast(ac.col), .explicit = explicit }; +} + +/// A position through one edit at `at` that deleted `del` bytes and put +/// `ins` in (one of the two is 0). A position exactly at an insertion stays +/// before it when `before` is set, else moves past it. +fn mapThroughEdit(pos: usize, at: usize, del: usize, ins: usize, before: bool) usize { + if (pos < at) return pos; + if (del > 0) return if (pos < at + del) at else pos - del; + if (pos == at and before) return pos; + return pos + ins; +} + +fn insertEdit(p: *Pardes, t: *Text, key: Key) void { t.vsel.active = false; if (!t.cur_pinned) pinPaneCursor(p, t); _ = clampFileCursor(t); @@ -748,12 +808,29 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { switch (key.cp) { Key.enter => { const line = modal.lineSlice(text, c.row); + const before = line[0..@min(c.col, line.len)]; + // helix insert_newline: after nothing but blanks, the line + // itself moves down, blanks and all; else the blanks before the + // cursor go and the new line takes the indent + if (std.mem.indexOfNone(u8, before, " \t") == null) { + const new = modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n") catch return; + setEditText(p, t, new); + t.cur_row += 1; + t.cur_pinned = true; + t.show(); + return; + } const indent = modal.newlineIndentWidth(line, c.col); const arena = p.scratch.allocator(); const block = arena.alloc(u8, 1 + indent) catch return; block[0] = '\n'; @memset(block[1..], ' '); - const new = modal.insertAt(p.gpa, text, c, block) catch return; + // a tag keeps its blanks: they part its words, and the last + // may be its read-only prefix's + const kept = if (t.what == .body) std.mem.trimEnd(u8, before, " \t").len else c.col; + const cut = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c) catch return; + defer p.gpa.free(cut); + const new = modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block) catch return; setEditText(p, t, new); t.cur_row += 1; t.cur_col = @intCast(indent); diff --git a/src/look.zig b/src/look.zig index 5e2d6068..30fb0dab 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1016,7 +1016,7 @@ pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void { pane.body.nsel = 0; pane.body.select = false; pane.body.normal.clear(); - pane.body.append_at = null; + pane.body.restore_cursor = false; pane.body.sticky_col = -1; for (0..pane.sel.len) |slot| pane.clearPointerSelection(slot); pane.sel = @splat(.{}); diff --git a/src/mouse.zig b/src/mouse.zig index 91ec41a6..d1c32b40 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -747,7 +747,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { pane.body.vsel.active = false; pane.body.nsel = 0; pane.body.select = false; - pane.body.append_at = null; + pane.body.restore_cursor = false; pane.body.sticky_col = -1; pane.body.normal.clear(); edit.setYank(p, text); @@ -859,7 +859,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.body.vsel.active = false; pane.body.nsel = 0; // a click says WHERE the one cursor is pane.body.select = false; - pane.body.append_at = null; + pane.body.restore_cursor = false; pane.body.sticky_col = -1; if (s.ctrl) p.lspRequest(s.id, .definition, ""); } diff --git a/src/normal.zig b/src/normal.zig index f5e868a4..53e416fd 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -149,7 +149,7 @@ const KeyState = struct { normal: modal.Normal.State, find_op: u8, find_ch: u21, - append_at: @FieldType(Text, "append_at"), + restore_cursor: bool, reg_wait: bool, fn of(t: *Text) KeyState { @@ -159,7 +159,7 @@ const KeyState = struct { .normal = t.normal, .find_op = t.find_op, .find_ch = t.find_ch, - .append_at = t.append_at, + .restore_cursor = t.restore_cursor, .reg_wait = t.reg_wait, }; } @@ -170,7 +170,7 @@ const KeyState = struct { t.normal = s.normal; t.find_op = s.find_op; t.find_ch = s.find_ch; - t.append_at = s.append_at; + t.restore_cursor = s.restore_cursor; t.reg_wait = s.reg_wait; } }; diff --git a/src/tagline.zig b/src/tagline.zig index 14bf5677..1c060a66 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -219,7 +219,7 @@ pub fn enterTag(p: *Pardes, pane: *Pane) void { t.msel.active = false; t.nsel = 0; t.select = false; - t.append_at = null; + t.restore_cursor = false; t.sticky_col = -1; t.mode = .normal; t.normal.clear(); @@ -325,7 +325,7 @@ pub fn enterHeader(p: *Pardes, column: ?usize) void { t.msel.active = false; t.nsel = 0; t.select = false; - t.append_at = null; + t.restore_cursor = false; t.mode = .normal; t.normal.clear(); } diff --git a/test/hxcases/cases.jsonl b/test/hxcases/cases.jsonl index 7ba44f09..ba75c611 100644 --- a/test/hxcases/cases.jsonl +++ b/test/hxcases/cases.jsonl @@ -344,6 +344,21 @@ {"name": "i-keeps-sel-start", "pane": "file", "text": "alpha beta\n", "keys": "wi"} {"name": "wa-sel-end", "pane": "file", "text": "alpha beta\n", "keys": "wa"} {"name": "wiX-edit-drops-sel", "pane": "file", "text": "alpha beta\n", "keys": "wiX"} +{"name": "reg-selection-insert", "pane": "file", "text": "ab\n", "keys": "vli."} +{"name": "ins-sel-backspace", "pane": "file", "text": "alpha beta\n", "keys": "wi"} +{"name": "ins-append-enter", "pane": "file", "text": "ab cd\n", "keys": "wax"} +{"name": "ins-append-backspace", "pane": "file", "text": "ab cd\n", "keys": "ea"} +{"name": "ins-sel-delete", "pane": "file", "text": "ab cd\n", "keys": "wi"} +{"name": "ins-sel-arrow-collapses", "pane": "file", "text": "ab cd\n", "keys": "wi"} +{"name": "msel-insert-keeps-ranges", "pane": "file", "text": "ab cd\nab cd\n", "keys": "wCiX"} +{"name": "msel-append-lines", "pane": "file", "text": "aa\nbb\n", "keys": "%a!"} +{"name": "ins-append-bare", "pane": "file", "text": "ab\n", "keys": "axy"} +{"name": "ins-change-then-type", "pane": "file", "text": "ab cd\n", "keys": "wcX"} +{"name": "ins-open-below-sel", "pane": "file", "text": "ab\ncd\n", "keys": "xoX"} +{"name": "ins-enter-trims-blanks", "pane": "file", "text": "ab cd\n", "keys": "5li"} +{"name": "ins-enter-in-indent", "pane": "file", "text": " ab\n", "keys": "2li"} +{"name": "ins-enter-after-open", "pane": "file", "text": " ab\n", "keys": "ox"} +{"name": "msel-ins-enter", "pane": "file", "text": "ab cd\nab cd\n", "keys": "wCa"} {"name": "a-esc-restore", "pane": "file", "text": "abc\n", "keys": "a"} {"name": "ax-restore", "pane": "file", "text": "abc\n", "keys": "ax"} {"name": "lax-restore", "pane": "file", "text": "abc\n", "keys": "lax"} diff --git a/test/hxcases/goldens.jsonl b/test/hxcases/goldens.jsonl index f6a6aada..188b7ce4 100644 --- a/test/hxcases/goldens.jsonl +++ b/test/hxcases/goldens.jsonl @@ -344,6 +344,21 @@ {"name":"i-keeps-sel-start","text":"alpha beta\n","mode":"insert","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":5}} {"name":"wa-sel-end","text":"alpha beta\n","mode":"insert","cursor":{"row":0,"col":6},"anchor":{"row":0,"col":0}} {"name":"wiX-edit-drops-sel","text":"Xalpha beta\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":6}} +{"name":"reg-selection-insert","text":"abab\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":3}} +{"name":"ins-sel-backspace","text":"alpha beta\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":5}} +{"name":"ins-append-enter","text":"ab\nxcd\n","mode":"normal","cursor":{"row":1,"col":0},"anchor":{"row":0,"col":0}} +{"name":"ins-append-backspace","text":" cd\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}} +{"name":"ins-sel-delete","text":"b cd\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":1}} +{"name":"ins-sel-arrow-collapses","text":"ab cd\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}} +{"name":"msel-insert-keeps-ranges","text":"Xab cd\nXab cd\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":3},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":3}}],"primary":1} +{"name":"msel-append-lines","text":"aa!\nbb!\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":0}}],"primary":0} +{"name":"ins-append-bare","text":"axyb\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} +{"name":"ins-change-then-type","text":"Xcd\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}} +{"name":"ins-open-below-sel","text":"ab\nX\ncd\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}} +{"name":"ins-enter-trims-blanks","text":"ab\ncd\n","mode":"normal","cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0}} +{"name":"ins-enter-in-indent","text":"\n ab\n","mode":"normal","cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2}} +{"name":"ins-enter-after-open","text":" ab\n\n x\n","mode":"normal","cursor":{"row":2,"col":5},"anchor":{"row":2,"col":5}} +{"name":"msel-ins-enter","text":"ab\ncd\nab\ncd\n","mode":"normal","cursor":{"row":2,"col":2},"anchor":{"row":2,"col":0},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":0}}],"primary":1} {"name":"a-esc-restore","text":"abc\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}} {"name":"ax-restore","text":"axbc\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}} {"name":"lax-restore","text":"abxc\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":1}} diff --git a/test/hxcases/waivers.jsonl b/test/hxcases/waivers.jsonl index 8ac3bd9c..2d74e346 100644 --- a/test/hxcases/waivers.jsonl +++ b/test/hxcases/waivers.jsonl @@ -1,3 +1 @@ -{"name":"wiX-edit-drops-sel","reason":"Insert edits clear the selection instead of tracking its anchor.","reference":{"name":"wiX-edit-drops-sel","text":"Xalpha beta\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":6}},"expected":{"name":"wiX-edit-drops-sel","text":"Xalpha beta\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}}} {"name":"alt-c-window-op","reason":"Alt-c moves a pane to a new column instead of Helix's change-noyank.","reference":{"name":"alt-c-window-op","text":"bc def\n","mode":"insert","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},"expected":{"name":"alt-c-window-op","text":"abc def\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}}} -{"name":"msel-append","reason":"Append-mode selection origins are tracked only for the primary selection.","reference":{"name":"msel-append","text":"aza\nbzb\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1},"expected":{"name":"msel-append","text":"aza\nbzb\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1}} diff --git a/test/mode.zig b/test/mode.zig index c7d7d548..cba93c30 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -79,14 +79,14 @@ test "Mode from actual tag Exec preserves parked file and output insert transact p.update(.{ .key = .{ .cp = pardes.Key.tab } }); try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); try std.testing.expect(pane.focus == .body); - try std.testing.expect(pane.body.append_at == null); + try std.testing.expect(!pane.body.restore_cursor); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("ab\n", pane.file.?.content); p.update(.{ .key = .{ .cp = 'a' } }); p.update(.{ .key = .{ .cp = 'z', .text = "z" } }); - try std.testing.expect(pane.body.append_at != null); + try std.testing.expect(pane.body.restore_cursor); try mode(p, 0, .normal); - try std.testing.expect(pane.body.append_at == null); + try std.testing.expect(!pane.body.restore_cursor); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("ab\n", pane.file.?.content); } diff --git a/test/panes.zig b/test/panes.zig index cbf9d097..4e98f449 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -4547,7 +4547,7 @@ const LookResetTests = struct { pane.body.nsel = 1; pane.body.select = true; pane.body.normal.count = 5; - pane.body.append_at = .{ .row = 0, .col = 3 }; + pane.body.restore_cursor = true; pane.body.sticky_col = 7; for (0..pane.sel.len) |slot| { pane.clearPointerSelection(slot); @@ -4567,7 +4567,7 @@ const LookResetTests = struct { try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); try std.testing.expect(!pane.body.select); try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); - try std.testing.expect(pane.body.append_at == null); + try std.testing.expect(!pane.body.restore_cursor); try std.testing.expectEqual(@as(i32, -1), pane.body.sticky_col); for (pane.sel) |selection| try std.testing.expectEqual(.none, selection.state); for (pane.pointer_selections) |selection| try std.testing.expect(selection == null); diff --git a/transactions.txt b/transactions.txt index 6c2e7646..8d2fda3f 100644 --- a/transactions.txt +++ b/transactions.txt @@ -1,13 +1,8 @@ -Selection anchors through insert-mode edits, and the transaction model -======================================================================= - -STATUS: still open. `wiX-edit-drops-sel` is line 1 of test/hxcases/waivers.jsonl, -so the gap below describes the code as it stands rather than something already -fixed. One correction to the sentence that follows: it is not quite "the one -place". Line 3 of the same file, `msel-append`, says in its own words "Same -family as wiX-edit-drops-sel: pardes does not map selections through insert-mode -edits" — so the gap has two waivers, and what is singular is the CAUSE below, -not the number of divergences it produces. +STATUS: closed for the waivers. Insert mode now carries every range through +each edit (edit.insertKey maps the range with helix's Range::map rules after +the edit is made), so `wiX-edit-drops-sel` and `msel-append` are gone. What +follows is the original analysis; the delta layer it proposes was not needed +for that and stays unbuilt. The one place the helix differential suite shows a real structural gap (waiver "wiX-edit-drops-sel" in test/hxcases/waivers.jsonl): helix keeps a -- cgit v1.3 From 7ce5d94b5d48b68c86d015060ebcabe63e299e1a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:24:59 -0300 Subject: A selection holds up to 1024 ranges on the desktop, 64 on the board The limit was 64 everywhere, which helix-golf's enumerate_and_align outgrows (%s |\d+ makes 121 ranges). It is now memory.limits.selections, per platform, and the counts that hold it are u16. The ranges stay inline in each Text, so a pane grows by about 80 KiB on the desktop (three texts and the regex prompt's snapshot); the Pane size budget in Terminal.zig moves from 128 to 160 KiB and says why. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 2 +- docs/selections.md | 8 +++++--- src/Pipe.zig | 6 +++--- src/Terminal.zig | 5 ++++- src/Text.zig | 5 +++-- src/exec.zig | 4 ++-- src/memory.zig | 4 ++++ src/normal.zig | 2 +- src/panes.zig | 4 ++-- src/pardes.zig | 4 ++-- test/hxcases/cases.jsonl | 2 ++ test/hxcases/goldens.jsonl | 2 ++ test/panes.zig | 10 +++++----- 13 files changed, 36 insertions(+), 22 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 3d02893b..1c9e0763 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -276,7 +276,7 @@ keeps the matches it found so far. | an all-lowercase pattern | matches case-blind | helix's smart-case. mvzr has no such flag, so the surface is lowercased instead (ASCII folding is byte-for-byte, so the offsets are identical) | helix-verified | | `^` and `$` | hold at every line's start and end | helix compiles with `multi_line(true)`; pardes gets the same by searching each line as its own haystack (`src/regexp.zig`) | helix-verified | | `.` | never matches a newline | as the Rust regex crate: a pattern without `\n` searches line by line, and one that names `\n` has its `.`s made `[^\n]` (`src/regexp.zig`) | helix-verified | -| more than 64 matches | the ones past `MAX_SELS` are dropped | the ceiling the whole selection model has, not this key's | +| many matches | up to `memory.limits.selections` ranges: 1024 on the desktop, 64 on the board; matches past it are dropped | helix has no limit. The ranges are held inline in every `Text` (about 20 KiB each on the desktop) | helix-verified up to the limit | | `K` / `Alt-K` | keep / remove ranges matching a regex | **skipped**: the same prompt, filtering instead of splitting — worth adding next | ### `Ctrl-c` — toggle comments diff --git a/docs/selections.md b/docs/selections.md index 202ec3d9..59c4415b 100644 --- a/docs/selections.md +++ b/docs/selections.md @@ -10,7 +10,8 @@ at `694e7dfdd`, upstream `278b24389`. Every `Text` (src/Text.zig) has its own: a pane's body, its tag, a prompt's answer, a column's or the workspace's tag. A selection is one primary range -plus up to 63 others. +plus others, up to `memory.limits.selections` in all (1024 on the +desktop, 64 on the board). - The PRIMARY is where the cursor always was: `cur_row`/`cur_col` is the head, `vsel.row`/`vsel.col` the anchor while `vsel.active`, and a bare @@ -33,7 +34,7 @@ plus up to 63 others. `Text.setRanges` is the one writer of a whole selection: it sorts by start, merges ranges that overlap or share a start (helix `normalize`), follows the -primary through the merges, and keeps the first 64. `setRange` writes one +primary through the merges, and keeps the first `max_selections`. `setRange` writes one range and drops the others. ## Making, splitting, merging, rotating, removing @@ -107,7 +108,8 @@ the replay. - Direction of a one-character range: both of its cells are the same cell, so it has none. helix can flip one (`Alt-;`) and the commands that read the head (`&`, the next extend) see the difference. -- Count: at most 64 ranges; matches past that are dropped silently. +- Count: at most `memory.limits.selections` ranges (1024 on the desktop, 64 + on the board); matches past that are dropped silently. - `n`/`N` walk the look ring (acme), not regex search hits, and there is no `*`; helix-golf's `*`, `""N` and `n` do not apply. - `s`/`S` match as sam does (docs/helix-keys.md, "Regex selection"): each diff --git a/src/Pipe.zig b/src/Pipe.zig index 37145edf..48e98b7b 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -55,10 +55,10 @@ pub const PendingPipe = struct { cwd: []u8, inputs: []selection_pipe.Input, ranges: [panes.Text.max_selections]modal.Selection, - primary: u8, + primary: u16, explicit: bool, how: modal.Normal.PipeBehavior, - nranges: u8, + nranges: u16, pub fn deinit(wait: *PendingPipe, gpa: std.mem.Allocator) void { gpa.free(wait.command); @@ -453,7 +453,7 @@ test "selection pipe replaces all ranges atomically and undo restores them" { p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); try std.testing.expectEqualSlices(u8, "AA bb \n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); - try std.testing.expectEqual(@as(u8, 1), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 6), pane.body.sels[0].col); try std.testing.expect(!denied.has_induced_failure); diff --git a/src/Terminal.zig b/src/Terminal.zig index 4f94533d..1ff561b1 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -545,7 +545,10 @@ test "replay ownership is terminal-only and construction rolls back on allocatio try std.testing.expectEqual(terminal and enabled, pane.terminal != null); } }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); + // Most of it is the three texts' selections, limits.selections ranges + // each held inline (about 20 KiB a text on the desktop), and the regex + // prompt's snapshot of them. + try std.testing.expect(@sizeOf(Pane) < 160 * 1024); try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); } diff --git a/src/Text.zig b/src/Text.zig index 764b8a6a..56ee199b 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -11,6 +11,7 @@ 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; @@ -36,7 +37,7 @@ pub const CharSel = struct { explicit: bool = false, }; -pub const max_selections = 64; +pub const max_selections = memory.limits.selections; pub const SelRange = struct { row: i32, @@ -60,7 +61,7 @@ cur_col: i32 = 0, msel: LineSel = .{}, vsel: CharSel = .{}, sels: [max_selections - 1]SelRange = undefined, -nsel: u8 = 0, +nsel: u16 = 0, select: bool = false, /// sticky goal column for j/k runs (helix old_visual_position): any /// non-vertical range write resets it to -1. diff --git a/src/exec.zig b/src/exec.zig index 1b82d2a8..455a325e 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -752,7 +752,7 @@ test "the acme chords act once per selection, not once on the primary" { .{ .anchor = 7, .head = 13 }, }; pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); - try std.testing.expectEqual(@as(u8, 1), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); const before = p.ncol; p.update(.{ .key = .{ .cp = Key.tab } }); // config.exec_key: Exec @@ -760,7 +760,7 @@ test "the acme chords act once per selection, not once on the primary" { // other cursor, so one keystroke over two cursors made one column. try std.testing.expectEqual(before + 2, p.ncol); // ...and the chord consumed the selection exactly as it does with one. - try std.testing.expectEqual(@as(u8, 0), p.panes[0].?.body.nsel); + try std.testing.expectEqual(@as(u16, 0), p.panes[0].?.body.nsel); } test "a switch clicked with a selection held flips unless the selection says on or off" { diff --git a/src/memory.zig b/src/memory.zig index 7b6ee2c0..abfd40f6 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -17,6 +17,9 @@ pub const limits = struct { pub const wrap_rows = if (board) 128 else 256; pub const undo_max = if (board) 16 else 256; pub const message_log = if (board) 16 else 128; + /// ranges one selection holds; helix has no limit, and a `%s` over a + /// file's words wants hundreds + pub const selections = if (board) 64 else 1024; /// /log's ring, which records whether or not anyone reads it. pub const log_bytes: usize = if (board) 4 * KiB else 64 * KiB; pub const max_tag_tail: usize = if (board) 512 else 4096; @@ -187,6 +190,7 @@ test "memory limits preserve desktop capacities" { try std.testing.expectEqual(256, limits.wrap_rows); try std.testing.expectEqual(256, limits.undo_max); try std.testing.expectEqual(128, limits.message_log); + try std.testing.expectEqual(1024, limits.selections); try std.testing.expectEqual(@as(usize, 4096), limits.max_tag_tail); try std.testing.expectEqual(@as(usize, 4095), limits.host_path_cap); try std.testing.expectEqual(config.embed_sources, limits.embedded_sources); diff --git a/src/normal.zig b/src/normal.zig index 542c9fb3..98ba80d6 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -771,7 +771,7 @@ test "flat text movement and selection replay need no scratch rows" { pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; handleNormal(p, &pane.body, .{ .cp = 'l' }); handleNormal(p, &pane.body, .{ .cp = 'j' }); - try std.testing.expectEqual(@as(u8, 1), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expectEqual(@as(i32, 1025), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 3073), pane.body.sels[0].row); diff --git a/src/panes.zig b/src/panes.zig index 9234912f..67954abd 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -155,8 +155,8 @@ pub const Pane = struct { search_row: ?usize = null, look_at: ?LookSpot = null, sel_snap: [Text.max_selections]modal.Selection = undefined, - nsel_snap: u8 = 0, - sel_snap_pri: u8 = 0, + nsel_snap: u16 = 0, + sel_snap_pri: u16 = 0, sel_snap_expl: bool = false, /// The tag: what the user keeps after the computed prefix (the path, the /// dirty marker, a PDF's page), its cursor, selections and undo. The diff --git a/src/pardes.zig b/src/pardes.zig index 87041f39..a7bcb195 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3123,7 +3123,7 @@ test "s in a header selects in the header's own text" { const text = try edit.flatSurface(p, &p.global_tag); const got = p.global_tag.ranges(text, 0, &ranges); try std.testing.expectEqual(@as(usize, 3), got.n); // Newcol, Joincol, NextColor - try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); } test "Enter in a header runs the word under its cursor, as the execute key does" { @@ -7547,7 +7547,7 @@ test "jump history clears selections and lands at the recorded cursor" { try std.testing.expectEqual(@as(usize, 2), p.njumps); try std.testing.expectEqual(@as(u32, 3), p.jumps[0].line); try std.testing.expect(!pane.body.vsel.active and !pane.body.msel.active and !pane.body.select); - try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); try std.testing.expectEqual(.none, pane.sel[0].state); try std.testing.expect(pane.pointer_selections[0] == null); try std.testing.expectEqual(@as(i32, if (index == 0) 2 else 0), pane.body.cur_row); diff --git a/test/hxcases/cases.jsonl b/test/hxcases/cases.jsonl index 8d6b0e6e..7aeb12e8 100644 --- a/test/hxcases/cases.jsonl +++ b/test/hxcases/cases.jsonl @@ -430,6 +430,8 @@ {"name": "msel-rotate-contents-lengths", "pane": "file", "text": "one to three\n", "keys": "%s\\w+)"} {"name": "msel-rotate-contents-backward", "pane": "file", "text": "ab cde\n", "keys": "%s\\w+"} {"name": "msel-rotate-contents-lines", "pane": "file", "text": "aa\nbbb\n", "keys": "%"} +{"name": "sel-many-ranges", "pane": "file", "text": "w w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\n", "keys": "%sw"} +{"name": "sel-many-ranges-edit", "pane": "file", "text": "w w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\n", "keys": "%swcxy"} {"name": "msel-align-basic", "pane": "file", "text": "a=1\nbbb=2\n", "keys": "%s=&"} {"name": "msel-align-columns", "pane": "file", "text": "a,b,c\nccc,d,e\n", "keys": "%s,&"} {"name": "msel-align-uneven", "pane": "file", "text": "a,b\nccc,d,eee,f\n", "keys": "%s,&"} diff --git a/test/hxcases/goldens.jsonl b/test/hxcases/goldens.jsonl index d62cb633..b8221c4c 100644 --- a/test/hxcases/goldens.jsonl +++ b/test/hxcases/goldens.jsonl @@ -430,6 +430,8 @@ {"name":"msel-rotate-contents-lengths","text":"to three one\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":7},"anchor":{"row":0,"col":3}},{"cursor":{"row":0,"col":11},"anchor":{"row":0,"col":9}}],"primary":0} {"name":"msel-rotate-contents-backward","text":"cde ab\n","mode":"normal","cursor":{"row":0,"col":4},"anchor":{"row":0,"col":5},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":2}},{"cursor":{"row":0,"col":4},"anchor":{"row":0,"col":5}}],"primary":1} {"name":"msel-rotate-contents-lines","text":"bbb\naa\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1} +{"name":"sel-many-ranges","text":"w w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}},{"cursor":{"row":0,"col":4},"anchor":{"row":0,"col":4}},{"cursor":{"row":0,"col":6},"anchor":{"row":0,"col":6}},{"cursor":{"row":0,"col":8},"anchor":{"row":0,"col":8}},{"cursor":{"row":0,"col":10},"anchor":{"row":0,"col":10}},{"cursor":{"row":0,"col":12},"anchor":{"row":0,"col":12}},{"cursor":{"row":0,"col":14},"anchor":{"row":0,"col":14}},{"cursor":{"row":0,"col":16},"anchor":{"row":0,"col":16}},{"cursor":{"row":0,"col":18},"anchor":{"row":0,"col":18}},{"cursor":{"row":0,"col":20},"anchor":{"row":0,"col":20}},{"cursor":{"row":0,"col":22},"anchor":{"row":0,"col":22}},{"cursor":{"row":0,"col":24},"anchor":{"row":0,"col":24}},{"cursor":{"row":0,"col":26},"anchor":{"row":0,"col":26}},{"cursor":{"row":0,"col":28},"anchor":{"row":0,"col":28}},{"cursor":{"row":0,"col":30},"anchor":{"row":0,"col":30}},{"cursor":{"row":0,"col":32},"anchor":{"row":0,"col":32}},{"cursor":{"row":0,"col":34},"anchor":{"row":0,"col":34}},{"cursor":{"row":0,"col":36},"anchor":{"row":0,"col":36}},{"cursor":{"row":0,"col":38},"anchor":{"row":0,"col":38}},{"cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0}},{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2}},{"cursor":{"row":1,"col":4},"anchor":{"row":1,"col":4}},{"cursor":{"row":1,"col":6},"anchor":{"row":1,"col":6}},{"cursor":{"row":1,"col":8},"anchor":{"row":1,"col":8}},{"cursor":{"row":1,"col":10},"anchor":{"row":1,"col":10}},{"cursor":{"row":1,"col":12},"anchor":{"row":1,"col":12}},{"cursor":{"row":1,"col":14},"anchor":{"row":1,"col":14}},{"cursor":{"row":1,"col":16},"anchor":{"row":1,"col":16}},{"cursor":{"row":1,"col":18},"anchor":{"row":1,"col":18}},{"cursor":{"row":1,"col":20},"anchor":{"row":1,"col":20}},{"cursor":{"row":1,"col":22},"anchor":{"row":1,"col":22}},{"cursor":{"row":1,"col":24},"anchor":{"row":1,"col":24}},{"cursor":{"row":1,"col":26},"anchor":{"row":1,"col":26}},{"cursor":{"row":1,"col":28},"anchor":{"row":1,"col":28}},{"cursor":{"row":1,"col":30},"anchor":{"row":1,"col":30}},{"cursor":{"row":1,"col":32},"anchor":{"row":1,"col":32}},{"cursor":{"row":1,"col":34},"anchor":{"row":1,"col":34}},{"cursor":{"row":1,"col":36},"anchor":{"row":1,"col":36}},{"cursor":{"row":1,"col":38},"anchor":{"row":1,"col":38}},{"cursor":{"row":2,"col":0},"anchor":{"row":2,"col":0}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":2}},{"cursor":{"row":2,"col":4},"anchor":{"row":2,"col":4}},{"cursor":{"row":2,"col":6},"anchor":{"row":2,"col":6}},{"cursor":{"row":2,"col":8},"anchor":{"row":2,"col":8}},{"cursor":{"row":2,"col":10},"anchor":{"row":2,"col":10}},{"cursor":{"row":2,"col":12},"anchor":{"row":2,"col":12}},{"cursor":{"row":2,"col":14},"anchor":{"row":2,"col":14}},{"cursor":{"row":2,"col":16},"anchor":{"row":2,"col":16}},{"cursor":{"row":2,"col":18},"anchor":{"row":2,"col":18}},{"cursor":{"row":2,"col":20},"anchor":{"row":2,"col":20}},{"cursor":{"row":2,"col":22},"anchor":{"row":2,"col":22}},{"cursor":{"row":2,"col":24},"anchor":{"row":2,"col":24}},{"cursor":{"row":2,"col":26},"anchor":{"row":2,"col":26}},{"cursor":{"row":2,"col":28},"anchor":{"row":2,"col":28}},{"cursor":{"row":2,"col":30},"anchor":{"row":2,"col":30}},{"cursor":{"row":2,"col":32},"anchor":{"row":2,"col":32}},{"cursor":{"row":2,"col":34},"anchor":{"row":2,"col":34}},{"cursor":{"row":2,"col":36},"anchor":{"row":2,"col":36}},{"cursor":{"row":2,"col":38},"anchor":{"row":2,"col":38}},{"cursor":{"row":3,"col":0},"anchor":{"row":3,"col":0}},{"cursor":{"row":3,"col":2},"anchor":{"row":3,"col":2}},{"cursor":{"row":3,"col":4},"anchor":{"row":3,"col":4}},{"cursor":{"row":3,"col":6},"anchor":{"row":3,"col":6}},{"cursor":{"row":3,"col":8},"anchor":{"row":3,"col":8}},{"cursor":{"row":3,"col":10},"anchor":{"row":3,"col":10}},{"cursor":{"row":3,"col":12},"anchor":{"row":3,"col":12}},{"cursor":{"row":3,"col":14},"anchor":{"row":3,"col":14}},{"cursor":{"row":3,"col":16},"anchor":{"row":3,"col":16}},{"cursor":{"row":3,"col":18},"anchor":{"row":3,"col":18}},{"cursor":{"row":3,"col":20},"anchor":{"row":3,"col":20}},{"cursor":{"row":3,"col":22},"anchor":{"row":3,"col":22}},{"cursor":{"row":3,"col":24},"anchor":{"row":3,"col":24}},{"cursor":{"row":3,"col":26},"anchor":{"row":3,"col":26}},{"cursor":{"row":3,"col":28},"anchor":{"row":3,"col":28}},{"cursor":{"row":3,"col":30},"anchor":{"row":3,"col":30}},{"cursor":{"row":3,"col":32},"anchor":{"row":3,"col":32}},{"cursor":{"row":3,"col":34},"anchor":{"row":3,"col":34}},{"cursor":{"row":3,"col":36},"anchor":{"row":3,"col":36}},{"cursor":{"row":3,"col":38},"anchor":{"row":3,"col":38}},{"cursor":{"row":4,"col":0},"anchor":{"row":4,"col":0}},{"cursor":{"row":4,"col":2},"anchor":{"row":4,"col":2}},{"cursor":{"row":4,"col":4},"anchor":{"row":4,"col":4}},{"cursor":{"row":4,"col":6},"anchor":{"row":4,"col":6}},{"cursor":{"row":4,"col":8},"anchor":{"row":4,"col":8}},{"cursor":{"row":4,"col":10},"anchor":{"row":4,"col":10}},{"cursor":{"row":4,"col":12},"anchor":{"row":4,"col":12}},{"cursor":{"row":4,"col":14},"anchor":{"row":4,"col":14}},{"cursor":{"row":4,"col":16},"anchor":{"row":4,"col":16}},{"cursor":{"row":4,"col":18},"anchor":{"row":4,"col":18}},{"cursor":{"row":4,"col":20},"anchor":{"row":4,"col":20}},{"cursor":{"row":4,"col":22},"anchor":{"row":4,"col":22}},{"cursor":{"row":4,"col":24},"anchor":{"row":4,"col":24}},{"cursor":{"row":4,"col":26},"anchor":{"row":4,"col":26}},{"cursor":{"row":4,"col":28},"anchor":{"row":4,"col":28}},{"cursor":{"row":4,"col":30},"anchor":{"row":4,"col":30}},{"cursor":{"row":4,"col":32},"anchor":{"row":4,"col":32}},{"cursor":{"row":4,"col":34},"anchor":{"row":4,"col":34}},{"cursor":{"row":4,"col":36},"anchor":{"row":4,"col":36}},{"cursor":{"row":4,"col":38},"anchor":{"row":4,"col":38}},{"cursor":{"row":5,"col":0},"anchor":{"row":5,"col":0}},{"cursor":{"row":5,"col":2},"anchor":{"row":5,"col":2}},{"cursor":{"row":5,"col":4},"anchor":{"row":5,"col":4}},{"cursor":{"row":5,"col":6},"anchor":{"row":5,"col":6}},{"cursor":{"row":5,"col":8},"anchor":{"row":5,"col":8}},{"cursor":{"row":5,"col":10},"anchor":{"row":5,"col":10}},{"cursor":{"row":5,"col":12},"anchor":{"row":5,"col":12}},{"cursor":{"row":5,"col":14},"anchor":{"row":5,"col":14}},{"cursor":{"row":5,"col":16},"anchor":{"row":5,"col":16}},{"cursor":{"row":5,"col":18},"anchor":{"row":5,"col":18}},{"cursor":{"row":5,"col":20},"anchor":{"row":5,"col":20}},{"cursor":{"row":5,"col":22},"anchor":{"row":5,"col":22}},{"cursor":{"row":5,"col":24},"anchor":{"row":5,"col":24}},{"cursor":{"row":5,"col":26},"anchor":{"row":5,"col":26}},{"cursor":{"row":5,"col":28},"anchor":{"row":5,"col":28}},{"cursor":{"row":5,"col":30},"anchor":{"row":5,"col":30}},{"cursor":{"row":5,"col":32},"anchor":{"row":5,"col":32}},{"cursor":{"row":5,"col":34},"anchor":{"row":5,"col":34}},{"cursor":{"row":5,"col":36},"anchor":{"row":5,"col":36}},{"cursor":{"row":5,"col":38},"anchor":{"row":5,"col":38}},{"cursor":{"row":6,"col":0},"anchor":{"row":6,"col":0}},{"cursor":{"row":6,"col":2},"anchor":{"row":6,"col":2}},{"cursor":{"row":6,"col":4},"anchor":{"row":6,"col":4}},{"cursor":{"row":6,"col":6},"anchor":{"row":6,"col":6}},{"cursor":{"row":6,"col":8},"anchor":{"row":6,"col":8}},{"cursor":{"row":6,"col":10},"anchor":{"row":6,"col":10}},{"cursor":{"row":6,"col":12},"anchor":{"row":6,"col":12}},{"cursor":{"row":6,"col":14},"anchor":{"row":6,"col":14}},{"cursor":{"row":6,"col":16},"anchor":{"row":6,"col":16}},{"cursor":{"row":6,"col":18},"anchor":{"row":6,"col":18}},{"cursor":{"row":6,"col":20},"anchor":{"row":6,"col":20}},{"cursor":{"row":6,"col":22},"anchor":{"row":6,"col":22}},{"cursor":{"row":6,"col":24},"anchor":{"row":6,"col":24}},{"cursor":{"row":6,"col":26},"anchor":{"row":6,"col":26}},{"cursor":{"row":6,"col":28},"anchor":{"row":6,"col":28}},{"cursor":{"row":6,"col":30},"anchor":{"row":6,"col":30}},{"cursor":{"row":6,"col":32},"anchor":{"row":6,"col":32}},{"cursor":{"row":6,"col":34},"anchor":{"row":6,"col":34}},{"cursor":{"row":6,"col":36},"anchor":{"row":6,"col":36}},{"cursor":{"row":6,"col":38},"anchor":{"row":6,"col":38}},{"cursor":{"row":7,"col":0},"anchor":{"row":7,"col":0}},{"cursor":{"row":7,"col":2},"anchor":{"row":7,"col":2}},{"cursor":{"row":7,"col":4},"anchor":{"row":7,"col":4}},{"cursor":{"row":7,"col":6},"anchor":{"row":7,"col":6}},{"cursor":{"row":7,"col":8},"anchor":{"row":7,"col":8}},{"cursor":{"row":7,"col":10},"anchor":{"row":7,"col":10}},{"cursor":{"row":7,"col":12},"anchor":{"row":7,"col":12}},{"cursor":{"row":7,"col":14},"anchor":{"row":7,"col":14}},{"cursor":{"row":7,"col":16},"anchor":{"row":7,"col":16}},{"cursor":{"row":7,"col":18},"anchor":{"row":7,"col":18}},{"cursor":{"row":7,"col":20},"anchor":{"row":7,"col":20}},{"cursor":{"row":7,"col":22},"anchor":{"row":7,"col":22}},{"cursor":{"row":7,"col":24},"anchor":{"row":7,"col":24}},{"cursor":{"row":7,"col":26},"anchor":{"row":7,"col":26}},{"cursor":{"row":7,"col":28},"anchor":{"row":7,"col":28}},{"cursor":{"row":7,"col":30},"anchor":{"row":7,"col":30}},{"cursor":{"row":7,"col":32},"anchor":{"row":7,"col":32}},{"cursor":{"row":7,"col":34},"anchor":{"row":7,"col":34}},{"cursor":{"row":7,"col":36},"anchor":{"row":7,"col":36}},{"cursor":{"row":7,"col":38},"anchor":{"row":7,"col":38}},{"cursor":{"row":8,"col":0},"anchor":{"row":8,"col":0}},{"cursor":{"row":8,"col":2},"anchor":{"row":8,"col":2}},{"cursor":{"row":8,"col":4},"anchor":{"row":8,"col":4}},{"cursor":{"row":8,"col":6},"anchor":{"row":8,"col":6}},{"cursor":{"row":8,"col":8},"anchor":{"row":8,"col":8}},{"cursor":{"row":8,"col":10},"anchor":{"row":8,"col":10}},{"cursor":{"row":8,"col":12},"anchor":{"row":8,"col":12}},{"cursor":{"row":8,"col":14},"anchor":{"row":8,"col":14}},{"cursor":{"row":8,"col":16},"anchor":{"row":8,"col":16}},{"cursor":{"row":8,"col":18},"anchor":{"row":8,"col":18}},{"cursor":{"row":8,"col":20},"anchor":{"row":8,"col":20}},{"cursor":{"row":8,"col":22},"anchor":{"row":8,"col":22}},{"cursor":{"row":8,"col":24},"anchor":{"row":8,"col":24}},{"cursor":{"row":8,"col":26},"anchor":{"row":8,"col":26}},{"cursor":{"row":8,"col":28},"anchor":{"row":8,"col":28}},{"cursor":{"row":8,"col":30},"anchor":{"row":8,"col":30}},{"cursor":{"row":8,"col":32},"anchor":{"row":8,"col":32}},{"cursor":{"row":8,"col":34},"anchor":{"row":8,"col":34}},{"cursor":{"row":8,"col":36},"anchor":{"row":8,"col":36}},{"cursor":{"row":8,"col":38},"anchor":{"row":8,"col":38}},{"cursor":{"row":9,"col":0},"anchor":{"row":9,"col":0}},{"cursor":{"row":9,"col":2},"anchor":{"row":9,"col":2}},{"cursor":{"row":9,"col":4},"anchor":{"row":9,"col":4}},{"cursor":{"row":9,"col":6},"anchor":{"row":9,"col":6}},{"cursor":{"row":9,"col":8},"anchor":{"row":9,"col":8}},{"cursor":{"row":9,"col":10},"anchor":{"row":9,"col":10}},{"cursor":{"row":9,"col":12},"anchor":{"row":9,"col":12}},{"cursor":{"row":9,"col":14},"anchor":{"row":9,"col":14}},{"cursor":{"row":9,"col":16},"anchor":{"row":9,"col":16}},{"cursor":{"row":9,"col":18},"anchor":{"row":9,"col":18}},{"cursor":{"row":9,"col":20},"anchor":{"row":9,"col":20}},{"cursor":{"row":9,"col":22},"anchor":{"row":9,"col":22}},{"cursor":{"row":9,"col":24},"anchor":{"row":9,"col":24}},{"cursor":{"row":9,"col":26},"anchor":{"row":9,"col":26}},{"cursor":{"row":9,"col":28},"anchor":{"row":9,"col":28}},{"cursor":{"row":9,"col":30},"anchor":{"row":9,"col":30}},{"cursor":{"row":9,"col":32},"anchor":{"row":9,"col":32}},{"cursor":{"row":9,"col":34},"anchor":{"row":9,"col":34}},{"cursor":{"row":9,"col":36},"anchor":{"row":9,"col":36}},{"cursor":{"row":9,"col":38},"anchor":{"row":9,"col":38}}],"primary":0} +{"name":"sel-many-ranges-edit","text":"xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}},{"cursor":{"row":0,"col":5},"anchor":{"row":0,"col":5}},{"cursor":{"row":0,"col":8},"anchor":{"row":0,"col":8}},{"cursor":{"row":0,"col":11},"anchor":{"row":0,"col":11}},{"cursor":{"row":0,"col":14},"anchor":{"row":0,"col":14}},{"cursor":{"row":0,"col":17},"anchor":{"row":0,"col":17}},{"cursor":{"row":0,"col":20},"anchor":{"row":0,"col":20}},{"cursor":{"row":0,"col":23},"anchor":{"row":0,"col":23}},{"cursor":{"row":0,"col":26},"anchor":{"row":0,"col":26}},{"cursor":{"row":0,"col":29},"anchor":{"row":0,"col":29}},{"cursor":{"row":0,"col":32},"anchor":{"row":0,"col":32}},{"cursor":{"row":0,"col":35},"anchor":{"row":0,"col":35}},{"cursor":{"row":0,"col":38},"anchor":{"row":0,"col":38}},{"cursor":{"row":0,"col":41},"anchor":{"row":0,"col":41}},{"cursor":{"row":0,"col":44},"anchor":{"row":0,"col":44}},{"cursor":{"row":0,"col":47},"anchor":{"row":0,"col":47}},{"cursor":{"row":0,"col":50},"anchor":{"row":0,"col":50}},{"cursor":{"row":0,"col":53},"anchor":{"row":0,"col":53}},{"cursor":{"row":0,"col":56},"anchor":{"row":0,"col":56}},{"cursor":{"row":0,"col":59},"anchor":{"row":0,"col":59}},{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}},{"cursor":{"row":1,"col":8},"anchor":{"row":1,"col":8}},{"cursor":{"row":1,"col":11},"anchor":{"row":1,"col":11}},{"cursor":{"row":1,"col":14},"anchor":{"row":1,"col":14}},{"cursor":{"row":1,"col":17},"anchor":{"row":1,"col":17}},{"cursor":{"row":1,"col":20},"anchor":{"row":1,"col":20}},{"cursor":{"row":1,"col":23},"anchor":{"row":1,"col":23}},{"cursor":{"row":1,"col":26},"anchor":{"row":1,"col":26}},{"cursor":{"row":1,"col":29},"anchor":{"row":1,"col":29}},{"cursor":{"row":1,"col":32},"anchor":{"row":1,"col":32}},{"cursor":{"row":1,"col":35},"anchor":{"row":1,"col":35}},{"cursor":{"row":1,"col":38},"anchor":{"row":1,"col":38}},{"cursor":{"row":1,"col":41},"anchor":{"row":1,"col":41}},{"cursor":{"row":1,"col":44},"anchor":{"row":1,"col":44}},{"cursor":{"row":1,"col":47},"anchor":{"row":1,"col":47}},{"cursor":{"row":1,"col":50},"anchor":{"row":1,"col":50}},{"cursor":{"row":1,"col":53},"anchor":{"row":1,"col":53}},{"cursor":{"row":1,"col":56},"anchor":{"row":1,"col":56}},{"cursor":{"row":1,"col":59},"anchor":{"row":1,"col":59}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":2}},{"cursor":{"row":2,"col":5},"anchor":{"row":2,"col":5}},{"cursor":{"row":2,"col":8},"anchor":{"row":2,"col":8}},{"cursor":{"row":2,"col":11},"anchor":{"row":2,"col":11}},{"cursor":{"row":2,"col":14},"anchor":{"row":2,"col":14}},{"cursor":{"row":2,"col":17},"anchor":{"row":2,"col":17}},{"cursor":{"row":2,"col":20},"anchor":{"row":2,"col":20}},{"cursor":{"row":2,"col":23},"anchor":{"row":2,"col":23}},{"cursor":{"row":2,"col":26},"anchor":{"row":2,"col":26}},{"cursor":{"row":2,"col":29},"anchor":{"row":2,"col":29}},{"cursor":{"row":2,"col":32},"anchor":{"row":2,"col":32}},{"cursor":{"row":2,"col":35},"anchor":{"row":2,"col":35}},{"cursor":{"row":2,"col":38},"anchor":{"row":2,"col":38}},{"cursor":{"row":2,"col":41},"anchor":{"row":2,"col":41}},{"cursor":{"row":2,"col":44},"anchor":{"row":2,"col":44}},{"cursor":{"row":2,"col":47},"anchor":{"row":2,"col":47}},{"cursor":{"row":2,"col":50},"anchor":{"row":2,"col":50}},{"cursor":{"row":2,"col":53},"anchor":{"row":2,"col":53}},{"cursor":{"row":2,"col":56},"anchor":{"row":2,"col":56}},{"cursor":{"row":2,"col":59},"anchor":{"row":2,"col":59}},{"cursor":{"row":3,"col":2},"anchor":{"row":3,"col":2}},{"cursor":{"row":3,"col":5},"anchor":{"row":3,"col":5}},{"cursor":{"row":3,"col":8},"anchor":{"row":3,"col":8}},{"cursor":{"row":3,"col":11},"anchor":{"row":3,"col":11}},{"cursor":{"row":3,"col":14},"anchor":{"row":3,"col":14}},{"cursor":{"row":3,"col":17},"anchor":{"row":3,"col":17}},{"cursor":{"row":3,"col":20},"anchor":{"row":3,"col":20}},{"cursor":{"row":3,"col":23},"anchor":{"row":3,"col":23}},{"cursor":{"row":3,"col":26},"anchor":{"row":3,"col":26}},{"cursor":{"row":3,"col":29},"anchor":{"row":3,"col":29}},{"cursor":{"row":3,"col":32},"anchor":{"row":3,"col":32}},{"cursor":{"row":3,"col":35},"anchor":{"row":3,"col":35}},{"cursor":{"row":3,"col":38},"anchor":{"row":3,"col":38}},{"cursor":{"row":3,"col":41},"anchor":{"row":3,"col":41}},{"cursor":{"row":3,"col":44},"anchor":{"row":3,"col":44}},{"cursor":{"row":3,"col":47},"anchor":{"row":3,"col":47}},{"cursor":{"row":3,"col":50},"anchor":{"row":3,"col":50}},{"cursor":{"row":3,"col":53},"anchor":{"row":3,"col":53}},{"cursor":{"row":3,"col":56},"anchor":{"row":3,"col":56}},{"cursor":{"row":3,"col":59},"anchor":{"row":3,"col":59}},{"cursor":{"row":4,"col":2},"anchor":{"row":4,"col":2}},{"cursor":{"row":4,"col":5},"anchor":{"row":4,"col":5}},{"cursor":{"row":4,"col":8},"anchor":{"row":4,"col":8}},{"cursor":{"row":4,"col":11},"anchor":{"row":4,"col":11}},{"cursor":{"row":4,"col":14},"anchor":{"row":4,"col":14}},{"cursor":{"row":4,"col":17},"anchor":{"row":4,"col":17}},{"cursor":{"row":4,"col":20},"anchor":{"row":4,"col":20}},{"cursor":{"row":4,"col":23},"anchor":{"row":4,"col":23}},{"cursor":{"row":4,"col":26},"anchor":{"row":4,"col":26}},{"cursor":{"row":4,"col":29},"anchor":{"row":4,"col":29}},{"cursor":{"row":4,"col":32},"anchor":{"row":4,"col":32}},{"cursor":{"row":4,"col":35},"anchor":{"row":4,"col":35}},{"cursor":{"row":4,"col":38},"anchor":{"row":4,"col":38}},{"cursor":{"row":4,"col":41},"anchor":{"row":4,"col":41}},{"cursor":{"row":4,"col":44},"anchor":{"row":4,"col":44}},{"cursor":{"row":4,"col":47},"anchor":{"row":4,"col":47}},{"cursor":{"row":4,"col":50},"anchor":{"row":4,"col":50}},{"cursor":{"row":4,"col":53},"anchor":{"row":4,"col":53}},{"cursor":{"row":4,"col":56},"anchor":{"row":4,"col":56}},{"cursor":{"row":4,"col":59},"anchor":{"row":4,"col":59}},{"cursor":{"row":5,"col":2},"anchor":{"row":5,"col":2}},{"cursor":{"row":5,"col":5},"anchor":{"row":5,"col":5}},{"cursor":{"row":5,"col":8},"anchor":{"row":5,"col":8}},{"cursor":{"row":5,"col":11},"anchor":{"row":5,"col":11}},{"cursor":{"row":5,"col":14},"anchor":{"row":5,"col":14}},{"cursor":{"row":5,"col":17},"anchor":{"row":5,"col":17}},{"cursor":{"row":5,"col":20},"anchor":{"row":5,"col":20}},{"cursor":{"row":5,"col":23},"anchor":{"row":5,"col":23}},{"cursor":{"row":5,"col":26},"anchor":{"row":5,"col":26}},{"cursor":{"row":5,"col":29},"anchor":{"row":5,"col":29}},{"cursor":{"row":5,"col":32},"anchor":{"row":5,"col":32}},{"cursor":{"row":5,"col":35},"anchor":{"row":5,"col":35}},{"cursor":{"row":5,"col":38},"anchor":{"row":5,"col":38}},{"cursor":{"row":5,"col":41},"anchor":{"row":5,"col":41}},{"cursor":{"row":5,"col":44},"anchor":{"row":5,"col":44}},{"cursor":{"row":5,"col":47},"anchor":{"row":5,"col":47}},{"cursor":{"row":5,"col":50},"anchor":{"row":5,"col":50}},{"cursor":{"row":5,"col":53},"anchor":{"row":5,"col":53}},{"cursor":{"row":5,"col":56},"anchor":{"row":5,"col":56}},{"cursor":{"row":5,"col":59},"anchor":{"row":5,"col":59}},{"cursor":{"row":6,"col":2},"anchor":{"row":6,"col":2}},{"cursor":{"row":6,"col":5},"anchor":{"row":6,"col":5}},{"cursor":{"row":6,"col":8},"anchor":{"row":6,"col":8}},{"cursor":{"row":6,"col":11},"anchor":{"row":6,"col":11}},{"cursor":{"row":6,"col":14},"anchor":{"row":6,"col":14}},{"cursor":{"row":6,"col":17},"anchor":{"row":6,"col":17}},{"cursor":{"row":6,"col":20},"anchor":{"row":6,"col":20}},{"cursor":{"row":6,"col":23},"anchor":{"row":6,"col":23}},{"cursor":{"row":6,"col":26},"anchor":{"row":6,"col":26}},{"cursor":{"row":6,"col":29},"anchor":{"row":6,"col":29}},{"cursor":{"row":6,"col":32},"anchor":{"row":6,"col":32}},{"cursor":{"row":6,"col":35},"anchor":{"row":6,"col":35}},{"cursor":{"row":6,"col":38},"anchor":{"row":6,"col":38}},{"cursor":{"row":6,"col":41},"anchor":{"row":6,"col":41}},{"cursor":{"row":6,"col":44},"anchor":{"row":6,"col":44}},{"cursor":{"row":6,"col":47},"anchor":{"row":6,"col":47}},{"cursor":{"row":6,"col":50},"anchor":{"row":6,"col":50}},{"cursor":{"row":6,"col":53},"anchor":{"row":6,"col":53}},{"cursor":{"row":6,"col":56},"anchor":{"row":6,"col":56}},{"cursor":{"row":6,"col":59},"anchor":{"row":6,"col":59}},{"cursor":{"row":7,"col":2},"anchor":{"row":7,"col":2}},{"cursor":{"row":7,"col":5},"anchor":{"row":7,"col":5}},{"cursor":{"row":7,"col":8},"anchor":{"row":7,"col":8}},{"cursor":{"row":7,"col":11},"anchor":{"row":7,"col":11}},{"cursor":{"row":7,"col":14},"anchor":{"row":7,"col":14}},{"cursor":{"row":7,"col":17},"anchor":{"row":7,"col":17}},{"cursor":{"row":7,"col":20},"anchor":{"row":7,"col":20}},{"cursor":{"row":7,"col":23},"anchor":{"row":7,"col":23}},{"cursor":{"row":7,"col":26},"anchor":{"row":7,"col":26}},{"cursor":{"row":7,"col":29},"anchor":{"row":7,"col":29}},{"cursor":{"row":7,"col":32},"anchor":{"row":7,"col":32}},{"cursor":{"row":7,"col":35},"anchor":{"row":7,"col":35}},{"cursor":{"row":7,"col":38},"anchor":{"row":7,"col":38}},{"cursor":{"row":7,"col":41},"anchor":{"row":7,"col":41}},{"cursor":{"row":7,"col":44},"anchor":{"row":7,"col":44}},{"cursor":{"row":7,"col":47},"anchor":{"row":7,"col":47}},{"cursor":{"row":7,"col":50},"anchor":{"row":7,"col":50}},{"cursor":{"row":7,"col":53},"anchor":{"row":7,"col":53}},{"cursor":{"row":7,"col":56},"anchor":{"row":7,"col":56}},{"cursor":{"row":7,"col":59},"anchor":{"row":7,"col":59}},{"cursor":{"row":8,"col":2},"anchor":{"row":8,"col":2}},{"cursor":{"row":8,"col":5},"anchor":{"row":8,"col":5}},{"cursor":{"row":8,"col":8},"anchor":{"row":8,"col":8}},{"cursor":{"row":8,"col":11},"anchor":{"row":8,"col":11}},{"cursor":{"row":8,"col":14},"anchor":{"row":8,"col":14}},{"cursor":{"row":8,"col":17},"anchor":{"row":8,"col":17}},{"cursor":{"row":8,"col":20},"anchor":{"row":8,"col":20}},{"cursor":{"row":8,"col":23},"anchor":{"row":8,"col":23}},{"cursor":{"row":8,"col":26},"anchor":{"row":8,"col":26}},{"cursor":{"row":8,"col":29},"anchor":{"row":8,"col":29}},{"cursor":{"row":8,"col":32},"anchor":{"row":8,"col":32}},{"cursor":{"row":8,"col":35},"anchor":{"row":8,"col":35}},{"cursor":{"row":8,"col":38},"anchor":{"row":8,"col":38}},{"cursor":{"row":8,"col":41},"anchor":{"row":8,"col":41}},{"cursor":{"row":8,"col":44},"anchor":{"row":8,"col":44}},{"cursor":{"row":8,"col":47},"anchor":{"row":8,"col":47}},{"cursor":{"row":8,"col":50},"anchor":{"row":8,"col":50}},{"cursor":{"row":8,"col":53},"anchor":{"row":8,"col":53}},{"cursor":{"row":8,"col":56},"anchor":{"row":8,"col":56}},{"cursor":{"row":8,"col":59},"anchor":{"row":8,"col":59}},{"cursor":{"row":9,"col":2},"anchor":{"row":9,"col":2}},{"cursor":{"row":9,"col":5},"anchor":{"row":9,"col":5}},{"cursor":{"row":9,"col":8},"anchor":{"row":9,"col":8}},{"cursor":{"row":9,"col":11},"anchor":{"row":9,"col":11}},{"cursor":{"row":9,"col":14},"anchor":{"row":9,"col":14}},{"cursor":{"row":9,"col":17},"anchor":{"row":9,"col":17}},{"cursor":{"row":9,"col":20},"anchor":{"row":9,"col":20}},{"cursor":{"row":9,"col":23},"anchor":{"row":9,"col":23}},{"cursor":{"row":9,"col":26},"anchor":{"row":9,"col":26}},{"cursor":{"row":9,"col":29},"anchor":{"row":9,"col":29}},{"cursor":{"row":9,"col":32},"anchor":{"row":9,"col":32}},{"cursor":{"row":9,"col":35},"anchor":{"row":9,"col":35}},{"cursor":{"row":9,"col":38},"anchor":{"row":9,"col":38}},{"cursor":{"row":9,"col":41},"anchor":{"row":9,"col":41}},{"cursor":{"row":9,"col":44},"anchor":{"row":9,"col":44}},{"cursor":{"row":9,"col":47},"anchor":{"row":9,"col":47}},{"cursor":{"row":9,"col":50},"anchor":{"row":9,"col":50}},{"cursor":{"row":9,"col":53},"anchor":{"row":9,"col":53}},{"cursor":{"row":9,"col":56},"anchor":{"row":9,"col":56}},{"cursor":{"row":9,"col":59},"anchor":{"row":9,"col":59}}],"primary":0} {"name":"msel-align-basic","text":"a =1\nbbb=2\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}}],"primary":0} {"name":"msel-align-columns","text":"a ,b,c\nccc,d,e\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":0,"col":5},"anchor":{"row":0,"col":5}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}}],"primary":0} {"name":"msel-align-uneven","text":"a ,b\nccc,d,eee,f\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}},{"cursor":{"row":1,"col":9},"anchor":{"row":1,"col":9}}],"primary":0} diff --git a/test/panes.zig b/test/panes.zig index f0e1ba3d..a56c07bf 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -305,7 +305,7 @@ const TagNavigationTests = struct { try std.testing.expectEqual(@as(usize, 2), got.n); for (ranges[0..got.n]) |range| try std.testing.expectEqualStrings("S", text[@min(range.anchor, range.head)..@max(range.anchor, range.head)]); // the body's selection is its own - try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); // `/` from the tag is the body's search, as acme's Look from a tag is key(p, ','); key(p, '/'); @@ -1984,8 +1984,8 @@ test "prompt cancellation restores the selection before regex previews" { p.update(.{ .key = .{ .cp = case.pattern[0], .text = case.pattern } }); try std.testing.expectEqual(case.secondary, pane.body.nsel); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); - try std.testing.expectEqual(@as(u8, 0), pane.nsel_snap); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 0), pane.nsel_snap); try std.testing.expectEqual(@as(i32, 10), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); try std.testing.expect(pane.body.vsel.active and pane.body.vsel.explicit); @@ -2761,7 +2761,7 @@ const OutputTests = struct { try fillResults(p, 0, "/", .{ .query = .hover }, "", try p.gpa.dupe(u8, "short\n"), null); try std.testing.expectEqualStrings("short\n", result.file.?.content); try std.testing.expect(!result.body.vsel.active and !result.body.msel.active and !result.body.select); - try std.testing.expectEqual(@as(u8, 0), result.body.nsel); + try std.testing.expectEqual(@as(u16, 0), result.body.nsel); try std.testing.expectEqual(@as(i32, 0), result.body.cur_row); try std.testing.expectEqual(@as(i32, 0), result.body.cur_col); try std.testing.expectEqual(@as(usize, 0), result.file.?.scroll); @@ -4581,7 +4581,7 @@ const LookResetTests = struct { fn cleared(pane: *const Pane) !void { try std.testing.expect(!pane.body.msel.active); - try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); try std.testing.expect(!pane.body.select); try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); try std.testing.expect(!pane.body.restore_cursor); -- cgit v1.3 From 79cdf76fd2dd0ba03622bfe742b525b770d51684 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:29:36 -0300 Subject: K and Alt-K keep or drop the ranges a regex matches in; Alt-: turns every range forward K and Alt-K share the s/S prompt, which now carries a mode rather than a split flag: a range stays when a match starts inside it (K) or when none does (Alt-K), the primary becomes the first, and keeping none leaves the selection as it was (helix keep_or_remove_matches). Alt-: is ensure_selections_forward. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 4 ++-- docs/selections.md | 2 ++ src/Text.zig | 9 +++++++ src/config.zig | 5 ++++ src/edit.zig | 5 ++-- src/look.zig | 2 +- src/modal.zig | 15 +++++++++--- src/normal.zig | 58 ++++++++++++++++++++++++++++++++-------------- src/pardes.zig | 4 ++-- test/hxcases/cases.jsonl | 8 +++++++ test/hxcases/goldens.jsonl | 8 +++++++ 11 files changed, 92 insertions(+), 28 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 1c9e0763..5c3972a5 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -212,6 +212,7 @@ found. Pure text math in `modal.zig`: `findChar`, `matchBracket`, | --- | --- | --- | --- | | `;` | collapse selection to cursor | drops vsel/msel, cursor stays | helix-verified (phase 5) | | `Alt-;` | flip anchor and head | vsel: swap cursor ↔ anchor; msel: cursor to the other end (r0/r1 swapped to keep the cursor-at-r1 invariant) | helix-verified (phase 5) | +| `Alt-:` | make every range point forward | helix `ensure_selections_forward` | helix-verified | | `%` | select whole buffer | vsel anchor 0,0, cursor on the buffer's last char | helix-verified (phase 5) | | `X` | snap selection to line bounds | vsel → msel over its row span; bare cursor → 1-line msel; msel: already line-wise, no-op | helix-verified (phase 5) | | `Alt-x` | shrink selection to line bounds | vsel only: partial first/last lines drop out; nothing left collapses the selection; msel: no-op | helix-verified (phase 5) | @@ -277,7 +278,7 @@ keeps the matches it found so far. | `^` and `$` | hold at every line's start and end | helix compiles with `multi_line(true)`; pardes gets the same by searching each line as its own haystack (`src/regexp.zig`) | helix-verified | | `.` | never matches a newline | as the Rust regex crate: a pattern without `\n` searches line by line, and one that names `\n` has its `.`s made `[^\n]` (`src/regexp.zig`) | helix-verified | | many matches | up to `memory.limits.selections` ranges: 1024 on the desktop, 64 on the board; matches past it are dropped | helix has no limit. The ranges are held inline in every `Text` (about 20 KiB each on the desktop) | helix-verified up to the limit | -| `K` / `Alt-K` | keep / remove ranges matching a regex | **skipped**: the same prompt, filtering instead of splitting — worth adding next | +| `K` / `Alt-K` Enter | keep only the ranges a match starts inside / only those none does; primary 0, and keeping none leaves the selection alone | helix `keep_selections` / `remove_selections`, on the same prompt as `s`/`S` (markers `Keep /`, `Remove /`). The range is searched as `s` searches it, line by line with its lines' context, where helix matches the range's text alone: a `^` right at a range that starts mid-line matches in helix and not here | helix-verified | ### `Ctrl-c` — toggle comments @@ -357,7 +358,6 @@ text. | insert `Ctrl-x` | completion menu | completion exists, but not as a popup: insert-mode Tab straight after a `.` opens a buffer of candidate DECLARATIONS (section A). helix's menu itself is skipped | | `Ctrl-s` (normal) | save jumplist position | jumplist itself is implemented (`Ctrl-o`/`Ctrl-i`, section A); only the explicit save point is skipped | | `Alt-u` / `Alt-U` | undo-history earlier/later | history timeline — linear snapshot u/U covers pardes | -| `K Alt-K`, `Alt-:` | regex keep/remove, ensure-forward | `K`/`Alt-K` are the same prompt `s`/`S` now have, filtering instead of splitting (`s S` moved to "Regex selection" in A, the rest of the family to "Multiple cursors") | | `:` | command mode | side-effects/file-ops — pardes builtins live in the tag, and `:` is bound to focusing it (section A) | | `gf` | goto file under selection | covered by pardes Enter-look | | `Ctrl-z` | suspend | pardes IS the terminal multiplexer | diff --git a/docs/selections.md b/docs/selections.md index 59c4415b..203cf1de 100644 --- a/docs/selections.md +++ b/docs/selections.md @@ -44,6 +44,8 @@ range and drops the others. per line), `o`/`O`, and `Alt-J` (the spaces a join put in). `s`/`S` re-run on every keystroke from the selection the prompt opened on (`Pane.sel_snap`); Esc is that snapshot restored. +- `K`/`Alt-K` keep or drop the ranges a regex matches in, on the `s` prompt; + `Alt-:` turns every range forward. - `Alt-minus` merges all into one, `Alt-_` the consecutive ones, `_` trims whitespace (dropping all-blank ranges). - `)`/`(` rotate which range is primary; `Alt-)`/`Alt-(` rotate the TEXT diff --git a/src/Text.zig b/src/Text.zig index 56ee199b..411c2ec8 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -328,6 +328,15 @@ pub fn multiSelAction(t: *Text, text: []const u8, kind: modal.Normal.Multi, cnt: } return setRanges(t, text, out[0..m], &.{}, pri, expl); } + if (kind == .ensure_forward) { + // helix ensure_selections_forward: every range points forward + for (rs[0..n]) |*r| { + const from = @min(r.anchor, r.head); + r.head = @max(r.anchor, r.head); + r.anchor = from; + } + return setRanges(t, text, rs[0..n], &.{}, got.pri, expl); + } if (kind == .split_newline) { // helix selection::split_on_newline — one range per line the // selection covers, the newlines themselves left out diff --git a/src/config.zig b/src/config.zig index bc053176..8c5c9771 100644 --- a/src/config.zig +++ b/src/config.zig @@ -414,6 +414,8 @@ pub const symbol_marker = " WsSymbols /"; pub const save_marker = " Save "; pub const select_marker = " Select /"; pub const split_marker = " Split /"; +pub const keep_marker = " Keep /"; +pub const remove_marker = " Remove /"; pub const pipe_marker = " |"; pub const search_buffer = "+Search"; @@ -532,6 +534,9 @@ pub const trim_sels: []const Chord = &.{.{ .cp = '_' }}; pub const select_regex: []const Chord = &.{.{ .cp = 's' }}; pub const split_regex: []const Chord = &.{.{ .cp = 'S' }}; +pub const keep_regex: []const Chord = &.{.{ .cp = 'K' }}; +pub const remove_regex: []const Chord = &.{.{ .cp = 'K', .alt = true }}; +pub const ensure_forward: []const Chord = &.{.{ .cp = ':', .alt = true }}; pub const delete: []const Chord = &.{.{ .cp = 'd' }}; pub const delete_noyank: []const Chord = &.{.{ .cp = 'd', .alt = true }}; diff --git a/src/edit.zig b/src/edit.zig index a373741c..5e0d20a4 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -148,7 +148,7 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { n += 1; }; if (n > 0) insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] }); - if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.split); + if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); return; } if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes); @@ -355,7 +355,8 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { for (rs[0..got.n]) |*r| { const from = @min(r.anchor, r.head); const to = @max(r.anchor, r.head); - r.* = .{ .anchor = from, .head = if (r.head > r.anchor) @max(from, modal.prevGrapheme(text, to)) else to }; + const head = if (r.head > r.anchor) @max(from, modal.prevGrapheme(text, to)) else to; + r.* = .{ .anchor = from, .head = head }; } t.setRanges(text, rs[0..got.n], &.{}, got.pri, expl); } diff --git a/src/look.zig b/src/look.zig index 30fb0dab..3da2e044 100644 --- a/src/look.zig +++ b/src/look.zig @@ -505,7 +505,7 @@ pub fn submitSearch(p: *Pardes, id: usize) void { if (normal.selRegexArmed(pane)) |a| { // helix keeps the pattern in `/` if (a.pat.len > 0) p.registers.put(p.gpa, '/', a.pat, 0, 1, true); - return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.split); + return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); } const armed = pane.promptText() orelse return; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; diff --git a/src/modal.zig b/src/modal.zig index 34c4dac7..f5f3081e 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -97,6 +97,9 @@ pub const Normal = struct { trim_sels, select_regex, split_regex, + keep_regex, + remove_regex, + ensure_forward, delete, delete_noyank, @@ -210,6 +213,8 @@ pub const Normal = struct { } }; + /// what the s/S/K/Alt-K prompt does with its pattern's matches + pub const RegexMode = enum { select, split, keep, remove }; pub const Scope = enum { once, per_selection }; pub const Direction = enum { backward, forward }; pub const Motion = enum { @@ -262,6 +267,7 @@ pub const Normal = struct { merge, merge_consecutive, trim, + ensure_forward, }; pub const Edit = enum { delete, @@ -314,7 +320,7 @@ pub const Normal = struct { insert: struct { kind: Insert, count: u32 }, select: struct { kind: Select, count: u32 }, multi: struct { kind: Multi, count: u32 }, - select_regex: bool, // false = select, true = split + select_regex: RegexMode, edit: struct { kind: Edit, count: u32 }, lsp: Lsp, adjust_number: i64, @@ -577,8 +583,11 @@ pub const Normal = struct { if (key.has(.merge_sels)) return resultAction(.{ .multi = .{ .kind = .merge, .count = count } }); if (key.has(.merge_consecutive_sels)) return resultAction(.{ .multi = .{ .kind = .merge_consecutive, .count = count } }); if (key.has(.trim_sels)) return resultAction(.{ .multi = .{ .kind = .trim, .count = count } }); - if (key.has(.select_regex)) return resultAction(.{ .select_regex = false }); - if (key.has(.split_regex)) return resultAction(.{ .select_regex = true }); + if (key.has(.select_regex)) return resultAction(.{ .select_regex = .select }); + if (key.has(.split_regex)) return resultAction(.{ .select_regex = .split }); + if (key.has(.keep_regex)) return resultAction(.{ .select_regex = .keep }); + if (key.has(.remove_regex)) return resultAction(.{ .select_regex = .remove }); + if (key.has(.ensure_forward)) return resultAction(.{ .multi = .{ .kind = .ensure_forward, .count = count } }); if (key.has(.delete)) return resultAction(.{ .edit = .{ .kind = .delete, .count = count } }); if (key.has(.delete_noyank)) return resultAction(.{ .edit = .{ .kind = .delete_noyank, .count = count } }); diff --git a/src/normal.zig b/src/normal.zig index 98ba80d6..d6c646ef 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -69,27 +69,38 @@ pub fn multiOnce(p: *Pardes) bool { return p.multi_first; } -fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, split: bool) void { +fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) void { const text = edit.flatSurface(p, t) catch return; const got = t.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); pane.sel_snap_expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; - p.startPrompt(pane, t, .{ .search = if (split) config.split_marker else config.select_marker }); + p.startPrompt(pane, t, .{ .search = regexMarker(mode) }); } -pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { +fn regexMarker(mode: modal.Normal.RegexMode) []const u8 { + return switch (mode) { + .select => config.select_marker, + .split => config.split_marker, + .keep => config.keep_marker, + .remove => config.remove_marker, + }; +} + +pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal.RegexMode } { if (pane.prompt != .search or pane.nsel_snap == 0) return null; const armed = pane.input.own orelse ""; - const split = std.mem.startsWith(u8, armed, config.split_marker); - if (!split and !std.mem.startsWith(u8, armed, config.select_marker)) return null; + const mode: modal.Normal.RegexMode = for (std.enums.values(modal.Normal.RegexMode)) |m| { + if (std.mem.startsWith(u8, armed, regexMarker(m))) break m; + } else return null; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null; - return .{ .pat = armed[slash + 1 ..], .split = split }; + return .{ .pat = armed[slash + 1 ..], .mode = mode }; } -/// Select (or split on) `pat` inside the selections `t` had when s/S was -/// pressed; the prompt's snapshot of them lives on `pane`. -pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: bool) void { +/// Select (or split on, keep or remove by) `pat` inside the selections `t` +/// had when s/S/K/Alt-K was pressed; the prompt's snapshot of them lives on +/// `pane`. +pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) void { const text = edit.flatSurface(p, t) catch return; const snap = pane.sel_snap[0..pane.nsel_snap]; var out: [Text.max_selections]modal.Selection = undefined; @@ -108,6 +119,17 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: const from = @min(r.anchor, r.head); const to = @min(@max(r.anchor, r.head), text.len); if (from >= to) continue; + if (mode == .keep or mode == .remove) { + // helix keep_or_remove_matches: the range stays when a match + // starts inside it (K), or when none does (Alt-K) + const hit_at = re.find(hay_all, from, to, to) catch null; + const found = if (hit_at) |h| h.start < to else false; + if (found == (mode == .keep) and m < Text.max_selections) { + out[m] = r; + m += 1; + } + continue; + } // Searched as sam searches, the way addr does (regexp.zig): the // text around the selection still says where its lines begin. var at = from; @@ -115,7 +137,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: while (at < to and m < Text.max_selections) { // A search too slow to finish keeps what it found so far. const hit_at = (re.find(hay_all, at, to, to) catch break) orelse break; - if (split) { + if (mode == .split) { out[m] = .{ .anchor = piece, .head = hit_at.start }; m += 1; piece = hit_at.end; @@ -126,7 +148,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, split: // an empty match would otherwise never advance at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1; } - if (split and piece < to and m < Text.max_selections) { + if (mode == .split and piece < to and m < Text.max_selections) { out[m] = .{ .anchor = piece, .head = to }; m += 1; } @@ -542,7 +564,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void }, // s, S and | answer for the text they are pressed in; `/` searches // the body wherever it is pressed, as acme's Look from a tag does. - .select_regex => |split| return startSelRegex(p, pane, t, split), + .select_regex => |mode| return startSelRegex(p, pane, t, mode), .edit => |op| switch (op.kind) { .delete => return edit.normalDelete(p, t, true), .delete_noyank => return edit.normalDelete(p, t, false), @@ -795,20 +817,20 @@ test "s and S search a multi-line selection as addr does: ^ and $ per line, . wi defer p.deinit(); const text = "alpha x\nbeta alpha\nalphabet\n"; const pane = try p.setTestFile(text); - const Case = struct { pat: []const u8, split: bool, want: []const [2]usize }; + const Case = struct { pat: []const u8, mode: modal.Normal.RegexMode, want: []const [2]usize }; for ([_]Case{ // ^ at each line's start, not only the selection's - .{ .pat = "^alpha", .split = false, .want = &.{ .{ 0, 5 }, .{ 19, 24 } } }, + .{ .pat = "^alpha", .mode = .select, .want = &.{ .{ 0, 5 }, .{ 19, 24 } } }, // $ at each line's end - .{ .pat = "alpha$", .split = false, .want = &.{.{ 13, 18 }} }, + .{ .pat = "alpha$", .mode = .select, .want = &.{.{ 13, 18 }} }, // . stops at the newline: one selection per line, not one for all - .{ .pat = "a.*", .split = false, .want = &.{ .{ 0, 7 }, .{ 11, 18 }, .{ 19, 27 } } }, + .{ .pat = "a.*", .mode = .select, .want = &.{ .{ 0, 7 }, .{ 11, 18 }, .{ 19, 27 } } }, // S splits on a line's end - .{ .pat = "$", .split = true, .want = &.{ .{ 0, 7 }, .{ 7, 18 }, .{ 18, 27 }, .{ 27, 28 } } }, + .{ .pat = "$", .mode = .split, .want = &.{ .{ 0, 7 }, .{ 7, 18 }, .{ 18, 27 }, .{ 27, 28 } } }, }) |c| { pane.sel_snap[0] = .{ .anchor = 0, .head = text.len }; pane.nsel_snap = 1; - applySelRegex(p, pane, &pane.body, c.pat, c.split); + applySelRegex(p, pane, &pane.body, c.pat, c.mode); var out: [Text.max_selections]modal.Selection = undefined; const got = pane.body.ranges(text, 0, &out); try std.testing.expectEqual(c.want.len, got.n); diff --git a/src/pardes.zig b/src/pardes.zig index a7bcb195..d43b38b1 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5270,7 +5270,7 @@ pub const Pardes = struct { .search => if (submit) look.submitSearch(p, p.active) else if (normal.selRegexArmed(pane)) |_| if (target) |answered| - normal.applySelRegex(p, pane, answered, "", false), + normal.applySelRegex(p, pane, answered, "", .select), .none, .del_side, .repl_choice, .name => unreachable, } pane.closePrompt(); @@ -5281,7 +5281,7 @@ pub const Pardes = struct { return; } edit.handleInsert(p, &pane.input, key); - if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.split); + if (normal.selRegexArmed(pane)) |a| if (p.promptTarget(pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); return; } if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) { diff --git a/test/hxcases/cases.jsonl b/test/hxcases/cases.jsonl index 7aeb12e8..43cbbf11 100644 --- a/test/hxcases/cases.jsonl +++ b/test/hxcases/cases.jsonl @@ -432,6 +432,14 @@ {"name": "msel-rotate-contents-lines", "pane": "file", "text": "aa\nbbb\n", "keys": "%"} {"name": "sel-many-ranges", "pane": "file", "text": "w w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\n", "keys": "%sw"} {"name": "sel-many-ranges-edit", "pane": "file", "text": "w w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\n", "keys": "%swcxy"} +{"name": "keep-regex", "pane": "file", "text": "foo bar baz\n", "keys": "%s\\w+Kba"} +{"name": "remove-regex", "pane": "file", "text": "foo bar baz\n", "keys": "%s\\w+ba"} +{"name": "keep-regex-none", "pane": "file", "text": "foo bar\n", "keys": "%s\\w+Kzz"} +{"name": "keep-regex-primary", "pane": "file", "text": "a1 b2 a3\n", "keys": "%s\\w+))Ka"} +{"name": "keep-regex-esc", "pane": "file", "text": "foo bar\n", "keys": "%s\\w+Kfo"} +{"name": "keep-regex-lines", "pane": "file", "text": "foo\nbar\nbaz\n", "keys": "%K^b"} +{"name": "ensure-forward", "pane": "file", "text": "ab cd\n", "keys": "%s\\w+"} +{"name": "ensure-forward-one", "pane": "file", "text": "abc\n", "keys": "vll"} {"name": "msel-align-basic", "pane": "file", "text": "a=1\nbbb=2\n", "keys": "%s=&"} {"name": "msel-align-columns", "pane": "file", "text": "a,b,c\nccc,d,e\n", "keys": "%s,&"} {"name": "msel-align-uneven", "pane": "file", "text": "a,b\nccc,d,eee,f\n", "keys": "%s,&"} diff --git a/test/hxcases/goldens.jsonl b/test/hxcases/goldens.jsonl index b8221c4c..9839335a 100644 --- a/test/hxcases/goldens.jsonl +++ b/test/hxcases/goldens.jsonl @@ -432,6 +432,14 @@ {"name":"msel-rotate-contents-lines","text":"bbb\naa\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":0}}],"primary":1} {"name":"sel-many-ranges","text":"w w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\nw w w w w w w w w w w w w w w w w w w w\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}},{"cursor":{"row":0,"col":4},"anchor":{"row":0,"col":4}},{"cursor":{"row":0,"col":6},"anchor":{"row":0,"col":6}},{"cursor":{"row":0,"col":8},"anchor":{"row":0,"col":8}},{"cursor":{"row":0,"col":10},"anchor":{"row":0,"col":10}},{"cursor":{"row":0,"col":12},"anchor":{"row":0,"col":12}},{"cursor":{"row":0,"col":14},"anchor":{"row":0,"col":14}},{"cursor":{"row":0,"col":16},"anchor":{"row":0,"col":16}},{"cursor":{"row":0,"col":18},"anchor":{"row":0,"col":18}},{"cursor":{"row":0,"col":20},"anchor":{"row":0,"col":20}},{"cursor":{"row":0,"col":22},"anchor":{"row":0,"col":22}},{"cursor":{"row":0,"col":24},"anchor":{"row":0,"col":24}},{"cursor":{"row":0,"col":26},"anchor":{"row":0,"col":26}},{"cursor":{"row":0,"col":28},"anchor":{"row":0,"col":28}},{"cursor":{"row":0,"col":30},"anchor":{"row":0,"col":30}},{"cursor":{"row":0,"col":32},"anchor":{"row":0,"col":32}},{"cursor":{"row":0,"col":34},"anchor":{"row":0,"col":34}},{"cursor":{"row":0,"col":36},"anchor":{"row":0,"col":36}},{"cursor":{"row":0,"col":38},"anchor":{"row":0,"col":38}},{"cursor":{"row":1,"col":0},"anchor":{"row":1,"col":0}},{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2}},{"cursor":{"row":1,"col":4},"anchor":{"row":1,"col":4}},{"cursor":{"row":1,"col":6},"anchor":{"row":1,"col":6}},{"cursor":{"row":1,"col":8},"anchor":{"row":1,"col":8}},{"cursor":{"row":1,"col":10},"anchor":{"row":1,"col":10}},{"cursor":{"row":1,"col":12},"anchor":{"row":1,"col":12}},{"cursor":{"row":1,"col":14},"anchor":{"row":1,"col":14}},{"cursor":{"row":1,"col":16},"anchor":{"row":1,"col":16}},{"cursor":{"row":1,"col":18},"anchor":{"row":1,"col":18}},{"cursor":{"row":1,"col":20},"anchor":{"row":1,"col":20}},{"cursor":{"row":1,"col":22},"anchor":{"row":1,"col":22}},{"cursor":{"row":1,"col":24},"anchor":{"row":1,"col":24}},{"cursor":{"row":1,"col":26},"anchor":{"row":1,"col":26}},{"cursor":{"row":1,"col":28},"anchor":{"row":1,"col":28}},{"cursor":{"row":1,"col":30},"anchor":{"row":1,"col":30}},{"cursor":{"row":1,"col":32},"anchor":{"row":1,"col":32}},{"cursor":{"row":1,"col":34},"anchor":{"row":1,"col":34}},{"cursor":{"row":1,"col":36},"anchor":{"row":1,"col":36}},{"cursor":{"row":1,"col":38},"anchor":{"row":1,"col":38}},{"cursor":{"row":2,"col":0},"anchor":{"row":2,"col":0}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":2}},{"cursor":{"row":2,"col":4},"anchor":{"row":2,"col":4}},{"cursor":{"row":2,"col":6},"anchor":{"row":2,"col":6}},{"cursor":{"row":2,"col":8},"anchor":{"row":2,"col":8}},{"cursor":{"row":2,"col":10},"anchor":{"row":2,"col":10}},{"cursor":{"row":2,"col":12},"anchor":{"row":2,"col":12}},{"cursor":{"row":2,"col":14},"anchor":{"row":2,"col":14}},{"cursor":{"row":2,"col":16},"anchor":{"row":2,"col":16}},{"cursor":{"row":2,"col":18},"anchor":{"row":2,"col":18}},{"cursor":{"row":2,"col":20},"anchor":{"row":2,"col":20}},{"cursor":{"row":2,"col":22},"anchor":{"row":2,"col":22}},{"cursor":{"row":2,"col":24},"anchor":{"row":2,"col":24}},{"cursor":{"row":2,"col":26},"anchor":{"row":2,"col":26}},{"cursor":{"row":2,"col":28},"anchor":{"row":2,"col":28}},{"cursor":{"row":2,"col":30},"anchor":{"row":2,"col":30}},{"cursor":{"row":2,"col":32},"anchor":{"row":2,"col":32}},{"cursor":{"row":2,"col":34},"anchor":{"row":2,"col":34}},{"cursor":{"row":2,"col":36},"anchor":{"row":2,"col":36}},{"cursor":{"row":2,"col":38},"anchor":{"row":2,"col":38}},{"cursor":{"row":3,"col":0},"anchor":{"row":3,"col":0}},{"cursor":{"row":3,"col":2},"anchor":{"row":3,"col":2}},{"cursor":{"row":3,"col":4},"anchor":{"row":3,"col":4}},{"cursor":{"row":3,"col":6},"anchor":{"row":3,"col":6}},{"cursor":{"row":3,"col":8},"anchor":{"row":3,"col":8}},{"cursor":{"row":3,"col":10},"anchor":{"row":3,"col":10}},{"cursor":{"row":3,"col":12},"anchor":{"row":3,"col":12}},{"cursor":{"row":3,"col":14},"anchor":{"row":3,"col":14}},{"cursor":{"row":3,"col":16},"anchor":{"row":3,"col":16}},{"cursor":{"row":3,"col":18},"anchor":{"row":3,"col":18}},{"cursor":{"row":3,"col":20},"anchor":{"row":3,"col":20}},{"cursor":{"row":3,"col":22},"anchor":{"row":3,"col":22}},{"cursor":{"row":3,"col":24},"anchor":{"row":3,"col":24}},{"cursor":{"row":3,"col":26},"anchor":{"row":3,"col":26}},{"cursor":{"row":3,"col":28},"anchor":{"row":3,"col":28}},{"cursor":{"row":3,"col":30},"anchor":{"row":3,"col":30}},{"cursor":{"row":3,"col":32},"anchor":{"row":3,"col":32}},{"cursor":{"row":3,"col":34},"anchor":{"row":3,"col":34}},{"cursor":{"row":3,"col":36},"anchor":{"row":3,"col":36}},{"cursor":{"row":3,"col":38},"anchor":{"row":3,"col":38}},{"cursor":{"row":4,"col":0},"anchor":{"row":4,"col":0}},{"cursor":{"row":4,"col":2},"anchor":{"row":4,"col":2}},{"cursor":{"row":4,"col":4},"anchor":{"row":4,"col":4}},{"cursor":{"row":4,"col":6},"anchor":{"row":4,"col":6}},{"cursor":{"row":4,"col":8},"anchor":{"row":4,"col":8}},{"cursor":{"row":4,"col":10},"anchor":{"row":4,"col":10}},{"cursor":{"row":4,"col":12},"anchor":{"row":4,"col":12}},{"cursor":{"row":4,"col":14},"anchor":{"row":4,"col":14}},{"cursor":{"row":4,"col":16},"anchor":{"row":4,"col":16}},{"cursor":{"row":4,"col":18},"anchor":{"row":4,"col":18}},{"cursor":{"row":4,"col":20},"anchor":{"row":4,"col":20}},{"cursor":{"row":4,"col":22},"anchor":{"row":4,"col":22}},{"cursor":{"row":4,"col":24},"anchor":{"row":4,"col":24}},{"cursor":{"row":4,"col":26},"anchor":{"row":4,"col":26}},{"cursor":{"row":4,"col":28},"anchor":{"row":4,"col":28}},{"cursor":{"row":4,"col":30},"anchor":{"row":4,"col":30}},{"cursor":{"row":4,"col":32},"anchor":{"row":4,"col":32}},{"cursor":{"row":4,"col":34},"anchor":{"row":4,"col":34}},{"cursor":{"row":4,"col":36},"anchor":{"row":4,"col":36}},{"cursor":{"row":4,"col":38},"anchor":{"row":4,"col":38}},{"cursor":{"row":5,"col":0},"anchor":{"row":5,"col":0}},{"cursor":{"row":5,"col":2},"anchor":{"row":5,"col":2}},{"cursor":{"row":5,"col":4},"anchor":{"row":5,"col":4}},{"cursor":{"row":5,"col":6},"anchor":{"row":5,"col":6}},{"cursor":{"row":5,"col":8},"anchor":{"row":5,"col":8}},{"cursor":{"row":5,"col":10},"anchor":{"row":5,"col":10}},{"cursor":{"row":5,"col":12},"anchor":{"row":5,"col":12}},{"cursor":{"row":5,"col":14},"anchor":{"row":5,"col":14}},{"cursor":{"row":5,"col":16},"anchor":{"row":5,"col":16}},{"cursor":{"row":5,"col":18},"anchor":{"row":5,"col":18}},{"cursor":{"row":5,"col":20},"anchor":{"row":5,"col":20}},{"cursor":{"row":5,"col":22},"anchor":{"row":5,"col":22}},{"cursor":{"row":5,"col":24},"anchor":{"row":5,"col":24}},{"cursor":{"row":5,"col":26},"anchor":{"row":5,"col":26}},{"cursor":{"row":5,"col":28},"anchor":{"row":5,"col":28}},{"cursor":{"row":5,"col":30},"anchor":{"row":5,"col":30}},{"cursor":{"row":5,"col":32},"anchor":{"row":5,"col":32}},{"cursor":{"row":5,"col":34},"anchor":{"row":5,"col":34}},{"cursor":{"row":5,"col":36},"anchor":{"row":5,"col":36}},{"cursor":{"row":5,"col":38},"anchor":{"row":5,"col":38}},{"cursor":{"row":6,"col":0},"anchor":{"row":6,"col":0}},{"cursor":{"row":6,"col":2},"anchor":{"row":6,"col":2}},{"cursor":{"row":6,"col":4},"anchor":{"row":6,"col":4}},{"cursor":{"row":6,"col":6},"anchor":{"row":6,"col":6}},{"cursor":{"row":6,"col":8},"anchor":{"row":6,"col":8}},{"cursor":{"row":6,"col":10},"anchor":{"row":6,"col":10}},{"cursor":{"row":6,"col":12},"anchor":{"row":6,"col":12}},{"cursor":{"row":6,"col":14},"anchor":{"row":6,"col":14}},{"cursor":{"row":6,"col":16},"anchor":{"row":6,"col":16}},{"cursor":{"row":6,"col":18},"anchor":{"row":6,"col":18}},{"cursor":{"row":6,"col":20},"anchor":{"row":6,"col":20}},{"cursor":{"row":6,"col":22},"anchor":{"row":6,"col":22}},{"cursor":{"row":6,"col":24},"anchor":{"row":6,"col":24}},{"cursor":{"row":6,"col":26},"anchor":{"row":6,"col":26}},{"cursor":{"row":6,"col":28},"anchor":{"row":6,"col":28}},{"cursor":{"row":6,"col":30},"anchor":{"row":6,"col":30}},{"cursor":{"row":6,"col":32},"anchor":{"row":6,"col":32}},{"cursor":{"row":6,"col":34},"anchor":{"row":6,"col":34}},{"cursor":{"row":6,"col":36},"anchor":{"row":6,"col":36}},{"cursor":{"row":6,"col":38},"anchor":{"row":6,"col":38}},{"cursor":{"row":7,"col":0},"anchor":{"row":7,"col":0}},{"cursor":{"row":7,"col":2},"anchor":{"row":7,"col":2}},{"cursor":{"row":7,"col":4},"anchor":{"row":7,"col":4}},{"cursor":{"row":7,"col":6},"anchor":{"row":7,"col":6}},{"cursor":{"row":7,"col":8},"anchor":{"row":7,"col":8}},{"cursor":{"row":7,"col":10},"anchor":{"row":7,"col":10}},{"cursor":{"row":7,"col":12},"anchor":{"row":7,"col":12}},{"cursor":{"row":7,"col":14},"anchor":{"row":7,"col":14}},{"cursor":{"row":7,"col":16},"anchor":{"row":7,"col":16}},{"cursor":{"row":7,"col":18},"anchor":{"row":7,"col":18}},{"cursor":{"row":7,"col":20},"anchor":{"row":7,"col":20}},{"cursor":{"row":7,"col":22},"anchor":{"row":7,"col":22}},{"cursor":{"row":7,"col":24},"anchor":{"row":7,"col":24}},{"cursor":{"row":7,"col":26},"anchor":{"row":7,"col":26}},{"cursor":{"row":7,"col":28},"anchor":{"row":7,"col":28}},{"cursor":{"row":7,"col":30},"anchor":{"row":7,"col":30}},{"cursor":{"row":7,"col":32},"anchor":{"row":7,"col":32}},{"cursor":{"row":7,"col":34},"anchor":{"row":7,"col":34}},{"cursor":{"row":7,"col":36},"anchor":{"row":7,"col":36}},{"cursor":{"row":7,"col":38},"anchor":{"row":7,"col":38}},{"cursor":{"row":8,"col":0},"anchor":{"row":8,"col":0}},{"cursor":{"row":8,"col":2},"anchor":{"row":8,"col":2}},{"cursor":{"row":8,"col":4},"anchor":{"row":8,"col":4}},{"cursor":{"row":8,"col":6},"anchor":{"row":8,"col":6}},{"cursor":{"row":8,"col":8},"anchor":{"row":8,"col":8}},{"cursor":{"row":8,"col":10},"anchor":{"row":8,"col":10}},{"cursor":{"row":8,"col":12},"anchor":{"row":8,"col":12}},{"cursor":{"row":8,"col":14},"anchor":{"row":8,"col":14}},{"cursor":{"row":8,"col":16},"anchor":{"row":8,"col":16}},{"cursor":{"row":8,"col":18},"anchor":{"row":8,"col":18}},{"cursor":{"row":8,"col":20},"anchor":{"row":8,"col":20}},{"cursor":{"row":8,"col":22},"anchor":{"row":8,"col":22}},{"cursor":{"row":8,"col":24},"anchor":{"row":8,"col":24}},{"cursor":{"row":8,"col":26},"anchor":{"row":8,"col":26}},{"cursor":{"row":8,"col":28},"anchor":{"row":8,"col":28}},{"cursor":{"row":8,"col":30},"anchor":{"row":8,"col":30}},{"cursor":{"row":8,"col":32},"anchor":{"row":8,"col":32}},{"cursor":{"row":8,"col":34},"anchor":{"row":8,"col":34}},{"cursor":{"row":8,"col":36},"anchor":{"row":8,"col":36}},{"cursor":{"row":8,"col":38},"anchor":{"row":8,"col":38}},{"cursor":{"row":9,"col":0},"anchor":{"row":9,"col":0}},{"cursor":{"row":9,"col":2},"anchor":{"row":9,"col":2}},{"cursor":{"row":9,"col":4},"anchor":{"row":9,"col":4}},{"cursor":{"row":9,"col":6},"anchor":{"row":9,"col":6}},{"cursor":{"row":9,"col":8},"anchor":{"row":9,"col":8}},{"cursor":{"row":9,"col":10},"anchor":{"row":9,"col":10}},{"cursor":{"row":9,"col":12},"anchor":{"row":9,"col":12}},{"cursor":{"row":9,"col":14},"anchor":{"row":9,"col":14}},{"cursor":{"row":9,"col":16},"anchor":{"row":9,"col":16}},{"cursor":{"row":9,"col":18},"anchor":{"row":9,"col":18}},{"cursor":{"row":9,"col":20},"anchor":{"row":9,"col":20}},{"cursor":{"row":9,"col":22},"anchor":{"row":9,"col":22}},{"cursor":{"row":9,"col":24},"anchor":{"row":9,"col":24}},{"cursor":{"row":9,"col":26},"anchor":{"row":9,"col":26}},{"cursor":{"row":9,"col":28},"anchor":{"row":9,"col":28}},{"cursor":{"row":9,"col":30},"anchor":{"row":9,"col":30}},{"cursor":{"row":9,"col":32},"anchor":{"row":9,"col":32}},{"cursor":{"row":9,"col":34},"anchor":{"row":9,"col":34}},{"cursor":{"row":9,"col":36},"anchor":{"row":9,"col":36}},{"cursor":{"row":9,"col":38},"anchor":{"row":9,"col":38}}],"primary":0} {"name":"sel-many-ranges-edit","text":"xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\nxy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy xy\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}},{"cursor":{"row":0,"col":5},"anchor":{"row":0,"col":5}},{"cursor":{"row":0,"col":8},"anchor":{"row":0,"col":8}},{"cursor":{"row":0,"col":11},"anchor":{"row":0,"col":11}},{"cursor":{"row":0,"col":14},"anchor":{"row":0,"col":14}},{"cursor":{"row":0,"col":17},"anchor":{"row":0,"col":17}},{"cursor":{"row":0,"col":20},"anchor":{"row":0,"col":20}},{"cursor":{"row":0,"col":23},"anchor":{"row":0,"col":23}},{"cursor":{"row":0,"col":26},"anchor":{"row":0,"col":26}},{"cursor":{"row":0,"col":29},"anchor":{"row":0,"col":29}},{"cursor":{"row":0,"col":32},"anchor":{"row":0,"col":32}},{"cursor":{"row":0,"col":35},"anchor":{"row":0,"col":35}},{"cursor":{"row":0,"col":38},"anchor":{"row":0,"col":38}},{"cursor":{"row":0,"col":41},"anchor":{"row":0,"col":41}},{"cursor":{"row":0,"col":44},"anchor":{"row":0,"col":44}},{"cursor":{"row":0,"col":47},"anchor":{"row":0,"col":47}},{"cursor":{"row":0,"col":50},"anchor":{"row":0,"col":50}},{"cursor":{"row":0,"col":53},"anchor":{"row":0,"col":53}},{"cursor":{"row":0,"col":56},"anchor":{"row":0,"col":56}},{"cursor":{"row":0,"col":59},"anchor":{"row":0,"col":59}},{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":2}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}},{"cursor":{"row":1,"col":8},"anchor":{"row":1,"col":8}},{"cursor":{"row":1,"col":11},"anchor":{"row":1,"col":11}},{"cursor":{"row":1,"col":14},"anchor":{"row":1,"col":14}},{"cursor":{"row":1,"col":17},"anchor":{"row":1,"col":17}},{"cursor":{"row":1,"col":20},"anchor":{"row":1,"col":20}},{"cursor":{"row":1,"col":23},"anchor":{"row":1,"col":23}},{"cursor":{"row":1,"col":26},"anchor":{"row":1,"col":26}},{"cursor":{"row":1,"col":29},"anchor":{"row":1,"col":29}},{"cursor":{"row":1,"col":32},"anchor":{"row":1,"col":32}},{"cursor":{"row":1,"col":35},"anchor":{"row":1,"col":35}},{"cursor":{"row":1,"col":38},"anchor":{"row":1,"col":38}},{"cursor":{"row":1,"col":41},"anchor":{"row":1,"col":41}},{"cursor":{"row":1,"col":44},"anchor":{"row":1,"col":44}},{"cursor":{"row":1,"col":47},"anchor":{"row":1,"col":47}},{"cursor":{"row":1,"col":50},"anchor":{"row":1,"col":50}},{"cursor":{"row":1,"col":53},"anchor":{"row":1,"col":53}},{"cursor":{"row":1,"col":56},"anchor":{"row":1,"col":56}},{"cursor":{"row":1,"col":59},"anchor":{"row":1,"col":59}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":2}},{"cursor":{"row":2,"col":5},"anchor":{"row":2,"col":5}},{"cursor":{"row":2,"col":8},"anchor":{"row":2,"col":8}},{"cursor":{"row":2,"col":11},"anchor":{"row":2,"col":11}},{"cursor":{"row":2,"col":14},"anchor":{"row":2,"col":14}},{"cursor":{"row":2,"col":17},"anchor":{"row":2,"col":17}},{"cursor":{"row":2,"col":20},"anchor":{"row":2,"col":20}},{"cursor":{"row":2,"col":23},"anchor":{"row":2,"col":23}},{"cursor":{"row":2,"col":26},"anchor":{"row":2,"col":26}},{"cursor":{"row":2,"col":29},"anchor":{"row":2,"col":29}},{"cursor":{"row":2,"col":32},"anchor":{"row":2,"col":32}},{"cursor":{"row":2,"col":35},"anchor":{"row":2,"col":35}},{"cursor":{"row":2,"col":38},"anchor":{"row":2,"col":38}},{"cursor":{"row":2,"col":41},"anchor":{"row":2,"col":41}},{"cursor":{"row":2,"col":44},"anchor":{"row":2,"col":44}},{"cursor":{"row":2,"col":47},"anchor":{"row":2,"col":47}},{"cursor":{"row":2,"col":50},"anchor":{"row":2,"col":50}},{"cursor":{"row":2,"col":53},"anchor":{"row":2,"col":53}},{"cursor":{"row":2,"col":56},"anchor":{"row":2,"col":56}},{"cursor":{"row":2,"col":59},"anchor":{"row":2,"col":59}},{"cursor":{"row":3,"col":2},"anchor":{"row":3,"col":2}},{"cursor":{"row":3,"col":5},"anchor":{"row":3,"col":5}},{"cursor":{"row":3,"col":8},"anchor":{"row":3,"col":8}},{"cursor":{"row":3,"col":11},"anchor":{"row":3,"col":11}},{"cursor":{"row":3,"col":14},"anchor":{"row":3,"col":14}},{"cursor":{"row":3,"col":17},"anchor":{"row":3,"col":17}},{"cursor":{"row":3,"col":20},"anchor":{"row":3,"col":20}},{"cursor":{"row":3,"col":23},"anchor":{"row":3,"col":23}},{"cursor":{"row":3,"col":26},"anchor":{"row":3,"col":26}},{"cursor":{"row":3,"col":29},"anchor":{"row":3,"col":29}},{"cursor":{"row":3,"col":32},"anchor":{"row":3,"col":32}},{"cursor":{"row":3,"col":35},"anchor":{"row":3,"col":35}},{"cursor":{"row":3,"col":38},"anchor":{"row":3,"col":38}},{"cursor":{"row":3,"col":41},"anchor":{"row":3,"col":41}},{"cursor":{"row":3,"col":44},"anchor":{"row":3,"col":44}},{"cursor":{"row":3,"col":47},"anchor":{"row":3,"col":47}},{"cursor":{"row":3,"col":50},"anchor":{"row":3,"col":50}},{"cursor":{"row":3,"col":53},"anchor":{"row":3,"col":53}},{"cursor":{"row":3,"col":56},"anchor":{"row":3,"col":56}},{"cursor":{"row":3,"col":59},"anchor":{"row":3,"col":59}},{"cursor":{"row":4,"col":2},"anchor":{"row":4,"col":2}},{"cursor":{"row":4,"col":5},"anchor":{"row":4,"col":5}},{"cursor":{"row":4,"col":8},"anchor":{"row":4,"col":8}},{"cursor":{"row":4,"col":11},"anchor":{"row":4,"col":11}},{"cursor":{"row":4,"col":14},"anchor":{"row":4,"col":14}},{"cursor":{"row":4,"col":17},"anchor":{"row":4,"col":17}},{"cursor":{"row":4,"col":20},"anchor":{"row":4,"col":20}},{"cursor":{"row":4,"col":23},"anchor":{"row":4,"col":23}},{"cursor":{"row":4,"col":26},"anchor":{"row":4,"col":26}},{"cursor":{"row":4,"col":29},"anchor":{"row":4,"col":29}},{"cursor":{"row":4,"col":32},"anchor":{"row":4,"col":32}},{"cursor":{"row":4,"col":35},"anchor":{"row":4,"col":35}},{"cursor":{"row":4,"col":38},"anchor":{"row":4,"col":38}},{"cursor":{"row":4,"col":41},"anchor":{"row":4,"col":41}},{"cursor":{"row":4,"col":44},"anchor":{"row":4,"col":44}},{"cursor":{"row":4,"col":47},"anchor":{"row":4,"col":47}},{"cursor":{"row":4,"col":50},"anchor":{"row":4,"col":50}},{"cursor":{"row":4,"col":53},"anchor":{"row":4,"col":53}},{"cursor":{"row":4,"col":56},"anchor":{"row":4,"col":56}},{"cursor":{"row":4,"col":59},"anchor":{"row":4,"col":59}},{"cursor":{"row":5,"col":2},"anchor":{"row":5,"col":2}},{"cursor":{"row":5,"col":5},"anchor":{"row":5,"col":5}},{"cursor":{"row":5,"col":8},"anchor":{"row":5,"col":8}},{"cursor":{"row":5,"col":11},"anchor":{"row":5,"col":11}},{"cursor":{"row":5,"col":14},"anchor":{"row":5,"col":14}},{"cursor":{"row":5,"col":17},"anchor":{"row":5,"col":17}},{"cursor":{"row":5,"col":20},"anchor":{"row":5,"col":20}},{"cursor":{"row":5,"col":23},"anchor":{"row":5,"col":23}},{"cursor":{"row":5,"col":26},"anchor":{"row":5,"col":26}},{"cursor":{"row":5,"col":29},"anchor":{"row":5,"col":29}},{"cursor":{"row":5,"col":32},"anchor":{"row":5,"col":32}},{"cursor":{"row":5,"col":35},"anchor":{"row":5,"col":35}},{"cursor":{"row":5,"col":38},"anchor":{"row":5,"col":38}},{"cursor":{"row":5,"col":41},"anchor":{"row":5,"col":41}},{"cursor":{"row":5,"col":44},"anchor":{"row":5,"col":44}},{"cursor":{"row":5,"col":47},"anchor":{"row":5,"col":47}},{"cursor":{"row":5,"col":50},"anchor":{"row":5,"col":50}},{"cursor":{"row":5,"col":53},"anchor":{"row":5,"col":53}},{"cursor":{"row":5,"col":56},"anchor":{"row":5,"col":56}},{"cursor":{"row":5,"col":59},"anchor":{"row":5,"col":59}},{"cursor":{"row":6,"col":2},"anchor":{"row":6,"col":2}},{"cursor":{"row":6,"col":5},"anchor":{"row":6,"col":5}},{"cursor":{"row":6,"col":8},"anchor":{"row":6,"col":8}},{"cursor":{"row":6,"col":11},"anchor":{"row":6,"col":11}},{"cursor":{"row":6,"col":14},"anchor":{"row":6,"col":14}},{"cursor":{"row":6,"col":17},"anchor":{"row":6,"col":17}},{"cursor":{"row":6,"col":20},"anchor":{"row":6,"col":20}},{"cursor":{"row":6,"col":23},"anchor":{"row":6,"col":23}},{"cursor":{"row":6,"col":26},"anchor":{"row":6,"col":26}},{"cursor":{"row":6,"col":29},"anchor":{"row":6,"col":29}},{"cursor":{"row":6,"col":32},"anchor":{"row":6,"col":32}},{"cursor":{"row":6,"col":35},"anchor":{"row":6,"col":35}},{"cursor":{"row":6,"col":38},"anchor":{"row":6,"col":38}},{"cursor":{"row":6,"col":41},"anchor":{"row":6,"col":41}},{"cursor":{"row":6,"col":44},"anchor":{"row":6,"col":44}},{"cursor":{"row":6,"col":47},"anchor":{"row":6,"col":47}},{"cursor":{"row":6,"col":50},"anchor":{"row":6,"col":50}},{"cursor":{"row":6,"col":53},"anchor":{"row":6,"col":53}},{"cursor":{"row":6,"col":56},"anchor":{"row":6,"col":56}},{"cursor":{"row":6,"col":59},"anchor":{"row":6,"col":59}},{"cursor":{"row":7,"col":2},"anchor":{"row":7,"col":2}},{"cursor":{"row":7,"col":5},"anchor":{"row":7,"col":5}},{"cursor":{"row":7,"col":8},"anchor":{"row":7,"col":8}},{"cursor":{"row":7,"col":11},"anchor":{"row":7,"col":11}},{"cursor":{"row":7,"col":14},"anchor":{"row":7,"col":14}},{"cursor":{"row":7,"col":17},"anchor":{"row":7,"col":17}},{"cursor":{"row":7,"col":20},"anchor":{"row":7,"col":20}},{"cursor":{"row":7,"col":23},"anchor":{"row":7,"col":23}},{"cursor":{"row":7,"col":26},"anchor":{"row":7,"col":26}},{"cursor":{"row":7,"col":29},"anchor":{"row":7,"col":29}},{"cursor":{"row":7,"col":32},"anchor":{"row":7,"col":32}},{"cursor":{"row":7,"col":35},"anchor":{"row":7,"col":35}},{"cursor":{"row":7,"col":38},"anchor":{"row":7,"col":38}},{"cursor":{"row":7,"col":41},"anchor":{"row":7,"col":41}},{"cursor":{"row":7,"col":44},"anchor":{"row":7,"col":44}},{"cursor":{"row":7,"col":47},"anchor":{"row":7,"col":47}},{"cursor":{"row":7,"col":50},"anchor":{"row":7,"col":50}},{"cursor":{"row":7,"col":53},"anchor":{"row":7,"col":53}},{"cursor":{"row":7,"col":56},"anchor":{"row":7,"col":56}},{"cursor":{"row":7,"col":59},"anchor":{"row":7,"col":59}},{"cursor":{"row":8,"col":2},"anchor":{"row":8,"col":2}},{"cursor":{"row":8,"col":5},"anchor":{"row":8,"col":5}},{"cursor":{"row":8,"col":8},"anchor":{"row":8,"col":8}},{"cursor":{"row":8,"col":11},"anchor":{"row":8,"col":11}},{"cursor":{"row":8,"col":14},"anchor":{"row":8,"col":14}},{"cursor":{"row":8,"col":17},"anchor":{"row":8,"col":17}},{"cursor":{"row":8,"col":20},"anchor":{"row":8,"col":20}},{"cursor":{"row":8,"col":23},"anchor":{"row":8,"col":23}},{"cursor":{"row":8,"col":26},"anchor":{"row":8,"col":26}},{"cursor":{"row":8,"col":29},"anchor":{"row":8,"col":29}},{"cursor":{"row":8,"col":32},"anchor":{"row":8,"col":32}},{"cursor":{"row":8,"col":35},"anchor":{"row":8,"col":35}},{"cursor":{"row":8,"col":38},"anchor":{"row":8,"col":38}},{"cursor":{"row":8,"col":41},"anchor":{"row":8,"col":41}},{"cursor":{"row":8,"col":44},"anchor":{"row":8,"col":44}},{"cursor":{"row":8,"col":47},"anchor":{"row":8,"col":47}},{"cursor":{"row":8,"col":50},"anchor":{"row":8,"col":50}},{"cursor":{"row":8,"col":53},"anchor":{"row":8,"col":53}},{"cursor":{"row":8,"col":56},"anchor":{"row":8,"col":56}},{"cursor":{"row":8,"col":59},"anchor":{"row":8,"col":59}},{"cursor":{"row":9,"col":2},"anchor":{"row":9,"col":2}},{"cursor":{"row":9,"col":5},"anchor":{"row":9,"col":5}},{"cursor":{"row":9,"col":8},"anchor":{"row":9,"col":8}},{"cursor":{"row":9,"col":11},"anchor":{"row":9,"col":11}},{"cursor":{"row":9,"col":14},"anchor":{"row":9,"col":14}},{"cursor":{"row":9,"col":17},"anchor":{"row":9,"col":17}},{"cursor":{"row":9,"col":20},"anchor":{"row":9,"col":20}},{"cursor":{"row":9,"col":23},"anchor":{"row":9,"col":23}},{"cursor":{"row":9,"col":26},"anchor":{"row":9,"col":26}},{"cursor":{"row":9,"col":29},"anchor":{"row":9,"col":29}},{"cursor":{"row":9,"col":32},"anchor":{"row":9,"col":32}},{"cursor":{"row":9,"col":35},"anchor":{"row":9,"col":35}},{"cursor":{"row":9,"col":38},"anchor":{"row":9,"col":38}},{"cursor":{"row":9,"col":41},"anchor":{"row":9,"col":41}},{"cursor":{"row":9,"col":44},"anchor":{"row":9,"col":44}},{"cursor":{"row":9,"col":47},"anchor":{"row":9,"col":47}},{"cursor":{"row":9,"col":50},"anchor":{"row":9,"col":50}},{"cursor":{"row":9,"col":53},"anchor":{"row":9,"col":53}},{"cursor":{"row":9,"col":56},"anchor":{"row":9,"col":56}},{"cursor":{"row":9,"col":59},"anchor":{"row":9,"col":59}}],"primary":0} +{"name":"keep-regex","text":"foo bar baz\n","mode":"normal","cursor":{"row":0,"col":6},"anchor":{"row":0,"col":4},"sels":[{"cursor":{"row":0,"col":6},"anchor":{"row":0,"col":4}},{"cursor":{"row":0,"col":10},"anchor":{"row":0,"col":8}}],"primary":0} +{"name":"remove-regex","text":"foo bar baz\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} +{"name":"keep-regex-none","text":"foo bar\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":6},"anchor":{"row":0,"col":4}}],"primary":0} +{"name":"keep-regex-primary","text":"a1 b2 a3\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":7},"anchor":{"row":0,"col":6}}],"primary":0} +{"name":"keep-regex-esc","text":"foo bar\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":6},"anchor":{"row":0,"col":4}}],"primary":0} +{"name":"keep-regex-lines","text":"foo\nbar\nbaz\n","mode":"normal","cursor":{"row":1,"col":2},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":0}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":0}}],"primary":0} +{"name":"ensure-forward","text":"ab cd\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":4},"anchor":{"row":0,"col":3}}],"primary":0} +{"name":"ensure-forward-one","text":"abc\n","mode":"select","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} {"name":"msel-align-basic","text":"a =1\nbbb=2\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}}],"primary":0} {"name":"msel-align-columns","text":"a ,b,c\nccc,d,e\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":0,"col":5},"anchor":{"row":0,"col":5}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}}],"primary":0} {"name":"msel-align-uneven","text":"a ,b\nccc,d,eee,f\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}},{"cursor":{"row":1,"col":9},"anchor":{"row":1,"col":9}}],"primary":0} -- cgit v1.3 From bdbab17204efdb785b6ab3cc2022484485c0ded2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:38:06 -0300 Subject: g. goes to where the last edit ended helix goto_last_modification: every range moves to the end of the last change (the start of a deletion, the end of an insertion), extending in select mode. The position is kept on the Text in surface rows, set where setEditText hands a body its new text, so a terminal's typed text has one too and moves with its scrollback. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 2 +- src/Terminal.zig | 6 +++++- src/Text.zig | 3 +++ src/config.zig | 1 + src/edit.zig | 7 +++++++ src/modal.zig | 3 +++ src/normal.zig | 4 ++++ test/hxcases/cases.jsonl | 5 +++++ test/hxcases/goldens.jsonl | 5 +++++ 9 files changed, 34 insertions(+), 2 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index f2901b92..2928d78e 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -184,6 +184,7 @@ found. Pure text math in `modal.zig`: `findChar`, `matchBracket`, | `Alt-.` | repeat last `f`/`t`/`F`/`T` motion (`Pane.find_op`/`find_ch`), takes a count | decision: repeats ONLY the find family, not `m`/`[`/`]` (helix extends it there; marginal) | helix-verified (phase 5) | | `g|`, `g|` | goto column n (1 = line start), clamped to the line | | helix-verified (phase 5) | | `gs` | goto first non-whitespace | alias of the `^` handler | helix-verified (phase 5) | +| `g.` | go to where the last edit ended (a deletion's start, an insertion's end), every range there, extending in select mode | helix `goto_last_modification`. The position is `Text.last_edit`, set by `edit.setEditText` from where the old and new texts part; helix's is the last history revision's, so with nothing edited yet pardes stays put where the harness's helix goes to the end of its setup text | helix-verified | | `gt` / `gc` / `gb` | goto screen top / center / bottom | view-relative (`pane.scroll()` + `pane.rows`), column kept (clamped) | helix-verified (phase 5) | | `gj` / `gk` | VISUAL line down / up (+ count) | follows the wrapped body's own breaks (`file_pane.visualRow`, the same walk `fillBody` renders), keeping the goal column INSIDE the row; the last row of a line steps into the next line's first. Wrap off = one row per line, and this IS `j`/`k`. helix assigns the pair the other way round (its `j` is the visual one) | pardes-specific | | `PageUp` / `PageDown` | FULL page (was half) | `Ctrl-u`/`Ctrl-d` stay the half-page pair | helix-verified (phase 5) | @@ -351,7 +352,6 @@ text. | Picker table (all rows), Prompt table (all rows) | picker / prompt internals | pickers — pardes' tag line is its own one-line editor | | `gn` `gp` `ga` `gm` | next/prev/alternate buffer | buffer nav — pardes panes aren't a buffer list | | `gw` | word-label jump | label-jump overlay machinery, not core editing | -| `g.` | goto last modification | jumplist/history position tracking | | Window mode table: `Ctrl-w` + `w v s t f F h j k l q o H J K L ns nv` (+ Ctrl variants) | splits/window management | window mode — pardes has its own Ctrl-w focus + Alt-n/Alt-c + mouse layout drags | | `]f [f ]t [t ]a [a ]c [c ]e [e ]T [T ]x [x` | TS unimpaired jumps | tree-sitter | | `]g [g ]G [G` | git change jumps | needs VCS diff state | diff --git a/src/Terminal.zig b/src/Terminal.zig index 1ff561b1..4c29e151 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -720,7 +720,7 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { if (comptime !enabled) return; if (pane.terminal == null) return; const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or - pane.body.msel.active or pane.body.nsel > 0 or pane.look_at != null or + pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; // Sticky bottom, as every other terminal does it: output drags the // viewport down only when the viewport was already on the last row, so @@ -846,6 +846,10 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { extra[nextra + 1] = &selection.arow; nextra += 2; } + if (pane.body.last_edit) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } if (pane.look_at) |*at| { extra[nextra] = &at.row; nextra += 1; diff --git a/src/Text.zig b/src/Text.zig index 411c2ec8..70ec5369 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -69,6 +69,9 @@ 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 = .{}, diff --git a/src/config.zig b/src/config.zig index 959f4c4a..993b6fe0 100644 --- a/src/config.zig +++ b/src/config.zig @@ -487,6 +487,7 @@ pub const goto_column: []const Chord = &.{.{ .cp = '|' }}; pub const goto_view_top: []const Chord = &.{.{ .cp = 't' }}; pub const goto_view_center: []const Chord = &.{.{ .cp = 'c' }}; pub const goto_view_bottom: []const Chord = &.{.{ .cp = 'b' }}; +pub const goto_last_modification: []const Chord = &.{.{ .cp = '.' }}; pub const goto_definition: []const Chord = &.{.{ .cp = 'd' }}; pub const goto_declaration: []const Chord = &.{.{ .cp = 'D' }}; pub const goto_type_definition: []const Chord = &.{.{ .cp = 'y' }}; diff --git a/src/edit.zig b/src/edit.zig index 5e0d20a4..9398674a 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -484,6 +484,13 @@ pub fn setEditText(p: *Pardes, t: *Text, new: []u8) void { return; } const pane = t.pane() orelse return retireEditText(p, new); + // what changed ended where the texts agree again from their ends + const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; + const front = std.mem.indexOfDiff(u8, old, new) orelse @min(old.len, new.len); + var back: usize = 0; + while (back < @min(old.len, new.len) - front and old[old.len - 1 - back] == new[new.len - 1 - back]) back += 1; + const end = modal.positionAt(new, new.len - back); + t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; if (pane.file) |*f| return panes.File.setContent(p, f, new); panes.Terminal.setEditText(p, pane, new); } diff --git a/src/modal.zig b/src/modal.zig index ae008f60..0171da93 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -28,6 +28,7 @@ pub const Normal = struct { goto_view_top, goto_view_center, goto_view_bottom, + goto_last_modification, goto_definition, goto_declaration, goto_type_definition, @@ -251,6 +252,7 @@ pub const Normal = struct { view_top, view_center, view_bottom, + last_modification, }; pub const View = enum { top, center, bottom, scroll_down, scroll_up }; pub const Find = enum { forward, backward, till_forward, till_backward }; @@ -437,6 +439,7 @@ pub const Normal = struct { if (key.has(.goto_view_top)) return resultAction(.{ .goto = .{ .target = .view_top, .count = count, .explicit_count = counted.explicit } }); if (key.has(.goto_view_center)) return resultAction(.{ .goto = .{ .target = .view_center, .count = count, .explicit_count = counted.explicit } }); if (key.has(.goto_view_bottom)) return resultAction(.{ .goto = .{ .target = .view_bottom, .count = count, .explicit_count = counted.explicit } }); + if (key.has(.goto_last_modification)) return resultAction(.{ .goto = .{ .target = .last_modification, .count = count, .explicit_count = counted.explicit } }); if (key.has(.goto_definition)) return resultAction(.{ .lsp = .definition }); if (key.has(.goto_declaration)) return resultAction(.{ .lsp = .declaration }); if (key.has(.goto_type_definition)) return resultAction(.{ .lsp = .type_definition }); diff --git a/src/normal.zig b/src/normal.zig index bc450581..228c9c39 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -460,6 +460,10 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .view_top => return t.gotoWindow(text, range, .top, go.count), .view_center => return t.gotoWindow(text, range, .center, go.count), .view_bottom => return t.gotoWindow(text, range, .bottom, go.count), + .last_modification => { + const at = t.last_edit orelse return; + return t.pointMove(text, range, modal.offsetAt(text, .{ .row = @intCast(@max(0, at.row)), .col = @intCast(@max(0, at.col)) })); + }, }, .view => |view| if (t.what == .body) switch (view) { .top => { diff --git a/test/hxcases/cases.jsonl b/test/hxcases/cases.jsonl index 8a8f8a94..03b20ff5 100644 --- a/test/hxcases/cases.jsonl +++ b/test/hxcases/cases.jsonl @@ -441,6 +441,11 @@ {"name": "ensure-forward", "pane": "file", "text": "ab cd\n", "keys": "%s\\w+"} {"name": "ensure-forward-one", "pane": "file", "text": "abc\n", "keys": "vll"} {"name": "node-keys-plain-text", "pane": "file", "text": "ab cd\n", "keys": "w"} +{"name": "goto-last-mod", "pane": "file", "text": "ab\ncd\nef\n", "keys": "jliXYgg"} +{"name": "goto-last-mod-go", "pane": "file", "text": "ab\ncd\nef\n", "keys": "jliXYggg."} +{"name": "goto-last-mod-delete", "pane": "file", "text": "abc\ndef\n", "keys": "jlxdgg"} +{"name": "goto-last-mod-delete-go", "pane": "file", "text": "abc\ndef\n", "keys": "jldggg."} +{"name": "goto-last-mod-select", "pane": "file", "text": "ab\ncd\nef\n", "keys": "jjiXggvg."} {"name": "msel-align-basic", "pane": "file", "text": "a=1\nbbb=2\n", "keys": "%s=&"} {"name": "msel-align-columns", "pane": "file", "text": "a,b,c\nccc,d,e\n", "keys": "%s,&"} {"name": "msel-align-uneven", "pane": "file", "text": "a,b\nccc,d,eee,f\n", "keys": "%s,&"} diff --git a/test/hxcases/goldens.jsonl b/test/hxcases/goldens.jsonl index f1df5c0a..8e642073 100644 --- a/test/hxcases/goldens.jsonl +++ b/test/hxcases/goldens.jsonl @@ -441,6 +441,11 @@ {"name":"ensure-forward","text":"ab cd\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":4},"anchor":{"row":0,"col":3}}],"primary":0} {"name":"ensure-forward-one","text":"abc\n","mode":"select","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} {"name":"node-keys-plain-text","text":"ab cd\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} +{"name":"goto-last-mod","text":"ab\ncXYd\nef\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}} +{"name":"goto-last-mod-go","text":"ab\ncXYd\nef\n","mode":"normal","cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}} +{"name":"goto-last-mod-delete","text":"abc\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}} +{"name":"goto-last-mod-delete-go","text":"abc\ndf\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}} +{"name":"goto-last-mod-select","text":"ab\ncd\nXef\n","mode":"select","cursor":{"row":2,"col":1},"anchor":{"row":0,"col":0}} {"name":"msel-align-basic","text":"a =1\nbbb=2\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}}],"primary":0} {"name":"msel-align-columns","text":"a ,b,c\nccc,d,e\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":0,"col":5},"anchor":{"row":0,"col":5}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}}],"primary":0} {"name":"msel-align-uneven","text":"a ,b\nccc,d,eee,f\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}},{"cursor":{"row":1,"col":9},"anchor":{"row":1,"col":9}}],"primary":0} -- cgit v1.3 From 68e30f560e46bb9a30433eb23b4edb1b93d69f46 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:57:01 -0300 Subject: A selection's other ranges live out of line, made at the second range and freed at one The ranges beside the primary were an inline array in every Text, which at 1024 grew each pane by about 60 KiB. They are now allocated when a second range appears (Text.reserveSels) and given back when the selection is one range again (Text.dropSels); a column's or the workspace's tag allocates from Text.gpa, any other text from its pane's. A refused tag edit restores them by copy. The Pane size budget is back to 128 KiB, and a test holds that a single cursor allocates nothing for them. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 2 +- docs/selections.md | 5 ++++- src/Terminal.zig | 5 +---- src/Text.zig | 42 +++++++++++++++++++++++++++++++++++++++--- src/edit.zig | 10 ++++++++-- src/layout.zig | 6 +++--- src/normal.zig | 28 ++++++++++++++++++++++++---- src/pardes.zig | 10 ++++++++-- test/panes.zig | 1 + 9 files changed, 89 insertions(+), 20 deletions(-) (limited to 'src/Text.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 88aca887..1fb1c67a 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -282,7 +282,7 @@ keeps the matches it found so far. | an all-lowercase pattern | matches case-blind | helix's smart-case. mvzr has no such flag, so the surface is lowercased instead (ASCII folding is byte-for-byte, so the offsets are identical) | helix-verified | | `^` and `$` | hold at every line's start and end | helix compiles with `multi_line(true)`; pardes gets the same by searching each line as its own haystack (`src/regexp.zig`) | helix-verified | | `.` | never matches a newline | as the Rust regex crate: a pattern without `\n` searches line by line, and one that names `\n` has its `.`s made `[^\n]` (`src/regexp.zig`) | helix-verified | -| many matches | up to `memory.limits.selections` ranges: 1024 on the desktop, 64 on the board; matches past it are dropped | helix has no limit. The ranges are held inline in every `Text` (about 20 KiB each on the desktop) | helix-verified up to the limit | +| many matches | up to `memory.limits.selections` ranges: 1024 on the desktop, 64 on the board; matches past it are dropped | helix has no limit. The room for them is allocated when a second range appears and given back at one range, so a single cursor costs nothing | helix-verified up to the limit | | `K` / `Alt-K` Enter | keep only the ranges a match starts inside / only those none does; primary 0, and keeping none leaves the selection alone | helix `keep_selections` / `remove_selections`, on the same prompt as `s`/`S` (markers `Keep /`, `Remove /`). The range is searched as `s` searches it, line by line with its lines' context, where helix matches the range's text alone: a `^` right at a range that starts mid-line matches in helix and not here | helix-verified | ### `Ctrl-c` — toggle comments diff --git a/docs/selections.md b/docs/selections.md index 203cf1de..5cc1df1a 100644 --- a/docs/selections.md +++ b/docs/selections.md @@ -17,7 +17,10 @@ desktop, 64 on the board). head, `vsel.row`/`vsel.col` the anchor while `vsel.active`, and a bare cursor (inactive `vsel`) is the one-character range under it. `msel` is the older whole-line form (`r0`..`r1`), kept for search-result highlights. -- The others are `sels[0..nsel]`, each a `SelRange` of head and anchor plus +- The others are `sels[0..nsel]`, in room allocated when a second range + appears and given back when the selection is one range again (a column's + or the workspace's tag allocates from `Text.gpa`, any other text from its + pane's), each a `SelRange` of head and anchor plus its own `j`/`k` goal column, in document order. The primary is not in the list; `Text.ranges` slots it in and returns its index. - Ends are CELLS, the characters a block cursor sits on, where helix's are diff --git a/src/Terminal.zig b/src/Terminal.zig index 4c29e151..ba156ada 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -545,10 +545,7 @@ test "replay ownership is terminal-only and construction rolls back on allocatio try std.testing.expectEqual(terminal and enabled, pane.terminal != null); } }; - // Most of it is the three texts' selections, limits.selections ranges - // each held inline (about 20 KiB a text on the desktop), and the regex - // prompt's snapshot of them. - try std.testing.expect(@sizeOf(Pane) < 160 * 1024); + try std.testing.expect(@sizeOf(Pane) < 128 * 1024); try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); } diff --git a/src/Text.zig b/src/Text.zig index 70ec5369..a44241ca 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -60,8 +60,14 @@ cur_row: i32 = 0, cur_col: i32 = 0, msel: LineSel = .{}, vsel: CharSel = .{}, -sels: [max_selections - 1]SelRange = undefined, +/// 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. @@ -101,10 +107,39 @@ pub fn pane(t: *Text) ?*Pane { /// 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 }; + 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; @@ -185,7 +220,7 @@ pub fn setRange(t: *Text, text: []const u8, row0: i32, r0: modal.Selection, expl .explicit = explicit or t.select, }; t.msel.active = false; - t.nsel = 0; // writing ONE range means the selection IS that range + t.dropSels(); // writing ONE range means the selection IS that range t.cur_pinned = true; t.sticky_col = -1; t.normal.clear(); @@ -262,6 +297,7 @@ pub fn setRanges(t: *Text, text: []const u8, in: []const modal.Selection, sticky } 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| { diff --git a/src/edit.zig b/src/edit.zig index 01b34237..5437a67d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -167,10 +167,16 @@ fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void { if (bytes.len == 0) return; const typed: pardes.Key = .{ .cp = bytes[0], .text = bytes }; if (t.what == .tag and t.mode == .insert) if (t.pane()) |pane| if (tagline.typedIntoName(p, pane, typed)) return; - const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel }; + const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel }; + var kept_sels: [Text.max_selections - 1]Text.SelRange = undefined; + const kept_n = t.nsel; + @memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]); t.refused = false; if (t.mode == .insert) insertKey(p, t, typed) else pasteText(p, t, bytes, false, 1); - if (t.refused) t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel = kept; + if (t.refused) { + t.cur_row, t.cur_col, t.vsel, t.msel = kept; + t.restoreSels(kept_sels[0..kept_n]); + } } pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { diff --git a/src/layout.zig b/src/layout.zig index 8e44f1d9..be8bad67 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -947,7 +947,7 @@ pub fn removePane(p: *Pardes, id: usize) void { p.col_serial[j] = p.col_serial[j + 1]; } p.ncol -= 1; - p.col_tags[p.ncol] = .{ .what = .column }; + p.col_tags[p.ncol] = .{ .what = .column, .gpa = p.gpa }; p.col_serial[p.ncol] = 0; } } @@ -971,7 +971,7 @@ pub fn joinCol(p: *Pardes) void { p.col_serial[j] = p.col_serial[j + 1]; } p.ncol -= 1; - p.col_tags[p.ncol] = .{ .what = .column }; + p.col_tags[p.ncol] = .{ .what = .column, .gpa = p.gpa }; p.col_serial[p.ncol] = 0; } @@ -1021,7 +1021,7 @@ pub fn splitColumn(p: *Pardes, source_id: usize, id: usize, before: bool) bool { p.col_serial[j] = p.col_serial[j - 1]; } p.col_weight[c] = new_weight; - p.col_tags[c] = .{ .what = .column }; + p.col_tags[c] = .{ .what = .column, .gpa = p.gpa }; p.col_serial[c] = 0; p.col_panes[c][0] = id; p.col_n[c] = 1; diff --git a/src/normal.zig b/src/normal.zig index 4459ab53..2aea2e54 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -686,10 +686,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .all => return t.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false), }, .multi => |multi| { - if (multi.kind == .keep_primary) { - t.nsel = 0; - return; - } + if (multi.kind == .keep_primary) return t.dropSels(); return t.multiSelAction(text, multi.kind, multi.count); }, // s, S and | answer for the text they are pressed in; `/` searches @@ -922,6 +919,7 @@ test "flat text movement and selection replay need no scratch rows" { pane.body.cur_row = 1024; pane.body.cur_col = 0; pane.body.nsel = 1; + _ = pane.body.reserveSels(); pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; handleNormal(p, &pane.body, .{ .cp = 'l' }); handleNormal(p, &pane.body, .{ .cp = 'j' }); @@ -1021,3 +1019,25 @@ test "tree-sitter selection keys do in a JSON file what hx 25.07.1 does" { }; } } + +test "one cursor holds no room for other ranges; a second range makes it and one again gives it back" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\nalpha beta\n"); + for ("wxe%;gg") |cp| handleNormal(p, &pane.body, .{ .cp = cp }); + try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); + handleNormal(p, &pane.body, .{ .cp = 'C' }); + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + try std.testing.expect(pane.body.sels.len > 0); + handleNormal(p, &pane.body, .{ .cp = 'l' }); // replayed at both, still two + try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); + handleNormal(p, &pane.body, .{ .cp = ',' }); + try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); + handleNormal(p, &pane.body, .{ .cp = 'C' }); + handleNormal(p, &pane.body, .{ .cp = ';' }); + handleNormal(p, &pane.body, .{ .cp = 'x' }); // x at both: still two lines + handleNormal(p, &pane.body, .{ .cp = '_', .alt = true }); // merged to one + try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); + try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); +} diff --git a/src/pardes.zig b/src/pardes.zig index 6b397017..187f3ed3 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4146,6 +4146,8 @@ pub const Pardes = struct { .pdf_gpa = pdf_gpa, .tree_sitter_gpa = tree_sitter_gpa, .opts = opts, + .col_tags = @splat(.{ .what = .column, .gpa = gpa }), + .global_tag = .{ .what = .workspace, .gpa = gpa }, .fs = .{}, .screen_w = opts.cols, .screen_h = opts.rows, @@ -5335,10 +5337,14 @@ pub const Pardes = struct { if (t.what == .tag and t.mode == .insert and tagline.typedIntoName(p, pane, key)) return; // A tag's prefix is read-only: a key whose edit reached into it // changes nothing, not even where the cursor is. - const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel }; + const kept = .{ t.cur_row, t.cur_col, t.vsel, t.msel }; + var kept_sels: [Text.max_selections - 1]Text.SelRange = undefined; + const kept_n = t.nsel; + @memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]); t.refused = false; defer if (t.refused) { - t.cur_row, t.cur_col, t.vsel, t.msel, t.sels, t.nsel = kept; + t.cur_row, t.cur_col, t.vsel, t.msel = kept; + t.restoreSels(kept_sels[0..kept_n]); }; const was = t.mode; switch (t.mode) { diff --git a/test/panes.zig b/test/panes.zig index a56c07bf..181317ca 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -4560,6 +4560,7 @@ const LookResetTests = struct { pane.body.cur_col = 3; pane.body.vsel = .{ .active = true, .explicit = true, .row = 0, .col = 0 }; pane.body.msel = .{ .active = true, .r0 = 0, .r1 = 1 }; + _ = pane.body.reserveSels(); pane.body.sels[0] = .{ .row = 1, .col = 2, .arow = 0, .acol = 1 }; pane.body.nsel = 1; pane.body.select = true; -- cgit v1.3 From 2663a4d1b3170cb2a4dca5e6f1f3535f44b30e44 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:47:26 -0300 Subject: No panic from a notice wider than its band, or from the rest of its class The showcase GUI died in joinNotice on a long shader-error notice: with the tagline narrower than the body, the band hides more columns (skip) than a long message has padding (pad), and `skip..@min(pad, ..)` ran backwards. An audit of draw.zig, Layer.zig, Presentation.zig and animation.zig found the same class elsewhere, all fixed: - a multi-row pane tag or header scrolled for its caret's line sliced a shorter row past its end (paintPaneTag, renderHeaderLayer); - a zero-width column tag kept an earlier frame's viewport, and a column move's clip took it below zero (now saturating, and the early return resets the viewport and caret); - a tag line past 65535 columns overflowed tag_scroll's u16; - a hover left over from a bigger window dashed past the grid; - a border drag over a column that went away, a move preview past a shrunken grid, a column-move rail at zero columns; - Layer.pointAt cast a host's unchecked float metrics (web) to u16; - Text.insertVerticalCursor read past its lines for a cursor whose text changed under it. Regressions: a test of a notice wider than its band through Msg and through setMessage (the Post.zig compile-error path), which panics without the fix; and a monkey over the core at a gui's metrics (random resizes to a cell, long notices, prompts, multi-row tags, clicks, keys), 400 steps in the suite, PARDES_FUZZ_SEED/STEPS for longer runs; 60 seeds x 3000 steps clean. Shared files touched: none of the list (draw.zig, Layer.zig, Text.zig). --- src/Layer.zig | 9 ++-- src/Text.zig | 3 +- src/draw.zig | 137 +++++++++++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 133 insertions(+), 16 deletions(-) (limited to 'src/Text.zig') diff --git a/src/Layer.zig b/src/Layer.zig index e979eab7..a9827304 100644 --- a/src/Layer.zig +++ b/src/Layer.zig @@ -106,9 +106,12 @@ const Point = struct { index: u16, col: u16, metrics: Metrics }; fn pointAt(layer: *const Layer, x: f32, y: f32, body_w: f32, body_h: f32, tagline_w: f32, tagline_h: f32) ?Point { if (layer.rows == 0 or !std.math.isFinite(x) or !std.math.isFinite(y)) return null; // A band's hit is refused outright on metrics no host could have; a - // body's has always been floored to a pixel instead. - if (layer.kind != .body) for ([_]f32{ body_w, body_h, tagline_w, tagline_h }) |metric| - if (!std.math.isFinite(metric) or metric < 1 or metric > std.math.maxInt(u16)) return null; + // body's has always been floored to a pixel instead, and both refuse + // what is no number or past a u16 (a host's floats: web's exports). + for ([_]f32{ body_w, body_h, tagline_w, tagline_h }) |metric| { + if (!std.math.isFinite(metric) or metric > std.math.maxInt(u16)) return null; + if (layer.kind != .body and metric < 1) return null; + } const bw = @max(1, body_w); const bh = @max(1, body_h); const tw = std.math.clamp(tagline_w, 1, bw); diff --git a/src/Text.zig b/src/Text.zig index 43dd8a95..f6780935 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -118,7 +118,8 @@ pub fn fromModalCursor(t: *Text, c: modal.Cursor) void { pub fn insertVerticalCursor(lines: []const []const u8, c: modal.Cursor, down: bool) modal.Cursor { if (lines.len == 0) return c; - const row = if (down) @min(c.row + 1, lines.len - 1) else c.row -| 1; + // 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 ""; diff --git a/src/draw.zig b/src/draw.zig index 3798bf59..0dbf5bae 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -219,13 +219,16 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { if (col > first) s.addRegion(.{ .kind = .guide, .rect = .{ .x = first, .y = d.cur_y, .w = col - first, .h = 1 } }); }; }, - .border_h => |d| if (d.cur_y < s.rows) { + // A column that went away mid-drag has nothing to guide. + .border_h => |d| if (d.cur_y < s.rows and d.col < p.ncol and p.col_x[d.col] < s.cols) { + const end = @min(s.cols, p.col_x[d.col] + p.col_w[d.col]); var col = p.col_x[d.col]; - while (col < p.col_x[d.col] + p.col_w[d.col]) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = p.col_x[d.col], .y = d.cur_y, .w = p.col_w[d.col], .h = 1 } }); + while (col < end) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); + s.addRegion(.{ .kind = .guide, .rect = .{ .x = p.col_x[d.col], .y = d.cur_y, .w = end - p.col_x[d.col], .h = 1 } }); }, .column_move => |d| rail: { const source = layout.columnBySerial(p, d.serial) orelse break :rail; + if (s.cols == 0) break :rail; // Where the column's left edge would land, reordered or not. const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { .stay => break :rail, @@ -258,7 +261,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); }, .move => |d| if (d.cur_x < s.cols) { - if (layout.movePlacement(p, d.id, d.cur_x, d.cur_y)) |placement| { + if (layout.movePlacement(p, d.id, d.cur_x, d.cur_y)) |placement| if (placement.row < s.rows and p.col_x[placement.preview_col] + p.col_w[placement.preview_col] <= s.cols) { var col: u16 = p.col_x[placement.preview_col]; while (col < p.col_x[placement.preview_col] + p.col_w[placement.preview_col]) : (col += 1) { s.set(col, placement.row, "╌", .{ .fg = .{ .rgb = chrome.lineno } }); @@ -266,9 +269,10 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } }); s.addRegion(.{ .kind = .guide, .rect = .{ .x = p.col_x[placement.preview_col], .y = placement.row, .w = p.col_w[placement.preview_col], .h = 1 } }); s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = placement.row, .w = 1, .h = 1 } }); - } + }; }, - .none, .select => if (p.pointer_inside) { + // A hover left over from a bigger window points past this one. + .none, .select => if (p.pointer_inside and p.hover_row < s.rows and p.hover_col < s.cols) { // hover hints on a pane's own trailing edge var c: usize = 0; while (c + 1 < p.ncol) : (c += 1) { @@ -554,7 +558,7 @@ pub fn paintHeaders(p: *Pardes, s: *Surface, arena: std.mem.Allocator) !void { try renderHeaderLayer(p, arena, layer, .column, @intCast(c), region.rect, tagline.columnTag(p, c), top, bg, fg); if (p.col_x[c] < s.cols) joinHeaderRows(s, layer, fg); // Laid out at its full width; only shown short of the rail. - layer.viewport.w -= region.clip; + layer.viewport.w -|= region.clip; }; } @@ -623,7 +627,10 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, layer: *pardes.Layer, kind: TagKind, id: u16, viewport: Rect, text: []const u8, top: usize, bg: [3]u8, fg: [3]u8) !void { _ = arena; if (viewport.w == 0 or viewport.h == 0) { + // No layer, and nothing of an earlier frame's left in it. layer.rows = 0; + layer.viewport = viewport; + layer.cursor = null; return; } var widest: usize = 0; @@ -656,7 +663,8 @@ fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, layer: *pardes.Layer, const shown = modal.lineSlice(text, index + top); var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells[index * columns ..][0..columns] }; surface.fill(0, 0, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - _ = surface.print(0, 0, columns, shown[panes.File.rawAtDisplay(shown, scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); + // The scroll is the caret's line's: a shorter line shows nothing. + _ = surface.print(0, 0, columns, shown[@min(shown.len, panes.File.rawAtDisplay(shown, scroll))..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); // The word under the pointer, a Look or Exec target: on a header even // while it is edited, on a notice, and on the grid's copy of either // (joined from this); not on a column a carried column's pointer is @@ -811,12 +819,13 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) joinCells(s, region.rect.x, region.rect.y, layer.cells[0..layer.cols], skip, chip, .{ .rgb = fg }); // The band's padding before the text is the chip's fill, which carries // no ink of its own (the layer prints it as spaces in the band's ink). - for (skip..@min(pad, skip + chip)) |col| s.at(region.rect.x + @as(u16, @intCast(col - skip)), region.rect.y).style.fg = .default; + // A notice wider than its band has less padding than the band hides. + for (skip..@max(skip, @min(pad, skip + chip))) |col| s.at(region.rect.x + @as(u16, @intCast(col - skip)), region.rect.y).style.fg = .default; if (layer.cursor) |caret| { if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; } // Laid out at its full width; only shown short of the rail. - layer.viewport.w -= region.clip; + layer.viewport.w -|= region.clip; } pub fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { @@ -873,10 +882,12 @@ pub fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pa raw = modal.nextGrapheme(line, raw); scroll = panes.File.rawDisplayCol(line, raw); } - pane.tag_scroll = @intCast(scroll); + // A line past a u16 of columns keeps its caret off the band. + pane.tag_scroll = @intCast(@min(scroll, std.math.maxInt(u16))); } else if (pane.focus != .tag) pane.tag_scroll = 0; for (lines[0..rows], 0..) |line, row| { - const start = panes.File.rawAtDisplay(line, pane.tag_scroll); + // The scroll is the caret's line's: a shorter row shows nothing. + const start = @min(line.len, panes.File.rawAtDisplay(line, pane.tag_scroll)); _ = s.print(tx, tag_y + @as(u16, @intCast(row)), tw, line[start..], tag_style); } const tag = lines[0]; @@ -1064,6 +1075,108 @@ test "the word under the pointer on a notice is lit in its layer and in the grid try std.testing.expect(lit_in_layer); } +test "a notice wider than its band, as a shader's compile error is, draws its end and nothing past it" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 20 }); + defer p.deinit(); + // A gui-shaped core: its tagline is narrower than the body, so a notice's + // band holds more columns than its chip has cells. + p.update(.{ .resize = .{ .cols = 80, .rows = 20, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 } } }); + _ = try p.setTestFile("text\n"); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const long = "Shader /home/someone/shaders/test_shadertoy_invalid.glsl: error: Linking fragment stage: No function definition (body) found: " ** 3; + for ([_][]const u8{ "Msg " ++ long, "" }) |line| { + // The Msg builtin, and the path a failed compile takes (Post.zig). + if (line.len > 0) try std.testing.expect(p.executeBuiltinLine(p.active, line)) else p.setMessage(p.active, long); + p.sync(); + for (0..30) |_| p.update(.tick); + _ = arena.reset(.retain_capacity); + const s = try p.render(arena.allocator()); + const notice = for (s.regionList()) |region| { + if (region.kind == .notice) break region; + } else return error.TestExpectedNotice; + // Text up to the chip's blank last cell, and no padding ink. + const row = s.cells[@as(usize, notice.rect.y) * s.cols ..][notice.rect.x..][0..notice.rect.w]; + try std.testing.expectEqualStrings(" ", row[row.len - 1].grapheme()); + try std.testing.expect(!std.mem.eql(u8, " ", row[row.len - 2].grapheme())); + } +} + +test "a monkey over notices, prompts, tags and tiny panes at a gui's metrics never panics" { + // The snapshot harness runs the tty, whose tagline pitch is the body's, + // so it never reaches what a narrower tagline does to a notice's band: + // this drives the core at a gui's metrics instead. PARDES_FUZZ_STEPS + // runs it longer (the suite's run is short). + const steps: usize = if (std.c.getenv("PARDES_FUZZ_STEPS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 400 else 400; + const seed: u64 = if (std.c.getenv("PARDES_FUZZ_SEED")) |v| std.fmt.parseInt(u64, std.mem.span(v), 10) catch 7 else 7; + var prng = std.Random.DefaultPrng.init(seed); + const random = prng.random(); + const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + _ = try p.setTestFile("fuzz\n\u{754c}\u{754c} wide\n" ** 20); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const words = [_][]const u8{ "error:", "\u{754c}", "x", "Shader /tmp/a.glsl:", "e\u{301}", "\t", "long-" ** 20, " " }; + const commands = [_][]const u8{ "New", "Newcol", "Collapse", "Tagbottom", "ColumnTags", "TreeContext", "Wrap", "Find", "Del", "FocusTint", "Debug" }; + var text: std.ArrayListUnmanaged(u8) = .empty; + defer text.deinit(std.testing.allocator); + for (0..steps) |_| { + switch (random.uintLessThan(u8, 8)) { + // A resize, down to a cell, at a gui's metrics: a tagline no + // wider and no taller than the body's cell, often narrower. + 0 => { + const body_w = random.intRangeAtMost(u16, 6, 12); + const body_h = random.intRangeAtMost(u16, 12, 24); + const cols = if (random.boolean()) random.intRangeAtMost(u16, 1, 12) else random.intRangeAtMost(u16, 13, 140); + const rows = if (random.boolean()) random.intRangeAtMost(u16, 1, 6) else random.intRangeAtMost(u16, 7, 50); + p.update(.{ .resize = .{ .cols = cols, .rows = rows, .row_metrics = .{ .body_w = body_w, .body_h = body_h, .tagline_w = random.intRangeAtMost(u16, 2, body_w), .tagline_h = random.intRangeAtMost(u16, 6, body_h) } } }); + }, + // A message, as long as a compile error or longer. + 1, 2 => { + text.clearRetainingCapacity(); + for (0..random.uintAtMost(usize, 60)) |_| try text.appendSlice(std.testing.allocator, words[random.uintLessThan(usize, words.len)]); + if (random.boolean()) p.setMessage(p.active, text.items) else { + const line = try std.fmt.allocPrint(arena.allocator(), "Msg {s}", .{text.items}); + _ = p.executeBuiltinLine(p.active, line); + } + }, + 3 => _ = p.executeBuiltinLine(p.active, commands[random.uintLessThan(usize, commands.len)]), + // Typing, escaping and entering, into a prompt when one is up. + 4 => p.update(.{ .key = .{ .cp = switch (random.uintLessThan(u8, 9)) { + 0 => pardes.Key.escape, + 1 => pardes.Key.enter, + 2 => 0x754c, + 3 => pardes.Key.end, + 4 => pardes.Key.home, + 5 => pardes.Key.up, + 6 => pardes.Key.down, + else => 'a' + random.uintLessThan(u21, 26), + } } }), + // A tag of several rows. + 5 => if (p.panes[p.active]) |pane| { + text.clearRetainingCapacity(); + for (0..random.uintAtMost(usize, 5)) |_| try text.appendSlice(std.testing.allocator, if (random.boolean()) " Look\nmore \u{754c}" else "\n" ++ "x" ** 150); + if (pane.tag.own) |own| std.testing.allocator.free(own); + pane.tag.own = try std.testing.allocator.dupe(u8, text.items); + }, + // Hover, and clicks: into a tag, a header, a body, a grip. + 6 => { + const col = random.uintAtMost(u16, p.screen_w); + const row = random.uintAtMost(u16, p.screen_h); + if (random.boolean()) p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = col, .row = row } }) else { + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row } }); + } + }, + else => for (0..random.uintAtMost(usize, 20)) |_| p.update(.tick), + } + p.sync(); + _ = arena.reset(.retain_capacity); + const s = try p.render(arena.allocator()); + p.acknowledgePanelPresentation(s.panelTracks()); + } +} + test "a wide glyph cut by a tag's or a notice's edge is joined into the grid as blank, never half drawn" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 41, .rows = 12 }); defer p.deinit(); -- cgit v1.3 From 04b047fb366ea2c595708fb62467f690fce4b9ec Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:56:14 -0300 Subject: Terminal.zig is terminal.zig: a file of functions and no fields takes a namespace's lowercase name The last of the deferred renames, now that the tty and theme agents have landed: panes.terminal at its importers, the alias lines in Text.zig and File.zig and panes.zig's own uses following. dump.zig's Terminal struct, a dump record, is not this. The served sources list and docs/design.typ name the new file. test/perf.zig's references change, so the three perf baselines take its new harness id with their numbers as recorded. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 2 +- src/File.zig | 6 +- src/Terminal.zig | 2670 ------------------------------- src/Text.zig | 18 +- src/body_layer.zig | 16 +- src/builtins.zig | 2 +- src/draw.zig | 8 +- src/dump.zig | 4 +- src/edit.zig | 26 +- src/exec.zig | 34 +- src/fs.zig | 2 +- src/host_io.zig | 2 +- src/layout.zig | 4 +- src/mouse.zig | 6 +- src/ninep/ctl.zig | 2 +- src/ninep/pane.zig | 4 +- src/ninep/pty.zig | 24 +- src/ninep/screen.zig | 4 +- src/panes.zig | 20 +- src/pardes.zig | 106 +- src/terminal.zig | 2670 +++++++++++++++++++++++++++++++ src/tty/tty.zig | 2 +- test/mode.zig | 2 +- test/panes.zig | 60 +- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 16 +- 28 files changed, 2858 insertions(+), 2858 deletions(-) delete mode 100644 src/Terminal.zig create mode 100644 src/terminal.zig (limited to 'src/Text.zig') diff --git a/docs/design.typ b/docs/design.typ index ebbf213a..ec9bd5c4 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -526,7 +526,7 @@ verbatim by right-click and the delayed hover preview; that policy stays beside input because it also observes live pane selections and wrapped grid coordinates. Each pane kind keeps its storage and operations together in its own file -(`File.zig`, `Terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the +(`File.zig`, `terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the image pane in `image.zig`), reached through `panes.zig` beside `Pane`. `layout.zig` owns placement and presentation state. `pardes.zig` handles input and cross-pane state directly, without a pane vtable; the rest of the editor diff --git a/src/File.zig b/src/File.zig index c4040863..8babb27d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -17,7 +17,7 @@ const locations = @import("locations.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; -const Terminal = panes.Terminal; +const terminal = panes.terminal; const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; @@ -782,7 +782,7 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); const path_copy = try p.gpa.dupe(u8, path); errdefer p.gpa.free(path_copy); - const pane = try Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try terminal.createDoc(p.gpa, p.screen_w, p.screen_h); errdefer p.gpa.destroy(pane); const history = try History.create(p.gpa); errdefer p.gpa.destroy(history); @@ -1239,7 +1239,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) pub fn drawGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { const prefix_width = gutterWidth(pane); const goff = pane.scroll(); - const gcur = Terminal.gridCursor(pane); + const gcur = terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); diff --git a/src/Terminal.zig b/src/Terminal.zig deleted file mode 100644 index c99a92a6..00000000 --- a/src/Terminal.zig +++ /dev/null @@ -1,2670 +0,0 @@ -//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay -//! typed over shell rows, and the Filter that recolours output to the theme. -const panes = @import("panes.zig"); -const std = @import("std"); -const pardes = @import("pardes.zig"); -const config = @import("config.zig"); -const Pardes = pardes.Pardes; -const Surface = pardes.Surface; -const modal = @import("modal.zig"); -const tracy = @import("tracy.zig"); -const dump = @import("dump.zig"); -const Key = pardes.Key; -const Pane = panes.Pane; -const EditText = panes.EditText; -const File = panes.File; - -pub const enabled = pardes.terminal_panes; -const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; - -pub const history_max = if (enabled) 64 else 8; - -pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; -pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; - -/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). -pub const prompt_aid = "pardes"; - -/// ghostty's handler, plus where the shell is in its command cycle as -/// its OSC 133 marks tell it: ghostty parses D's exit status and drops -/// it, and /pane//pty/run waits on exactly that. Only marks carrying -/// pardes's own `aid` move it, so fish's native marks, a nested shell's -/// and a stray `133;D` in some file being printed all pass it by. -pub const MarkedHandler = if (enabled) struct { - inner: ghostty_vt.TerminalStream.Handler, - phase: enum { none, prompt, input, running } = .none, - /// Counts commands started (C at the input phase). - started: u32 = 0, - /// Counts prompts drawn (B), so a line the shell refused without - /// running (a fish syntax error: no C, no D, a new prompt) shows. - prompts: u32 = 0, - /// D marks outside a running command: the shell handled a line - /// without starting it (bash on a syntax error prints no C). - declined: u32 = 0, - /// The newest prompt continues an unfinished line (bash's PS2, marked - /// `k=c`): the shell still holds the start of the command. - continuation: bool = false, - /// Where the newest command's output began (its C) and ended (its - /// D) on the primary screen, pinned so scrolling keeps them. - out_start: ?*ghostty_vt.Pin = null, - out_end: ?*ghostty_vt.Pin = null, - /// The running command's output was erased under it -- a clear, ED 3, - /// a reset -- so the pins no longer span what it printed: ED 3 moves - /// a pin to the next page without flagging it `garbage` - /// (PageList.erasePage). - lost: bool = false, - - /// The newest command to end: which one, and its status if given. - finished: ?struct { seq: u32, status: ?i32 } = null, - - const Action = ghostty_vt.TerminalStream.Action; - - /// Move one of the output pins to the cursor. Only the primary screen - /// is pinned: a command's own full-screen display is not its output. - fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { - const screen = self.inner.terminal.screens.get(.primary) orelse return; - if (slot.*) |old| screen.pages.untrackPin(old); - slot.* = null; - if (!now or self.inner.terminal.screens.active_key != .primary) return; - slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; - } - - pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { - if (comptime action == .semantic_prompt) mark: { - const aid = value.readOption(.aid) orelse break :mark; - if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; - switch (value.action) { - .fresh_line_new_prompt => { - self.phase = .prompt; - self.continuation = value.readOption(.prompt_kind) == .continuation; - }, - .end_prompt_start_input => { - self.phase = .input; - self.prompts +%= 1; - }, - // bash's DEBUG trap also fires on its own PROMPT_COMMAND, - // outside the input phase; only a C that ends input counts - .end_input_start_output => if (self.phase == .input) { - self.phase = .running; - self.started +%= 1; - self.lost = false; - self.pinCursor(&self.out_start, true); - self.pinCursor(&self.out_end, false); - }, - .end_command => if (self.phase == .running) { - self.phase = .none; - self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; - self.pinCursor(&self.out_end, true); - } else { - self.declined +%= 1; - }, - else => {}, - } - } - if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { - if (self.phase == .running) self.lost = true; - } - self.inner.vt(action, value); - } - - pub fn deinit(self: *@This()) void { - self.inner.deinit(); - } -} else void; - -pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, -}; - -pub const State = struct { - vt: VtSlot, - stream: StreamSlot, - replay: Replay, - reply: [256]u8 = undefined, - reply_len: u16 = 0, -}; - -const GColor = ghostty_vt.color; - -const FilterPaletteKey = struct { - bg: GColor.RGB, - fg: GColor.RGB, - base: [16]GColor.RGB, -}; - -pub const FilterPalette = if (enabled) LivePalette else struct {}; - -const LivePalette = struct { - key: ?FilterPaletteKey = null, - colors: GColor.Palette = GColor.default, - - fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { - const bg = asGhostRgb(theme.bg orelse theme.tag_bg); - const fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var base: [16]GColor.RGB = undefined; - if (theme.palette) |palette| { - for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); - } else { - const synthesized = [16][3]u8{ - theme.bg orelse theme.tag_bg, - theme.kw, - theme.str, - theme.num, - theme.box, - theme.sel_bg, - theme.comment, - theme.fg orelse theme.tag_fg, - theme.lineno, - theme.kw, - theme.str, - theme.num, - theme.scroll_thumb, - theme.sel_fg, - theme.tag_fg, - theme.fg orelse theme.tag_fg, - }; - for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); - } - - const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; - - var seed = GColor.default; - for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); - self.key = key; - return &self.colors; - } -}; - -fn asGhostRgb(rgb: [3]u8) GColor.RGB { - return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; -} - -fn asPardesColor(rgb: GColor.RGB) pardes.Color { - return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; -} - -/// 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: panes.Text.CharSel, -}; - -pub const PendingCommand = struct { - bytes: []u8 = &.{}, - wait: enum { none, spawn, input } = .none, -}; - -pub fn armShellSpawn(pane: *Pane) void { - if (comptime !enabled) return; - std.debug.assert(pane.pending_command.bytes.len == 0); - pane.pending_command.wait = .spawn; -} - -/// Remembers a line pardes types into this terminal as the command it -/// started, for Kill: it runs from the shell's next C mark to its D. -/// ponytail: of several lines queued for a shell not up yet, only the last -/// is remembered, as the first of them. -pub fn noteCommand(pane: *Pane, line: []const u8) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; - var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; - sent.len = @intCast(@min(word.len, sent.word.len)); - @memcpy(sent.word[0..sent.len], word[0..sent.len]); - pane.sent_command = sent; -} - -/// Whether the command pardes last typed here is running now. -pub fn commandRunning(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const sent = pane.sent_command orelse return false; - const marks = &state.stream.handler; - return marks.phase == .running and marks.started == sent.seq; -} - -pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { - if (pane.pending_command.wait == .none) return false; - const old_len = pane.pending_command.bytes.len; - const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); - const bytes = if (old_len == 0) - try pane.gpa.alloc(u8, new_len) - else - try pane.gpa.realloc(pane.pending_command.bytes, new_len); - @memcpy(bytes[old_len..][0..command.len], command); - bytes[new_len - 1] = '\r'; - pane.pending_command.bytes = bytes; - pane.greet = false; - return true; -} - -pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { - const pane = p.panes[id] orelse return; - if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; - if (prompt_marks) { - pane.pending_command.wait = .input; - releasePendingCommand(p, id, pane, false); - } else { - pane.greet = false; - releasePendingCommand(p, id, pane, true); - } -} - -pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { - if (pane.pending_command.wait == .input) - releasePendingCommand(p, id, pane, promptInputReady(pane)); -} - -fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { - if (!ready) return; - const bytes = pane.pending_command.bytes; - pane.pending_command = .{}; - if (bytes.len > 0) { - p.emitWrite(id, bytes); - pane.gpa.free(bytes); - } -} - -pub fn deinitPendingCommand(pane: *Pane) void { - if (pane.pending_command.bytes.len > 0) - pane.gpa.free(pane.pending_command.bytes); - pane.pending_command = .{}; -} - -pub fn terminalIo() std.Io { - return if (comptime !pardes.hosted) - std.Io.failing - else - std.Io.Threaded.global_single_threaded.io(); -} - -/// The three numbers ghostty's scrollbar reports; all zero without an emulator. -pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; - -pub fn scrollbar(pane: *const Pane) Scrollbar { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const sb = state.vt.screens.active.pages.scrollbar(); - return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; -} - -/// The emulator's viewport offset, in SHELL rows: the top of what it shows. -pub fn gridOffset(pane: *const Pane) i32 { - return @intCast(scrollbar(pane).offset); -} - -/// Where the emulator itself puts the cursor, in active-area cells — the origin -/// without one, which is where an empty pane's cursor belongs anyway. -pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; - -pub fn gridCursor(pane: *const Pane) GridCursor { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const cur = state.vt.screens.active.cursor; - return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; -} - -pub fn visibleCursor(pane: *const Pane) ?GridCursor { - if (comptime !enabled) return null; - const state = pane.terminal orelse return null; - if (!state.vt.modes.get(.cursor_visible)) return null; - const cur = state.vt.screens.active.cursor; - const sb = scrollbar(pane); - const row = sb.total - sb.len + cur.y; - if (row < sb.offset or row - sb.offset >= sb.len) return null; - return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; -} - -/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). -pub fn scrollGrid(pane: *Pane, delta: i32) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.{ .delta_row = delta }); -} - -/// Is the viewport already showing the last row of output? -pub fn atBottom(pane: *const Pane) bool { - if (comptime !enabled) return true; - const sb = scrollbar(pane); - return sb.offset + sb.len >= sb.total; -} - -/// Snap the viewport back onto live output. -pub fn followOutput(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.active); -} - -/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping -/// a scrollback; the next resize retries with the same numbers. -pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - if (cols != pane.cols) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; -} - -/// DECSET 2004: the program wants its pastes bracketed. -pub fn bracketedPaste(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.bracketed_paste); -} - -/// The program tracks the mouse itself, so a click in its body is its event. -pub fn reportsMouse(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const m = &state.vt.modes; - return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); -} - -/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. -pub fn mouseFormatSgr(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.mouse_format_sgr); -} - -/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body -/// reads and `Save` writes out. Logical lines: rows the terminal wrapped -/// are joined again (ghostty's wrap flags, as pty/run's output is), and -/// the last line ends with a newline. -pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { - if (comptime !enabled) return &.{}; - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - try writeScreenText(pane, &out.writer); - return out.toOwnedSlice(); -} - -fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - const br = screen.pages.getBottomRight(.screen) orelse return; - var both: TeeWriter = .{ .a = w }; - try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); - if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); -} - -/// Passes bytes through, remembering how many and the last one. -const TeeWriter = struct { - a: *std.Io.Writer, - count: usize = 0, - final: u8 = 0, - writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, - - fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); - var n: usize = 0; - for (data[0 .. data.len - 1]) |bytes| { - try t.a.writeAll(bytes); - t.note(bytes); - n += bytes.len; - } - const pattern = data[data.len - 1]; - for (0..splat) |_| { - try t.a.writeAll(pattern); - t.note(pattern); - n += pattern.len; - } - return n; - } - - fn note(t: *TeeWriter, bytes: []const u8) void { - if (bytes.len == 0) return; - t.count += bytes.len; - t.final = bytes[bytes.len - 1]; - } -}; - -/// How long `screenTextAlloc` would be, counted without keeping it: the -/// length a terminal's body reads as, which its ctl line reports. -pub fn screenTextLen(pane: *Pane) usize { - if (comptime !enabled) return 0; - var buf: [256]u8 = undefined; - var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &counting.writer) catch return 0; - return @intCast(counting.fullCount()); -} - -/// Release the emulator's heap. The Pane allocation itself is the core's. -pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.stream.deinit(); - state.vt.deinit(gpa); - gpa.destroy(state); - pane.terminal = null; -} - -/// Allocate the live emulator half of a terminal pane. Slot ownership, serial -/// assignment, and spawn effects remain core lifecycle invariants. -pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try createDoc(gpa, cols, rows); - errdefer gpa.destroy(pane); - if (comptime !enabled) return pane; - const state = try gpa.create(State); - errdefer gpa.destroy(state); - state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ - .cols = cols, - .rows = rows, - .max_scrollback = 16 * 1024 * 1024, - }); - state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); - state.replay.head = 0; - state.replay.len = 0; - state.reply_len = 0; - state.stream.handler.inner.effects.write_pty = ptyReport; - state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; - pane.terminal = state; - pane.tty_filter = true; - return pane; -} - -pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try gpa.create(Pane); - pane.* = .{ - .gpa = gpa, - .cols = cols, - .rows = rows, - }; - return pane; -} - -/// Where a restored terminal's history ends and its new shell begins. -pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; - -/// Rebuild a dump's terminal emulator from its recorded output. `live`: a -/// shell will be spawned into it, so the history is marked off from what -/// that shell prints and the pane waits for it like any new terminal. -/// Registration and tag/cwd policy stay with the core; raw VT replay and -/// viewport restoration belong here. -pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { - const terminal = src.terminal.?; - if (comptime !enabled) { - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - errdefer p.gpa.destroy(pane); - if (terminal.stream.len > 0) - pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; - return pane; - } - // An older dump's raw output tail cannot come back live: cut off mid - // redraw, or written at sizes the pane no longer has, it replays as - // garbage. Its rendered text can. - const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; - const bytes = if (legacy_text) - try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") - else if (terminal.stream_b64.len > 0) - try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) - else - &.{}; - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - if (live) { - if (bytes.len > 0) { - ingest(pane, bytes); - ingest(pane, restored_banner); - } - followOutput(pane); - // A view left scrolled back stays on what it was showing: the - // banner's line breaks scrolled a full screen by that many more. - if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); - armShellSpawn(pane); - } else if (bytes.len > 0) { - ingest(pane, bytes); - followOutput(pane); - if (src.scroll > 0) - scrollGrid(pane, -@as(i32, @intCast(src.scroll))); - } - return pane; -} - -/// Feed the emulator and retain the bounded suffix a dump can replay. Live -/// output and restoration share this byte path, then apply different views. -fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); -} - -/// Return the replay ring in chronological order. Wrapped records are copied -/// into `allocator`; contiguous records remain a borrowed slice of the pane. -fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - return out; -} - -test "replay ownership is terminal-only and construction rolls back on allocation failure" { - const Case = struct { - fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqual(terminal and enabled, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "document construction allocates only the pane and has inert terminal defaults" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); - const allocator = failing.allocator(); - const pane = try createDoc(allocator, 40, 12); - defer allocator.destroy(pane); - defer deinitEmulator(pane, allocator); - try std.testing.expect(pane.terminal == null); - try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); - try std.testing.expectEqual(@as(usize, 0), failing.resize_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expect(!bracketedPaste(pane)); - try std.testing.expect(!reportsMouse(pane)); - try std.testing.expect(!mouseFormatSgr(pane)); - try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, allocator, 80, 24); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); - try std.testing.expectEqualStrings("", try replayBytes(pane, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - if (comptime !enabled) return error.SkipZigTest; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var replies: usize = 0; - while (p.nextEffect()) |effect| { - if (effect != .write) continue; - try std.testing.expectEqual(@as(u8, 0), effect.write.pane); - try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - replies += 1; - } - try std.testing.expectEqual(@as(usize, 1), replies); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); -} - -test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); -} - -test "replay restores terminal cells from the retained stream" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); - defer gpa.free(encoded); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = pane.cols, - .rows = pane.rows, - .terminal = .{ .stream_b64 = encoded }, - }, false); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - const before = try screenTextAlloc(pane, gpa); - defer gpa.free(before); - const after = try screenTextAlloc(restored, gpa); - defer gpa.free(after); - try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime !enabled or pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try p.newCommand(cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try dump.dumpState(p); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - try std.testing.expectEqualStrings("make test", again.command.?); - try std.testing.expect(again.command_done); - try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime !enabled or pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "old output\r\n$ ls\r\n"); - try pane.setOwnedCwd("/tmp"); - pane.shell = try gpa.dupe(u8, "bash"); // `Tty bash`: it comes back as bash - try dump.dumpState(p); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - try std.testing.expectEqualStrings("bash", again.shell.?); - try std.testing.expect(again.command == null); - try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; - const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; - try std.testing.expect(old_at < mark_at); -} - -test "an older dump comes back live from its rendered text, not its raw output tail" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - // A tail cut mid-redraw: relative moves from a cursor it never set. - const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); - defer gpa.free(tail); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = 40, - .rows = 12, - .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, - }, true); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - defer deinitPendingCommand(restored); - const text = try screenTextAlloc(restored, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); -} - -/// Record and parse one live pty read, invalidate its motion surface, and -/// follow it only when the body (possibly parked under a tag edit) is raw. -pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { - // There are no pty reads at all without an emulator to parse them into. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or - pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or - pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; - // Sticky bottom, as every other terminal does it: output drags the - // viewport down only when the viewport was already on the last row, so - // a reader scrolled back into the scrollback stays where they scrolled. - const at_bottom = atBottom(pane); - if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); - p.shell_rows.markStale(pane); - if (pane.body.mode == .tty and at_bottom) followOutput(pane); -} - -const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; -const PositionPin = struct { - target: *i32, - row: RowPin, - overlay: ?*EditBuffer, - edit_row: ?i32 = null, -}; - -fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { - if (row < 0) return .{ .offset = row }; - const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); - var left = pages.total_rows - 1 - bounded; - var node = pages.pages.last.?; - while (left >= node.rows()) { - left -= node.rows(); - node = node.prev.?; - } - const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { - failed.* = true; - return .{}; - }; - return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; -} - -fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { - const pin = row.pin orelse return row.offset; - const alive = pages orelse return 0; - if (pin.garbage) return 0; - var after: usize = 0; - var node = alive.pages.last; - while (node) |item| : (node = item.prev) { - if (item == pin.node) - return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; - after += item.rows(); - } - return 0; -} - -fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { - var grid = target.*; - if (overlay) |edit| { - const lines: i32 = @intCast(modal.lineCount(edit.text)); - if (grid >= edit.row and grid < edit.row +| lines) - return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; - if (grid > edit.row) grid = grid -| lines +| edit.rows; - } - return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; -} - -fn pointerRowCount(pane: *const Pane) usize { - var count: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - count += rows.len; - }; - return count; -} - -fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { - const screens = &pane.terminal.?.vt.screens; - const key = screens.active_key; - const generation = screens.generation(key); - const pages = &screens.active.pages; - const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; - var groups: [history_max * 2 + 1]Group = undefined; - groups[0] = .{ - .overlay = if (pane.ovl) |*overlay| overlay else null, - .cursor = &pane.body.cur_row, - .selection = &pane.body.vsel, - }; - var ngroups: usize = 1; - for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { - for (history) |*snapshot| { - groups[ngroups] = .{ - .overlay = if (snapshot.ovl) |*overlay| overlay else null, - .cursor = &snapshot.cur_row, - .selection = &snapshot.vsel, - }; - ngroups += 1; - } - } - const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; - var spans: [groups.len]Span = undefined; - var nspans: usize = 0; - var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; - var npositions: usize = 0; - var failed = false; - for (groups[0..ngroups]) |group| { - if (group.overlay) |overlay| { - spans[nspans] = .{ - .overlay = overlay, - .start = trackRow(pages, overlay.row, &failed), - .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), - }; - nspans += 1; - } - positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); - npositions += 1; - if (group.selection.active) { - positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); - npositions += 1; - } - } - const overlay = groups[0].overlay; - var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; - var nextra: usize = 0; - if (pane.body.msel.active) { - extra[nextra] = &pane.body.msel.r0; - extra[nextra + 1] = &pane.body.msel.r1; - nextra += 2; - } - for (pane.body.sels[0..pane.body.nsel]) |*selection| { - extra[nextra] = &selection.row; - extra[nextra + 1] = &selection.arow; - nextra += 2; - } - if (pane.body.last_edit) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - if (pane.look_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - for (extra[0..nextra]) |target| { - positions[npositions] = trackPosition(pages, target, overlay, &failed); - npositions += 1; - } - const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; - defer if (pointer_positions) |pins| pane.gpa.free(pins); - if (pointer_positions) |pins| { - var index: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - for (rows) |*row| { - pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); - index += 1; - } - }; - } else failed = true; - ingest(pane, bytes); - // RIS can destroy the alternate screen and every pin it owned. - const alive = if (screens.generation(key) == generation) pages else null; - var moved = false; - var pointer_rows_lost = alive == null or pointer_positions == null; - if (pointer_positions) |pins| for (pins) |position| { - if (alive != null) if (position.row.pin) |pin| { - if (pin.garbage) pointer_rows_lost = true; - }; - }; - for (spans[0..nspans]) |span| { - const start = pinnedRow(alive, span.start); - const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); - moved = moved or start != span.overlay.row or rows != span.overlay.rows; - span.overlay.row = start; - span.overlay.rows = rows; - if (alive) |owner| { - if (span.start.pin) |pin| owner.untrackPin(pin); - if (span.end.pin) |pin| owner.untrackPin(pin); - } - } - for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { - var row = pinnedRow(alive, position.row); - if (position.overlay) |edit| { - if (position.edit_row) |relative| { - row = edit.row +| relative; - } else if (row > edit.row) { - row = if (row < edit.row +| edit.rows) - edit.row - else - row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); - } - } - moved = moved or row != position.target.*; - position.target.* = row; - if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); - }; - if (pointer_rows_lost) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. - if (failed) { - const message = "terminal edit position reset: out of memory"; - @memcpy(pane.msg[0..message.len], message); - pane.msg_len = message.len; - } -} - -test "raw terminal output needs no position tracking allocations" { - if (comptime !enabled) return error.SkipZigTest; - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - feedOutput(p, pane, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - feedOutput(p, pane, " output"); - try std.testing.expectEqual(allocations, failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); -} - -/// A full-screen program has the emulator on its alternate screen. -pub fn onAlternateScreen(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .alternate; -} - -/// Whether a new terminal's greeting may be typed now: only at the shell's -/// first prompt (pardes's own marks: no command started; a prompt drawn -/// again for a resize is the same first prompt), with nothing -/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or -/// been typed first, and an `ls` then would go into it. A shell pardes -/// cannot mark has no first prompt to find, and is never greeted. -pub fn greeting(pane: *const Pane) enum { wait, now, never } { - if (comptime !enabled) return .never; - if (pane.fs.unmarked) return .never; - // Text typed into the edit buffer that stands in for the prompt row. - if (pane.ovl) |o| if (o.text.len > 0) return .never; - const state = pane.terminal orelse return .wait; - const marks = &state.stream.handler; - // (Not `declined`: bash's first prompt comes after a D of its own.) - if (marks.started > 0) return .never; - // At a prompt's input (ghostty's semantic marks, pardes's or the - // shell's own), before any command pardes's marks saw run. - if (!promptInputReady(pane)) return .wait; - return if (promptInputEmpty(pane)) .now else .never; -} - -pub fn promptInputReady(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key != .alternate and - state.vt.screens.active.cursor.semantic_content == .input; -} - -pub const CommandOutput = struct { - /// Owned by the caller. - text: [:0]const u8, - /// Whether `text` starts where the command did. It does not when that - /// start is not there to read: cut off by `max_rows`, scrolled out of - /// the history (ghostty moved the pin to the oldest row it kept and - /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or - /// never pinned (a C or D that came on the alternate screen). - whole: bool, -}; - -/// What the newest finished command printed: the screen text between its -/// C and D marks, read from at most `max_rows` rows above its end, so a -/// command that printed the whole history costs no more than its tail. -/// The shell exited in the middle of a command (its `exit 3`): no end mark -/// will come, so the command's output ends where the cursor is. -pub fn endOutputHere(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const marks = &state.stream.handler; - if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); -} - -pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { - // Unless there is text to read, whether the nothing it printed is the - // whole of it. - const whole = if (comptime enabled) printed: { - const state = pane.terminal orelse break :printed true; - const marks = &state.stream.handler; - const start = marks.out_start orelse break :printed false; - const end = marks.out_end orelse break :printed false; - const screen = state.vt.screens.get(.primary) orelse break :printed false; - if (end.garbage) break :printed false; - var whole = !marks.lost and !start.garbage; - // D is where the next prompt begins: the output ends a cell before. - const last = end.leftWrap(1) orelse break :printed whole; - if (start.eql(end.*) or last.before(start.*)) break :printed whole; - var from = start.*; - if (last.up(max_rows)) |floor| if (from.before(floor)) { - from = floor; - from.x = 0; - whole = false; - }; - return .{ - .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), - .whole = whole, - }; - } else true; - return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; -} - -/// At a prompt with nothing typed on its line: no input left of the -/// cursor and none under it (text typed and then Ctrl-A'd starts at the -/// cursor). Nothing further right counts: that is where fish draws a -/// right prompt, and fish suggests nothing on an empty line. -pub fn promptInputEmpty(pane: *const Pane) bool { - if (comptime !enabled) return false; - if (!promptInputReady(pane)) return false; - const cursor = &pane.terminal.?.vt.screens.active.cursor; - const row = cursor.page_pin.cells(.all); - for (row[0..@min(cursor.x + 1, row.len)]) |cell| - if (cell.semantic_content == .input and !cell.isEmpty()) return false; - return true; -} - -/// Encode one key for the program that owns a raw terminal and queue its pty -/// write, respecting the application's keyboard protocol and terminal modes. -pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - if (comptime enabled) { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; - const input = ghostty_vt.input; - const function_keys = comptime keys: { - var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; - for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); - break :keys keys; - }; - const physical: input.Key = switch (key.cp) { - Key.enter => .enter, - Key.backspace => .backspace, - Key.tab => .tab, - Key.escape => .escape, - Key.up => .arrow_up, - Key.down => .arrow_down, - Key.left => .arrow_left, - Key.right => .arrow_right, - Key.home => .home, - Key.end => .end, - Key.page_up => .page_up, - Key.page_down => .page_down, - Key.delete => .delete, - Key.insert => .insert, - Key.print_screen => .print_screen, - Key.scroll_lock => .scroll_lock, - Key.pause => .pause, - Key.menu => .context_menu, - Key.f1...Key.f25 => function_keys[key.cp - Key.f1], - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, - }; - var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; - // A key with no text of its own types its code point only when that - // is a character: the kitty keyboard protocol numbers function and - // modifier keys in the private use area (F3 is U+E016), and a shell - // was typed those as junk. - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) - utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] - else - ""; - var buffer: [256]u8 = undefined; - var writer = std.Io.Writer.fixed(&buffer); - input.encodeKey(&writer, .{ - .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, - .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, - }, options: { - var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); - // fromTerminal cannot know this one and says so, defaulting to - // "option is not alt" — right for an app that lets macOS do the - // unicode translation and hands the encoder the composed text. - // Every pardes shell resolves the modifier itself and hands the - // core the BASE key with the alt bit and no text at all (see - // PardesView.keyDown, and app.mjs doing the same with the same - // two bits), so by the time this runs alt already means alt. - // Left at the default, a macOS build drops the ESC prefix on - // the floor and forwards Alt-n to the child as a bare `n`. - opts.macos_option_as_alt = .true; - break :options opts; - }) catch return; - if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); - return; - } - var control: [1]u8 = undefined; - const bytes: ?[]const u8 = blk: { - if (key.ctrl) { - if (key.cp >= 'a' and key.cp <= 'z') { - control[0] = @intCast(key.cp - 0x60); - break :blk control[0..1]; - } - // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. - if (key.cp >= '@' and key.cp <= '_') { - control[0] = @intCast(key.cp - 0x40); - break :blk control[0..1]; - } - } - if (key.text.len > 0) break :blk key.text; - break :blk switch (key.cp) { - Key.enter => "\r", - Key.backspace => "\x7f", - Key.tab => "\t", - Key.escape => "\x1b", - Key.up => "\x1b[A", - Key.down => "\x1b[B", - Key.right => "\x1b[C", - Key.left => "\x1b[D", - Key.delete => "\x1b[3~", - else => null, - }; - }; - if (bytes) |encoded| - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); -} - -pub fn enterTty(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; - if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { - const screen = pane.terminal.?.vt.screens.active; - const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.body.cur_row) - goff; - if (vp_row < 0) break :handoff; - - var grid_col: i32 = @max(0, pane.body.cur_col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { - if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { - .cut => |cols| grid_col += @intCast(cols), - .keep, .blank => {}, - }; - } - const click_pin = screen.pages.pin(.{ - .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, - }) orelse break :handoff; - const cursor_pin = screen.cursor.page_pin.*; - var prompts = cursor_pin.promptIterator(.left_up, null); - const prompt_pin = prompts.next() orelse break :handoff; - if (click_pin.before(prompt_pin)) break :handoff; - const moves = screen.promptClickMove(click_pin); - for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); - for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); - }; - - pane.body.mode = .tty; - followOutput(pane); // entering raw mode is a request for the live shell - pane.body.msel.active = false; - pane.body.vsel.active = false; - pane.body.nsel = 0; - // The raw renderer follows the live cursor. A captured mouse selection - // keeps its modal endpoint for the next return to editor mode. - pane.body.cur_pinned = selected; - pane.body.select = false; - pane.body.restore_cursor = false; - pane.body.sticky_col = -1; - pane.body.normal.clear(); -} - -// Returned slices remain valid until the next cache rebuild or reset. -pub const RowsCache = struct { - /// whose grid this describes; null = the slot is free - pane: ?*const Pane = null, - /// the rows joined by '\n' — `flatSurface` hands this back verbatim - /// instead of rebuilding the join on every keystroke - text: []const u8 = &.{}, - /// slices INTO `text`, absolute grid rows from 0 - rows: [][]const u8 = &.{}, - /// `text` is a prefix of this: blanking a prompt row shortens the join, - /// and the slack is not worth a second allocation to reclaim - text_alloc: []u8 = &.{}, - stale: bool = false, - - pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); - c.* = .{}; - } - - /// Free a stale entry. Called at the top of `update`, and nowhere else. - pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.stale) c.reset(gpa); - } - - /// `pane`'s grid moved: the entry no longer describes it. - pub fn markStale(c: *RowsCache, pane: *const Pane) void { - if (c.pane == pane) c.stale = true; - } - - pub fn dropPane(c: *RowsCache, pane: *const Pane) void { - if (c.pane != pane) return; - c.pane = null; - c.stale = true; - } -}; - -const Rows = struct { - text_alloc: []u8, - text: []const u8, - rows: [][]const u8, -}; - -const empty_grid = [1][]const u8{""}; - -/// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. -const PromptCut = union(enum) { - /// show the row exactly as ghostty dumped it - keep, - /// show nothing at all - blank, - /// drop this many leading COLUMNS — the prompt — and keep the rest, which - /// is what was typed at it - cut: usize, -}; - -fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; - const cells = pin.cells(.all); - var cols: usize = 0; - while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; - // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or - // a repaint that has moved on. Nothing here is the prompt, so hide nothing. - if (cols == 0) return .keep; - // ...and all prompt, nothing typed yet: the row is chrome end to end. - if (cols >= cells.len) return .blank; - return .{ .cut = cols }; -} - -pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { - if (comptime !enabled) return 0; - if (row < 0) return 0; - const state = pane.terminal orelse return 0; - const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; - if (pin.rowAndCell().row.semantic_prompt == .none) return 0; - return switch (promptCut(pin)) { - .keep => 0, - .blank => raw.len, - .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), - }; -} - -fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { - const cols = switch (promptCut(pin)) { - .keep => return raw, - .blank => return "", - .cut => |n| n, - }; - const cells = pin.cells(.all); - var at: usize = 0; - var col: usize = 0; - while (col < cols and at < raw.len) { - const cell = &cells[col]; - at = @min(raw.len, at + dumpedBytes(pin, cell)); - // the tail cell of a wide glyph spells nothing of its own - col += if (cell.wide == .wide) @as(usize, 2) else 1; - } - return std.mem.trimEnd(u8, raw[at..], " \t"); -} - -fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { - switch (cell.wide) { - .spacer_head, .spacer_tail => return 0, - .narrow, .wide => {}, - } - var n: usize = switch (cell.content_tag) { - .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( - cell.codepoint(), - ) catch 1, - // A cell carrying only a colour still spells one blank in the dump. - else => 1, - }; - if (cell.content_tag == .codepoint_grapheme) { - if (pin.grapheme(cell)) |extra| for (extra) |cp| { - n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; - }; - } - return n; -} - -pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (comptime !enabled) return &empty_grid; - if (pane.terminal == null) return &empty_grid; - const c = &p.shell_rows; - if (!c.stale and c.pane == pane) return c.rows; - if (c.pane != null) { - c.stale = true; - return (try buildRows(p.scratch.allocator(), p, pane)).rows; - } - const built = try buildRows(p.gpa, p, pane); - c.* = .{ - .pane = pane, - .text = built.text, - .rows = built.rows, - .text_alloc = built.text_alloc, - }; - return c.rows; -} - -/// The full modal motion surface: shell history with the live edit overlay -/// spliced into the rows it covers. -pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { - const rows = try shellRows(p, pane); - if (pane.ovl == null) return rows; - var last = rows.len; - if (pane.ovl) |overlay| - last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); - var count = last; - if (pane.ovl) |overlay| { - if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) - count = count - @min( - @as(usize, @intCast(overlay.rows)), - last - @as(usize, @intCast(overlay.row)), - ) + @max(1, modal.lineCount(overlay.text)); - } - const lines = try p.scratch.allocator().alloc([]const u8, count); - var n: usize = 0; - var grid_row: usize = 0; - while (grid_row < last) : (grid_row += 1) { - if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { - var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); - while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; - grid_row += @intCast(overlay.rows - 1); - continue; - }; - lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; - n += 1; - } - return lines[0..n]; -} - -/// Flatten `cursorLines` without rebuilding the common cached/no-overlay -/// case. Scratch-owned when a join is required. -pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { - const cache = &p.shell_rows; - if (!cache.stale and cache.pane == pane and - lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; - var total: usize = if (lines.len > 0) lines.len - 1 else 0; - for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); - var at: usize = 0; - for (lines, 0..) |line, i| { - if (i > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..line.len], line); - at += line.len; - } - return text; -} - -/// Materialize or extend the terminal edit overlay with one exact allocation. -/// Row slices are scratch-owned/borrowed; only the joined text is installed. -pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { - const want_lo = @max(0, @min(lo, hi)); - const want_hi = @max(want_lo, @max(lo, hi)); - const fresh = pane.ovl == null; - const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; - const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); - const up = old.row - want_lo; - const down = want_hi - (old.row + lines - 1); - const extending = fresh or up > 0 or down > 0; - var row0 = old.row; - var covered = old.rows; - var text = old.text; - var owned = false; - if (extending) { - const rows = shellRows(p, pane) catch return null; - row0 = old.row - @max(0, up); - covered = old.rows + @max(0, up) + @max(0, down); - const up_len: usize = @intCast(@max(0, up)); - const down_len: usize = @intCast(@max(0, down)); - const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; - for (parts[0..up_len], 0..) |*part, i| { - const src = @as(usize, @intCast(row0)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - const middle: usize = @intCast(old.row); - parts[up_len] = if (fresh) - (if (middle < rows.len) rows[middle] else "") - else - old.text; - for (parts[up_len + 1 ..], 0..) |*part, i| { - const src = @as(usize, @intCast(old.row + old.rows)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - text = std.mem.join(p.gpa, "\n", parts) catch return null; - owned = true; - } - - const row: usize = @intCast(@max(0, want_lo - row0)); - const line_len: i32 = @intCast(modal.lineSlice(text, row).len); - if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); - return null; - }; - @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); - return null; - }; - if (owned) p.gpa.free(text); - text = padded; - owned = true; - } - if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); - pane.ovl = .{ .row = row0, .rows = covered, .text = text }; - } - return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; -} - -/// Consume a rewritten overlay, freeing the terminal edit text it replaces. -pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - p.gpa.free(overlay.text); - overlay.text = new; -} - -/// The shell's screen and scrollback (the primary screen, even under a -/// full-screen program) as VT that replays to what was shown: styled -/// text, soft-wrapped lines rejoined so they reflow at another width. -fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { - const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; - var out: std.Io.Writer.Allocating = .init(arena); - try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); - return out.written(); -} - -/// Serialize terminal-only state; the core supplies shared pane metadata. -pub fn dumpPane( - pane: *Pane, - arena: std.mem.Allocator, - tag: []const u8, - body: []const u8, - scroll: usize, -) !dump.Pane { - if (!enabled or pane.terminal == null) { - const text = if (pane.ovl) |overlay| overlay.text else ""; - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = try arena.dupe(u8, text), - .stream_b64 = &.{}, - .cursor = .{ .col = 0, .row = 0 }, - }, - }; - } - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); - const extra = if (pane.ovl) |overlay| overlay.text.len else 0; - const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); - var len: usize = 0; - var lines = std.mem.splitAny(u8, full, "\n"); - var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - var row: i32 = 0; - var skip: i32 = 0; - while (lines.next()) |raw| : (row += 1) { - // Hidden overlay rows still consume prompt pins to keep them aligned. - const prompt = if (pane.body.mode != .tty) prompts.next() else null; - if (skip > 0) { - skip -= 1; - continue; - } - if (row > 0) { - stream[len] = '\n'; - len += 1; - } - if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { - @memcpy(stream[len..][0..overlay.text.len], overlay.text); - len += overlay.text.len; - skip = overlay.rows - 1; - continue; - }; - const shown = if (prompt) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - @memcpy(stream[len..][0..shown.len], shown); - len += shown.len; - } - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), - .stream_is_screen = true, - .cursor = .{ - .col = pane.terminal.?.vt.screens.active.cursor.x, - .row = pane.terminal.?.vt.screens.active.cursor.y, - }, - }, - }; -} - -fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); - var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - // split yields one more item than delimiters; the extra final slot is the - // cursor row retained below. - const n_rows = std.mem.count(u8, full, "\n") + 2; - const rows = try alloc.alloc([]const u8, n_rows); - errdefer alloc.free(rows); - // Blanking a prompt row only ever SHORTENS it and the retained cursor row - // adds one separator, so the dump's length plus one bounds the join. - const text = try alloc.alloc(u8, full.len + 1); - errdefer alloc.free(text); - var at: usize = 0; - var n: usize = 0; - var it = std.mem.splitScalar(u8, full, '\n'); - while (it.next()) |raw| { - const shown = if (pit.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - if (n > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; - at += shown.len; - n += 1; - } - text[at] = '\n'; - at += 1; - rows[n] = text[at..][0..0]; - n += 1; - std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; -} - -pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { - const state = pane.terminal orelse break :vp &.{}; - const screen = state.vt.screens.active; - var tl = screen.pages.getTopLeft(.viewport); - tl.x = 0; - const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; - var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); - const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); - const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); - var lines = std.mem.splitScalar(u8, raw, '\n'); - var n: usize = 0; - while (lines.next()) |ln| { - vp[n] = if (pane.body.mode != .tty) - if (prompts.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln - else - ln - else - ln; - n += 1; - } - std.debug.assert(n == vp.len); - break :vp vp; - }; - - const len = fillBody(null, pane, vp); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, vp); - std.debug.assert(filled == out.len); - return out; -} - -pub const BodyRow = union(enum) { - grid: i32, - edit: struct { line: []const u8, idx: usize }, -}; - -const BodyWalk = struct { - pane: *Pane, - goff: i32, - g: i32, - /// the buffer can start above the viewport: drop the lines scrolled past - skip: usize, - n: usize = 0, - lines: ?std.mem.SplitIterator(u8, .scalar) = null, - covered: i32 = 0, - line_idx: usize = 0, - - fn init(pane: *Pane) BodyWalk { - const off = pane.scroll(); - const goff = gridOffset(pane); - return .{ - .pane = pane, - .goff = goff, - .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), - .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, - }; - } - - fn next(w: *BodyWalk) ?BodyRow { - while (w.n < w.pane.rows) { - if (w.lines) |*it| { - if (it.next()) |line| { - const idx = w.line_idx; - w.line_idx += 1; - // Lines scrolled off the top still count: the index names a - // line of the BUFFER, not of the visible body. - if (w.skip > 0) { - w.skip -= 1; - continue; - } - w.n += 1; - return .{ .edit = .{ .line = line, .idx = idx } }; - } - // The buffer stands in for `rows` shell rows however many lines - // it actually spelled, which is the whole slide. - w.g += w.covered; - w.skip = 0; - w.lines = null; - continue; - } - if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { - w.lines = std.mem.splitScalar(u8, o.text, '\n'); - w.covered = o.rows; - w.line_idx = 0; - continue; - }; - const vi = w.g - w.goff; - w.g += 1; - w.n += 1; - return .{ .grid = vi }; - } - return null; - } -}; - -/// Run the terminal body row walk. A null destination counts bytes; a slice -/// fills the exact allocation made from that count. -fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { - var walk: BodyWalk = .init(pane); - var written: usize = 0; - var first = true; - while (walk.next()) |row| { - if (!first) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - first = false; - const bytes = switch (row) { - .edit => |e| e.line, - .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) - viewport[@intCast(vi)] - else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; - } - return written; -} - -// Match surviving edit-buffer rows to their original terminal styles. -const EditAnchors = struct { - /// the buffer's own text, walked in order: a line the VIEWPORT skipped still - /// consumes the row it came from, so the lines below it stay aligned - text: []const u8 = &.{}, - at: usize = 0, - shell: []const []const u8 = &.{}, - /// the covered span, absolute grid rows, as `[first, end)` - first: usize = 0, - end: usize = 0, - lines: usize = 0, - /// the line `at` names, and the first row still unclaimed - idx: usize = 0, - cursor: usize = 0, - budget: usize = 0, - active: bool = false, - - fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { - if (o.rows <= 0 or o.row < 0) return .{}; - const first: usize = @intCast(o.row); - const screen = pane.terminal.?.vt.screens.active; - const total = screen.pages.scrollbar().total; - if (first >= total) return .{}; - const covered: usize = @intCast(o.rows); - const count = @min(covered, total - first); - const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; - const br = screen.pages.pin(.{ .screen = .{ - .x = screen.pages.cols - 1, - .y = @intCast(first + count - 1), - } }) orelse return .{}; - const arena = p.scratch.allocator(); - var output: std.Io.Writer.Allocating = .init(arena); - screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; - const shell = arena.alloc([]const u8, count) catch return .{}; - var raw = std.mem.splitScalar(u8, output.written(), '\n'); - var pins = tl.rowIterator(.right_down, br); - for (shell) |*row| { - const text = raw.next() orelse ""; - row.* = if (pins.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text - else - text; - } - const lines = std.mem.count(u8, o.text, "\n") + 1; - return .{ - .text = o.text, - .shell = shell, - .first = first, - .end = first + count, - .lines = lines, - .cursor = first, - .budget = covered + 4 * lines, - .active = true, - }; - } - - fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { - if (!a.active or idx >= a.lines) return null; - var found: ?Anchor = null; - while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); - return found; - } - - fn nextLine(a: *EditAnchors) ?[]const u8 { - if (a.at > a.text.len) return null; - const rest = a.text[a.at..]; - if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { - a.at += n + 1; - return rest[0..n]; - } - // The last line has no terminator; one past the end ends the walk. - a.at = a.text.len + 1; - return rest; - } - - /// Where this line still stands over the grid, if anywhere. - fn claim(a: *EditAnchors, line: []const u8) ?Anchor { - const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; - var k = a.cursor; - while (k < end) : (k += 1) { - if (a.budget == 0) return null; - a.budget -= 1; - if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; - a.cursor = k + 1; - return .{ .row = @intCast(k) }; - } - if (a.cursor >= a.end) return null; - const shell = a.shell[a.cursor - a.first]; - var p: usize = 0; - while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; - var s: usize = 0; - const room = @min(line.len, shell.len) - p; - while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; - if (p + s == 0) return null; - if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; - const row = a.cursor; - if (s > 0 or p >= shell.len) a.cursor += 1; - return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; - } -}; - -const Anchor = struct { - /// the row, absolute while it comes from `EditAnchors`, viewport once - /// `recolorAnsi` has subtracted the walk's offset - row: i32, - prefix: usize = std.math.maxInt(usize), - suffix: usize = 0, - /// the row's own dumped length — what the suffix is measured from on the - /// GRID side, where the edit may have changed the byte count - shell_len: usize = 0, - - fn whole(an: Anchor) bool { - return an.prefix == std.math.maxInt(usize); - } -}; - -pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - // No emulator, no ANSI cells: the whole pass — and the 256-colour theme - // projection behind it — is compiled out. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const body_y = p.bodyTop(pane, r); - var filtered_storage: FilteredColors = undefined; - const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { - const tz_filter = tracy.zone(@src(), "filterInit"); - defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, pane); - break :blk &filtered_storage; - } else null; - // DECSCNM, read once: the filtered palette folds it in itself, the raw - // path needs it per cell. - const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); - const pages = &pane.terminal.?.vt.screens.active.pages; - const vp_rows: i32 = @intCast(scrollbar(pane).len); - // Which buffer lines the user has not actually changed, so a row swallowed - // by a growing buffer keeps the colour it still stands over. - var anchors: ?EditAnchors = null; - var walk: BodyWalk = .init(pane); - var lines = std.mem.splitScalar(u8, body, '\n'); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - // Before any early exit below, or the lines fall out of step with rows. - const text = lines.next() orelse ""; - const anchor: Anchor = switch (row) { - .edit => |e| blk: { - if (anchors == null) anchors = .init(p, pane, pane.ovl.?); - var an = anchors.?.shellRow(e.idx) orelse continue; - an.row -= walk.goff; - break :blk an; - }, - .grid => |v| .{ .row = v }, - }; - const vi = anchor.row; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { - if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; - break :cut switch (promptCut(row_pin)) { - .keep => 0, - // Blanked end to end: the row shows nothing of the grid, so - // projecting the prompt's own colours onto it would be a lie. - .blank => continue, - .cut => |n| std.math.cast(u16, n) orelse continue, - }; - }; - if (cut > 0 and text.len == 0) continue; - var at: usize = 0; - var sc: u16 = 0; - var gc: u16 = cut; - var sb: usize = 0; - const mine_from = @min(anchor.prefix, text.len); - const mine_to = text.len - @min(anchor.suffix, text.len); - var crossed = false; - while (at < text.len and sc < tw) { - const stop = modal.nextGrapheme(text, at); - if (stop <= at) break; - const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; - if (at >= mine_from and at < mine_to) { - sc += span; - at = stop; - continue; - } - if (at >= mine_to and !crossed) { - crossed = true; - const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); - while (sb < upto) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - sb += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - } - } - const want = stop - at; - // Consume every cell that contributed to this grapheme. A cluster - // ghostty split across several cells is still ONE printed glyph. - var covered: usize = 0; - var style: ?pardes.CellStyle = null; - while (covered < want) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) - style = cellStyle(p, ci, filtered, scnm); - covered += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - // A spacer contributes no bytes; without this the loop would - // spin on a row that ends in one. - if (covered == 0 and gc >= pane.cols) break; - } - while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { - if (t.cell.wide != .spacer_tail) break; - gc = std.math.add(u16, gc, 1) catch break; - } - if (style) |st| for (0..span) |k| { - const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = st; - }; - sb += covered; - sc += span; - at = stop; - } - var tail: ?pardes.CellStyle = null; - if (anchor.whole() or anchor.suffix > 0) { - while (sc < tw) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - gc = std.math.add(u16, gc, 1) catch break; - if (ci.cell.wide == .spacer_tail) continue; - const cell = s.at(tx + sc, body_y + vr); - sc += 1; - const style = cellStyle(p, ci, filtered, scnm); - tail = style; - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - } - if (tail) |style| while (sc < tw) : (sc += 1) { - const cell = s.at(tx + sc, body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - }; - } - } -} - -fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { - const style = ci.style(); - var cs: pardes.CellStyle = .{ - .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), - .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), - .bold = style.flags.bold, - .dim = style.flags.faint, - .italic = style.flags.italic, - .blink = style.flags.blink, - .reverse = style.flags.inverse, - .invisible = style.flags.invisible, - .strikethrough = style.flags.strikethrough, - .ul = switch (style.flags.underline) { - .none => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; - if (filtered == null) switch (ci.cell.content_tag) { - .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), - .bg_color_rgb => { - const rgb = ci.cell.content.color_rgb; - cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; - }, - else => {}, - }; - return cs; -} - -const FilteredColors = struct { - source: GColor.Palette, - target: *const GColor.Palette, - theme_bg: GColor.RGB, - theme_fg: GColor.RGB, - dynamic_bg: ?GColor.RGB, - dynamic_fg: ?GColor.RGB, - default_bg: GColor.RGB, - /// What a foreground too near `default_bg` becomes instead. - fallback_fg: GColor.RGB, - default_bg_luminance: f64, - fg_for_palette: [256]pardes.Color = undefined, - bg_for_palette: [256]pardes.Color = undefined, - /// The two answers for a cell that names no colour of its own. - fg_default: pardes.Color = undefined, - bg_default: pardes.Color = undefined, - cache_rgb: [256]GColor.RGB = undefined, - cache_key: [256]u8 = undefined, - cache_valid: [256]bool = @splat(false), - - fn init(p: *Pardes, pane: *const Pane) FilteredColors { - var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; - const theme = p.theme(); - var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); - var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); - var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); - if (pane.terminal.?.vt.modes.get(.reverse_colors)) { - std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); - std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); - } - var self: FilteredColors = .{ - .source = source, - .target = p.tty_filter_palette.get(theme), - .theme_bg = theme_bg, - .theme_fg = theme_fg, - .dynamic_bg = dynamic_bg, - .dynamic_fg = dynamic_fg, - .default_bg = theme_bg, - .fallback_fg = theme_fg, - .default_bg_luminance = luminanceOf(theme_bg), - }; - if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); - self.default_bg_luminance = luminanceOf(self.default_bg); - if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) - self.fallback_fg = self.theme_bg; - - self.fg_default = asPardesColor(self.legible( - if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, - )); - self.bg_default = asPardesColor(self.default_bg); - for (&self.source, 0..) |current, i| { - const idx: u8 = @intCast(i); - const mapped = self.paletteRgb(idx, current); - self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); - self.bg_for_palette[idx] = asPardesColor(mapped); - } - return self; - } - - fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { - return switch (style.fg_color) { - .none => self.fg_default, - .palette => |idx| self.fg_for_palette[idx], - .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ - .default = self.dynamic_fg orelse self.theme_fg, - .palette = &self.source, - .bold = null, - })))), - }; - } - - fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { - switch (cell.content_tag) { - .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], - .bg_color_rgb => {}, - else => switch (style.bg_color) { - .none => return self.bg_default, - .palette => |idx| return self.bg_for_palette[idx], - .rgb => {}, - }, - } - // Truecolour, from either the cell or its style. - return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); - } - - fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { - if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= - config.tty_filter_min_contrast) return rgb; - return self.fallback_fg; - } - - fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { - if (current.eql(GColor.default[idx])) return self.target[idx]; - return self.keyedRgb(current); - } - - fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { - return self.target[self.nearestKey(rgb)]; - } - - fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { - const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; - const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); - if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) - return self.cache_key[slot]; - - var best: u8 = 0; - var best_distance: u32 = std.math.maxInt(u32); - for (GColor.default, 0..) |candidate, i| { - const distance = colorDistance(rgb, candidate); - // Strict comparison makes duplicate-colour ties stable at the - // lowest canonical xterm key. - if (distance < best_distance) { - best_distance = distance; - best = @intCast(i); - } - } - self.cache_rgb[slot] = rgb; - self.cache_key[slot] = best; - self.cache_valid[slot] = true; - return best; - } -}; - -const channel_luminance: [256]f64 = blk: { - @setEvalBranchQuota(20000); - var table: [256]f64 = undefined; - for (&table, 0..) |*slot, c| { - const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; - slot.* = if (normalized <= 0.03928) - normalized / 12.92 - else - std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); - } - break :blk table; -}; - -fn luminanceOf(rgb: GColor.RGB) f64 { - return 0.2126 * channel_luminance[rgb.r] + - 0.7152 * channel_luminance[rgb.g] + - 0.0722 * channel_luminance[rgb.b]; -} - -/// ghostty's `RGB.contrast` with both luminances already in hand. -fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { - const lighter = @max(a_luminance, b_luminance); - const darker = @min(a_luminance, b_luminance); - return (lighter + 0.05) / (darker + 0.05); -} - -fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { - const dr = @as(i32, a.r) - @as(i32, b.r); - const dg = @as(i32, a.g) - @as(i32, b.g); - const db = @as(i32, a.b) - @as(i32, b.b); - return @intCast(dr * dr + dg * dg + db * db); -} - -test "the luminance table answers exactly what ghostty computes" { - for (0..256) |i| { - const c: u8 = @intCast(i); - const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; - try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); - } - // Channel weights are asymmetric, so a grey ramp alone would not catch a - // transposed coefficient. The palette is what the tables enumerate. - for (GColor.default) |candidate| { - try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); - for (GColor.default) |page| { - try std.testing.expectEqual( - candidate.contrast(page), - contrastOf(luminanceOf(candidate), luminanceOf(page)), - ); - } - } -} - -test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { - const testing = std.testing; - // Raw index assertions require a theme that inherits the ANSI palette. - const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a one-row tag keeps this small screen's rows - p.sync(); - try testing.expect(pane.tty_filter); - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ - "\x1b[38;5;196mB" ++ - "\x1b[38;2;255;0;0mC" ++ - "\x1b[0;48;5;25mD" ++ - "\x1b[0;48;2;0;95;175mE" ++ - "\x1b[0;1;2;3;4;5;7;8;9mF" ++ - "\x1b[0;48;5;25m\x1b[K" ++ - "\r\n\x1b[0;38;5;2m界" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - const raw = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = expected_cache.get(p.theme()); - try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); - try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); - try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); - - const attrs = filtered.at(tx + 5, body_y).style; - try testing.expect(attrs.bold); - try testing.expect(attrs.dim); - try testing.expect(attrs.italic); - try testing.expect(attrs.blink); - try testing.expect(attrs.reverse); - try testing.expect(attrs.invisible); - try testing.expect(attrs.strikethrough); - try testing.expectEqual(.single, attrs.ul); - - const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; - try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); - try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); - // A filtered terminal never delegates either colour to a backend palette, - // including cells which were empty/default before the pass. - for (0..r.w - config.GUTTER) |col| { - const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); - try testing.expect(!cell.default); - switch (cell.style.fg) { - .rgb => {}, - else => return error.FilteredForegroundWasNotRgb, - } - switch (cell.style.bg) { - .rgb => {}, - else => return error.FilteredBackgroundWasNotRgb, - } - } - - // Colors remains the global master gate. The pane remembers Filter while - // ANSI projection is dormant, and resumes it without replaying VT bytes. - p.settings.colors = false; - _ = frame.reset(.retain_capacity); - const plain = try p.render(frame.allocator()); - try testing.expect(pane.tty_filter); - try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); - p.settings.colors = true; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); - const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); - pane.tty_filter = false; - pane.tty_filter = true; - try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - _ = frame.reset(.retain_capacity); - const osc_palette = try p.render(frame.allocator()); - try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); - - // Dynamic default foreground/background colours key every default cell, - // including the otherwise blank end of the row. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ - "\x1b]11;#5f5f5f\x1b\\" } }); - const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; - const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; - try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); - try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); - _ = frame.reset(.retain_capacity); - const dynamic = try p.render(frame.allocator()); - const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), blank.bg); - - const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); -} - -test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = cache.get(p.theme()); - try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); -} - -test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); -} - -test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, pane); - // `dark` declares no background of its own, which is exactly why the - // resolver reads the tag colours as the fallback rather than `.?`. - const theme = p.theme(); - try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); - // With no OSC 11 in play the mapped page IS that anchor, and the - // fallback is the other one: a background never contrasts with itself. - try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); - try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); - try testing.expect(!moved.default_bg.eql(moved.theme_bg)); - try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); -} - -test "terminal Filter refuses a foreground that would collapse onto the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ - "\x1b[0;30mB" ++ - "\x1b[0;31mR" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - const page = asPardesColor(fc.default_bg); - const rescued = asPardesColor(fc.fallback_fg); - _ = frame.reset(.retain_capacity); - const g = try p.render(frame.allocator()); - - // The colour each of the three would have been given with no floor. - const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); - const raw_black = fc.paletteRgb(0, GColor.default[0]); - const raw_red = fc.paletteRgb(1, GColor.default[1]); - - for ([_]struct { at: u16, raw: GColor.RGB }{ - .{ .at = 0, .raw = raw_white }, - .{ .at = 1, .raw = raw_black }, - .{ .at = 2, .raw = raw_red }, - }) |case| { - const cell = g.at(tx + case.at, body_y).style; - try testing.expectEqual(page, cell.bg); - if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { - // Refused: the projection's answer is not painted, the anchor is. - try testing.expectEqual(rescued, cell.fg); - try testing.expect(!std.meta.eql(cell.fg, cell.bg)); - } else { - // Cleared the floor, so stage two leaves it exactly alone. - try testing.expectEqual(asPardesColor(case.raw), cell.fg); - } - // Either way a filtered cell delegates neither colour to a backend. - switch (cell.fg) { - .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= - config.tty_filter_min_contrast), - else => return error.FilteredForegroundWasNotRgb, - } - } - - // At least one of the three has to have been a real collapse, or this - // theme proved nothing: white on the light theme, black on the dark. - try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or - raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - } -} - -test "terminal Filter holds every projected foreground off the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - var refused: usize = 0; - for (fc.target, 0..) |projected, key| { - const ink = fc.legible(projected); - try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(fc.fallback_fg)); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); - } - // The key a background asks for is handed back untouched, including - // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } -} - -test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.body.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.body.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); -} - -test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a 12x8 screen: the body, not the tag - p.sync(); - pane.tty_filter = false; - pane.body.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); -} - -pub fn palColor(p: *Pardes, idx: u8) pardes.Color { - if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; - return .{ .index = idx }; -} - -pub fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { - return switch (color) { - .none => blk: { - const t = if (is_bg) p.theme().bg else p.theme().fg; - break :blk if (t) |c| .{ .rgb = c } else .default; - }, - .palette => |idx| palColor(p, idx), - .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, - }; -} - -/// executing at a prompt with typed text below it: pad the output area -/// with newlines so the command's output doesn't overwrite the buffer -pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { - // Nothing to pad away from: with no emulator there is no prompt and no - // child whose output could land on top of the edit buffer. - if (comptime !enabled) return; - const pane = p.panes[id] orelse return; - const o = pane.ovl orelse return; - if (!pane.isTerminal()) return; - const state = pane.terminal orelse return; - if (!state.vt.cursorIsAtPrompt()) return; - // the buffer's LAST surface row: its lines may outnumber the shell - // rows it covers, and it is the bottom one output must clear - const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; - const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); - const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); - const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); - var i: i32 = 0; - while (i < pad) : (i += 1) p.emitWrite(id, "\r"); -} - -pub fn pushUndo(p: *Pardes, pane: *Pane) void { - pane.body.remember(p.gpa, pane.ovl); -} - -pub fn undo(p: *Pardes, pane: *Pane) void { - const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = back_to.ovl; - pane.ensureCursorVisible(); -} - -pub fn redo(p: *Pardes, pane: *Pane) void { - const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = forward_to.ovl; - pane.ensureCursorVisible(); -} - -pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - const n = @min(room, data.len); - @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); - state.reply_len += @intCast(n); -} - -const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( - @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), -).optional.child).pointer.child).@"fn".return_type.?; -pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { - return .{}; -} diff --git a/src/Text.zig b/src/Text.zig index ab23bf8e..cef76b3b 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -14,7 +14,7 @@ const config = @import("config.zig"); const memory = @import("memory.zig"); const Pane = panes.Pane; const File = panes.File; -const Terminal = panes.Terminal; +const terminal = panes.terminal; const Text = @This(); pub const Mode = enum { normal, insert, tty }; @@ -84,9 +84,9 @@ normal: modal.Normal.State = .{}, /// last f/F/t/T motion, for Alt-. repeat find_op: u8 = 0, find_ch: u21 = 0, -ed_undo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_undo: [terminal.history_max]terminal.Snapshot = undefined, ed_undo_len: usize = 0, -ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, +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 @@ -706,10 +706,10 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.show(); } -fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, value: Terminal.Snapshot) void { +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..]); + std.mem.copyForwards(terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); len.* -= 1; } slots[len.*] = value; @@ -719,14 +719,14 @@ fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, /// 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) void { +pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer) 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 = gpa.dupe(u8, now.text) catch return } else null; + const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return } 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; @@ -736,13 +736,13 @@ pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer) /// 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) ?Terminal.Snapshot { +pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer, back: bool) ?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 = gpa.dupe(u8, now.text) catch return null } else null; + const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return null } 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.*]; diff --git a/src/body_layer.zig b/src/body_layer.zig index 6e1fe8f1..cb26c1f2 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -51,7 +51,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { if (visible >= r.h -| pane.tag_rows) break; - const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; + const source_row = if (raw) panes.terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; for (rows) |row| { const target = if (row.raw_terminal) (if (raw) row.row else pane.surfRow(row.row)) @@ -64,7 +64,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ lo -|= row.prompt_bytes; hi -|= row.prompt_bytes; } else if (!row.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, source_row, line); + const prefix = panes.terminal.promptPrefixBytes(pane, source_row, line); lo += prefix; hi += prefix; } @@ -85,7 +85,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); - const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; + const terminal_lines = if (pane.file == null) panes.terminal.cursorLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; const body_y = p.bodyTop(pane, r); @@ -291,7 +291,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); } else if (pane.isTerminal() and p.settings.colors) { - panes.Terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); + panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); @@ -440,8 +440,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // (the tag's or a prompt's cursor wins while that is being typed into) if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice)) { if (pane.body.mode != .tty) { - const cur = panes.Terminal.gridCursor(pane); - const goff = panes.Terminal.gridOffset(pane); + const cur = panes.terminal.gridCursor(pane); + const goff = panes.terminal.gridOffset(pane); const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); const cwp = pane.wrapRow(crow, ccol); @@ -460,7 +460,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane ccol; if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; - } else if (panes.Terminal.visibleCursor(pane)) |cur| { + } else if (panes.terminal.visibleCursor(pane)) |cur| { if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; } @@ -492,5 +492,5 @@ pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { unreachable; } if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); - return panes.Terminal.bodyText(arena, pane); + return panes.terminal.bodyText(arena, pane); } diff --git a/src/builtins.zig b/src/builtins.zig index cc86067e..c549b17f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -625,7 +625,7 @@ pub const Kill = struct { stopped = true; continue; }; - if (!panes.Terminal.commandRunning(pane)) continue; + if (!panes.terminal.commandRunning(pane)) continue; const sent = pane.sent_command.?; if (names.len > 0) { var words = std.mem.tokenizeAny(u8, names, " \t"); diff --git a/src/draw.zig b/src/draw.zig index 10303117..ad24153f 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -63,7 +63,7 @@ pub fn place(p: *Pardes, s: *Surface) void { // A folded pane is its tag rows and nothing else. if (pane.collapsed) continue; const body_h = r.h -| pane.tag_rows; - const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.Terminal.gridOffset(pane) else 0; + const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } }; // An image's rail has no thumb; a native PDF's is measured as its @@ -78,7 +78,7 @@ pub fn place(p: *Pardes, s: *Surface) void { .offset = page, .len = 1, } else blk: { - const gsb = panes.Terminal.scrollbar(pane); + const gsb = panes.terminal.scrollbar(pane); break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; }; const track_h: usize = body_h; @@ -241,7 +241,7 @@ fn glideCursor(p: *Pardes, s: *Surface) void { if (inside) frame = paneFrame(s, pane.serial, rect); const origin: [2]f32 = .{ @floatFromInt(rect.x), @floatFromInt(rect.y) }; const view = p.cursor_view; - const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) panes.Terminal.gridOffset(pane) else 0; + const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; if (view.serial == pane.serial and view.inside == inside) { // The pane moved in the layout: the springs move with it (its // own cursor's; one in a column's tag stays). @@ -719,7 +719,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { sb_off = page; sb_total = if (comptime pdf_enabled) at.pdf.?.page_count else 0; } else { - const sb = panes.Terminal.scrollbar(at); + const sb = panes.terminal.scrollbar(at); sb_off = sb.offset; sb_total = sb.total; } diff --git a/src/dump.zig b/src/dump.zig index 1eabdae8..73d4e4ed 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -731,7 +731,7 @@ pub fn dumpState(p: *Pardes) !void { } else if (pane.image) |iv| try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) else - try pardes.panes.Terminal.dumpPane(pane, arena, tag, body, scroll); + try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); dp.tag_tail = pane.tag.own; if (dp.file) |*df| { const dot = ctlfs.pane.dotOf(pane); @@ -914,7 +914,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo // and how it ended: its command is not run again. const live = comptime (terminal_panes and platform != .web and !isolated); const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; - const restored = try pardes.panes.Terminal.restore(p, src, revive); + const restored = try pardes.panes.terminal.restore(p, src, revive); p.installPane(i, restored); try restored.setOwnedCwd(t.cwd); if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); diff --git a/src/edit.zig b/src/edit.zig index 26062029..98c60efb 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -113,7 +113,7 @@ pub fn clipRequest(p: *Pardes, id: usize, mode: @FieldType(ClipRequest, "mode")) pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { if (text.len == 0) return; - if (panes.Terminal.bracketedPaste(pane)) { + if (panes.terminal.bracketedPaste(pane)) { p.emitWrite(id, "\x1b[200~"); p.emitWrite(id, text); p.emitWrite(id, "\x1b[201~"); @@ -225,7 +225,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); - const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null and !raw) try panes.terminal.cursorLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows); @@ -242,7 +242,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { const left: i32 = if (cols.first) cols.lo else prefix; const right: i32 = cols.hi orelse std.math.maxInt(i32) / 2; var source = pane.wrapAt(visible); - if (raw) source = .{ .line = panes.Terminal.gridOffset(pane) + visible, .at = 0 }; + if (raw) source = .{ .line = panes.terminal.gridOffset(pane) + visible, .at = 0 }; const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); var next = pane.wrapAt(visible + 1); if (raw) next = .{ .line = source.line + 1, .at = 0 }; @@ -256,7 +256,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { .hi = if (right < prefix) lo else if (cols.hi == null) end else @min(end, modal.nextGrapheme(line, at)), .to_edge = cols.hi == null, .raw_terminal = raw, - .prompt_bytes = if (raw) panes.Terminal.promptPrefixBytes(pane, source.line, line) else 0, + .prompt_bytes = if (raw) panes.terminal.promptPrefixBytes(pane, source.line, line) else 0, }; const rendered = modal.lineSlice(body, @intCast(visible)); const prefix_end = @min(rendered.len, @as(usize, @intCast(@min(prefix, right + 1)))); @@ -276,7 +276,7 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { const arena = p.scratch.allocator(); if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); if (pane.pointerSelection(sl)) |rows| { - const terminal_lines = if (pane.file == null) try panes.Terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null) try panes.terminal.cursorLines(p, pane) else &.{}; var total: usize = rows.len -| 1; for (rows) |row| { const line = pointerSourceLine(pane, terminal_lines, row.row); @@ -402,7 +402,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); unreachable; } - return panes.Terminal.cursorLines(p, pane); + return panes.terminal.cursorLines(p, pane); } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { @@ -448,8 +448,8 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); unreachable; } - const lines = try panes.Terminal.cursorLines(p, pane); - return panes.Terminal.flatSurface(p, pane, lines); + const lines = try panes.terminal.cursorLines(p, pane); + return panes.terminal.flatSurface(p, pane, lines); } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { @@ -474,7 +474,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; - return panes.Terminal.editText(p, pane, lo, hi, col); + return panes.terminal.editText(p, pane, lo, hi, col); } fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { @@ -535,7 +535,7 @@ pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) }; t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; if (pane.file) |*f| return panes.File.setContent(p, f, new); - panes.Terminal.setEditText(p, pane, new); + panes.terminal.setEditText(p, pane, new); } /// Take a text an edit made that nothing keeps, holding it until the next @@ -2057,7 +2057,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { } const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { @@ -2065,7 +2065,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undo(p, pane); - panes.Terminal.undo(p, pane); + panes.terminal.undo(p, pane); } pub fn doRedo(p: *Pardes, t: *Text) void { @@ -2073,7 +2073,7 @@ pub fn doRedo(p: *Pardes, t: *Text) void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.redo(p, pane); - panes.Terminal.redo(p, pane); + panes.terminal.redo(p, pane); } /// Undo or redo an edit of a text's own characters; stepping back past its diff --git a/src/exec.zig b/src/exec.zig index 2c42389c..221de105 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -42,11 +42,11 @@ pub fn takesCommandLine(p: *const Pardes, id: usize) bool { // idle, EMPTY prompt is typed at; otherwise a new pane runs the line. // (Text in pardes's own edit buffer is not the shell's yet: an exec of // it, or of anything, types only what it runs.) - if (panes.Terminal.promptInputReady(pane) and !panes.Terminal.promptInputEmpty(pane)) return false; + if (panes.terminal.promptInputReady(pane) and !panes.terminal.promptInputEmpty(pane)) return false; // A mounted shell sits behind sudo's process supervisor. Its OSC 133 // prompt marks identify input readiness; the launcher's executable is // not the shell executable used by the ordinary process heuristic. - if (pane.v9fs_on_spawn) return panes.Terminal.promptInputReady(pane); + if (pane.v9fs_on_spawn) return panes.terminal.promptInputReady(pane); return !p.hostTtyTaken(id); } @@ -111,7 +111,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand const visible = clicked.r0 - @as(i32, pane.tag_rows); const wrapped = pane.wrapAt(visible); const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows; - const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; + const row = if (raw) panes.terminal.gridOffset(pane) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) @@ -143,7 +143,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand lo -|= span.prompt_bytes; hi -|= span.prompt_bytes; } else if (!span.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, row, raw_line); + const prefix = panes.terminal.promptPrefixBytes(pane, row, raw_line); lo += prefix; hi += prefix; } @@ -429,8 +429,8 @@ pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { const tt = p.panes[tty_id] orelse return; // No typing, cursor on the first prompt line, no scrollback: this is // the throwaway boot placeholder a document may replace. - if (tt.ovl != null or panes.Terminal.gridCursor(tt).y != 0 or - panes.Terminal.scrollbar(tt).total > tt.rows) return; + if (tt.ovl != null or panes.terminal.gridCursor(tt).y != 0 or + panes.terminal.scrollbar(tt).total > tt.rows) return; p.deinitPane(tt) catch |err| return p.reportError(tty_id, "close", err); layout.compute(p); // a just-stacked doc has no rect yet; absorb snaps to rows _ = layout.absorbVWeight(p, tty_id, null); @@ -588,7 +588,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { var said: [128]u8 = undefined; return p.setMessage(from, std.fmt.bufPrint(&said, "Repl: {d} bytes is more than can be sent at once; send less", .{n}) catch "Repl: too long to send"); } - const pasted = panes.Terminal.bracketedPaste(dst); + const pasted = panes.terminal.bracketedPaste(dst); edit.typeToTty(p, to, dst, clean[0..n]); // A Python block whose last line is indented, or a bare header, is not // over at one Enter, pasted into 3.13's REPL or typed into the old one: @@ -611,7 +611,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { dst.repl_enter_due_ns = clockNow(p) + repl_enter_wait_ns; } else for (0..enters) |_| p.emitWrite(to, "\r"); // Line by line, a blank line inside a Python block ends the block. - if (!panes.Terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and + if (!panes.terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and std.mem.indexOfScalar(u8, text, '\n') != null) { dst.repl_warned = true; @@ -671,9 +671,9 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi return null; } if (!takesCommandLine(p, id)) return runCommand(p, id, cmd); - panes.Terminal.padOutputBelowEdits(p, id); - panes.Terminal.noteCommand(pane, cmd); - if (panes.Terminal.queuePendingCommand(pane, cmd) catch |err| { + panes.terminal.padOutputBelowEdits(p, id); + panes.terminal.noteCommand(pane, cmd); + if (panes.terminal.queuePendingCommand(pane, cmd) catch |err| { p.reportError(id, "queue command", err); return id; }) return id; @@ -733,8 +733,8 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // saved cursor), mouse reports and bracketed paste off, the cursor // shown, colours reset. (Not DECSTR: ghostty's stream does not // implement it.) - if (panes.Terminal.onAlternateScreen(pane)) panes.Terminal.feedOutput(p, pane, "\x1b[?1049l"); - panes.Terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); + if (panes.terminal.onAlternateScreen(pane)) panes.terminal.feedOutput(p, pane, "\x1b[?1049l"); + panes.terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); echoCommand(p, pane, line); p.emitSpawn(id, pane.serial, pane.cwdSlice()); noteRun(p, pane, "run", line); @@ -760,10 +760,10 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { fn echoCommand(p: *Pardes, pane: *Pane, line: []const u8) void { var buf: [2 * command_max + 8]u8 = undefined; var w = std.Io.Writer.fixed(&buf); - w.writeAll(if (panes.Terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {}; + w.writeAll(if (panes.terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {}; for (line) |c| (if (c == '\n') w.writeAll("\r\n") else w.writeByte(c)) catch {}; w.writeAll("\r\n") catch {}; - panes.Terminal.feedOutput(p, pane, w.buffered()); + panes.terminal.feedOutput(p, pane, w.buffered()); } /// `run ` or `exit ` in the log. @@ -788,8 +788,8 @@ pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void { var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?"; var said: [32]u8 = undefined; - const lead = if (panes.Terminal.gridCursor(pane).x != 0) "\r\n" else ""; - panes.Terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n"); + const lead = if (panes.terminal.gridCursor(pane).x != 0) "\r\n" else ""; + panes.terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n"); noteRun(p, pane, "exit", code); p.needs_frame = true; } diff --git a/src/fs.zig b/src/fs.zig index a2e8daf8..fc3eb98f 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -57,7 +57,7 @@ const source_files = [_]Source{ .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, - .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, + .{ .path = "src/terminal.zig", .contents = @embedFile("terminal.zig") }, .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, diff --git a/src/host_io.zig b/src/host_io.zig index 9e3fbf79..e7be28cd 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1293,7 +1293,7 @@ pub fn forkShell( var command: std.Io.Writer.Allocating = .init(c.gpa); defer command.deinit(); try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); - if (!try pardes.panes.Terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; + if (!try pardes.panes.terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } // Built here and not after the fork: between fork and exec the child may // not call setenv, whose malloc can deadlock against a pty reader thread diff --git a/src/layout.zig b/src/layout.zig index 28f567bc..28f3d270 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -607,7 +607,7 @@ fn blankRows(p: *const Pardes, id: usize) u16 { // The empty line after a final newline shows nothing. (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll else if (pane.isTerminal()) - @as(usize, panes.Terminal.gridCursor(pane).y) + 1 + @as(usize, panes.terminal.gridCursor(pane).y) + 1 else rows; return rows -| @as(u16, @intCast(@min(used, rows))); @@ -742,7 +742,7 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { // Its tag may wrap to more than one row: the rows under it are its body. const tag_h = @max(BOX_H, src.tag_rows); const body: u16 = if (src_h > tag_h) src_h - tag_h else 1; - const cur: u16 = if (!src.isTerminal()) body / 2 else panes.Terminal.gridCursor(src).y + 1; + const cur: u16 = if (!src.isTerminal()) body / 2 else panes.terminal.gridCursor(src).y + 1; // cap keep so a content-full source still leaves the new pane a tag + // a few body rows (an Alt-n from a full shell was born 0 rows tall) // ...and the source min_body_rows of its own (exec.placeNew), when it diff --git a/src/mouse.zig b/src/mouse.zig index 1f2648b0..cb0378de 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -821,7 +821,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0); const endpoint = rows[if (forward) rows.len - 1 else 0]; const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; - const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.terminal.gridOffset(pane)))); const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; pane.body.cur_row = pane.surfRow(endpoint.row); var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); @@ -1137,11 +1137,11 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut) return; const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; - if (panes.Terminal.reportsMouse(pane)) { + if (panes.terminal.reportsMouse(pane)) { const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows) + 1, 1, 9999)); var mb: [32]u8 = undefined; - if (panes.Terminal.mouseFormatSgr(pane)) { + if (panes.terminal.mouseFormatSgr(pane)) { p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return); } else { // ponytail: legacy X10 bytes; add utf8/urxvt formats if an app ever wants them diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 5bf354eb..060e0d6c 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -344,7 +344,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { pane.serial, pane_files.tagOf(p, pane).len, // A terminal's body is its history, read whole on an open's first read. - if (pane.isTerminal()) panes.Terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, + if (pane.isTerminal()) panes.terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, @as(u32, 0), @intFromBool(pane_files.dirtyOf(pane)), pane.cols, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3c1e181e..3fad1fae 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -258,7 +258,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pf = &pane.fs; return switch (f) { // A terminal's body reads its screen and history, as text. - .body => if (pane.file == null and pane.isTerminal()) panes.Terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len, + .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len, .data, .xdata => bodyOf(pane).len, .tag => tagOf(p, pane).len, .name => nameOf(pane).len + 1, @@ -399,7 +399,7 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return tree.stagedReply(p, req); } if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane); - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); defer p.gpa.free(text); const out = p.fs.stage(p.gpa); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 8ba9f4df..0f5202cc 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -139,9 +139,9 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // or a line is typed at the prompt. Before the shell's first prompt a // run waits for it rather than answer busy, so that is not busy. // A build with no terminal panes (the board) has no marks to read. - const marks = if (comptime !pardes.panes.Terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; + const marks = if (comptime !pardes.panes.terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or - (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane)) else false))); + (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane)) else false))); const out = p.fs.stage(p.gpa); const size = winsize(pane); out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch {}; @@ -222,7 +222,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); - if (comptime !pardes.panes.Terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); + if (comptime !pardes.panes.terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &pane.fs; const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; @@ -235,7 +235,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { } else if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or - !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) + !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) { // Something is running or someone has typed at the prompt: sending // now would type into the middle of it. The phase is pardes's own @@ -288,7 +288,7 @@ pub fn readRun(p: *Pardes, req: Req) Reply { /// for the prompt means whoever reads the answer can send the next command /// at once instead of finding the shell still drawing it. pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { - if (comptime !pardes.panes.Terminal.enabled) return; + if (comptime !pardes.panes.terminal.enabled) return; const state = pane.terminal orelse return; const pf = &pane.fs; const slot = waitingRun(p, pane) orelse return; @@ -299,13 +299,13 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { pf.run = null; return; } - if (marks.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; + if (marks.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; slot.want = marks.started +% 1; slot.prompts = marks.prompts; slot.declined = marks.declined; p.emitWrite(id, slot.line); p.emitWrite(id, "\r"); - pardes.panes.Terminal.noteCommand(pane, slot.line); + pardes.panes.terminal.noteCommand(pane, slot.line); slot.phase = .sent; return; } @@ -319,7 +319,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { // typed into an empty prompt, so throw it away with Ctrl-C, which // drops the whole pending command, and answer at the prompt after // that, so the next line finds the shell clear. - const empty = pardes.panes.Terminal.promptInputEmpty(pane); + const empty = pardes.panes.terminal.promptInputEmpty(pane); switch (slot.cleared) { .no => { if (marks.continuation) { @@ -360,7 +360,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { /// Answers a run whose command ended with `status`: the header and the /// output it printed. fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { - const printed = pardes.panes.Terminal.commandOutput(pane, p.gpa, output_rows) catch + const printed = pardes.panes.terminal.commandOutput(pane, p.gpa, output_rows) catch return answer(p, slot, "error out of memory", .{}); defer p.gpa.free(printed.text); // Keep the tail, cut at a line start so the first line kept is whole. @@ -400,7 +400,7 @@ pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void { const code = status orelse return; if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) { pane.fs.run = null; - pardes.panes.Terminal.endOutputHere(pane); + pardes.panes.terminal.endOutputHere(pane); finish(p, slot, pane, code); }; var buf: [4]u8 = undefined; @@ -963,10 +963,10 @@ test "a run's answer says cut when its output's start is gone, and reads a bound // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); - pardes.panes.Terminal.resizeGrid(pane, gpa, 50, 20); + pardes.panes.terminal.resizeGrid(pane, gpa, 50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pardes.panes.Terminal.resizeGrid(pane, gpa, pane.cols, pane.rows); + pardes.panes.terminal.resizeGrid(pane, gpa, pane.cols, pane.rows); // A full-screen program leaves nothing on the primary screen, and a D // with no status is not a success. diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index f496da03..b991c3e4 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -47,7 +47,7 @@ pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot; if (snapshot.* == null) { const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.* = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + snapshot.* = panes.terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); } const bytes = snapshot.*.?; const off = @min(req.off, bytes.len); @@ -129,7 +129,7 @@ test "terminal body handles keep one history snapshot across fragmented reads" { const node = Node.of(serialOf(p), .body); p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); while (p.nextEffect()) |_| {} - const original = try panes.Terminal.screenTextAlloc(p.panes[0].?, gpa); + const original = try panes.terminal.screenTextAlloc(p.panes[0].?, gpa); defer gpa.free(original); const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqual(Status.ok, opened.reply.status); diff --git a/src/panes.zig b/src/panes.zig index b6fdc31a..0380f89f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -89,7 +89,7 @@ pub const Pane = struct { pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; pub const Focus = enum { body, tag }; - terminal: ?*Terminal.State = null, + terminal: ?*terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the @@ -116,7 +116,7 @@ pub const Pane = struct { /// A shell has run in it (Pardes.acknowledgeShell): a Tty whose first /// shell fails to start closes, one started again keeps its pane. had_shell: bool = false, - pending_command: Terminal.PendingCommand = .{}, + pending_command: terminal.PendingCommand = .{}, /// The last command line pardes typed into this terminal (an exec, a /// middle click, a pty/run): its first word, which Kill matches, and /// the shell's command count its start (C mark) reaches. @@ -227,7 +227,7 @@ pub const Pane = struct { next_pointer_selection: u64 = 0, /// terminals only: the typed-text buffer standing in for shell rows - ovl: ?Terminal.EditBuffer = null, + ovl: ?terminal.EditBuffer = null, tty_filter: bool = false, msg: [256]u8 = undefined, msg_len: u16 = 0, @@ -486,7 +486,7 @@ pub const Pane = struct { pub fn scroll(pane: *Pane) i32 { if (pane.file) |f| return @intCast(f.scroll); if (comptime Pdf.enabled) if (pane.pdf) |pv| return @intCast(pv.text_scroll); - return pane.surfRow(Terminal.gridOffset(pane)); + return pane.surfRow(terminal.gridOffset(pane)); } pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32 } { @@ -531,8 +531,8 @@ pub const Pane = struct { } } else { // the vt scrolls in SHELL rows; convert through the edit buffer - const off = Terminal.gridOffset(pane); - Terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); + const off = terminal.gridOffset(pane); + terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); } } @@ -611,8 +611,8 @@ pub const Pane = struct { pane.body.cur_row = pane.scroll(); pane.body.cur_col = 0; } else { - const cur = Terminal.gridCursor(pane); - pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + Terminal.gridOffset(pane)); + const cur = terminal.gridCursor(pane); + pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + terminal.gridOffset(pane)); pane.body.cur_col = @intCast(cur.x); } pane.body.cur_pinned = true; @@ -642,7 +642,7 @@ pub const Image = @import("image.zig"); pub const Pdf = @import("pdf_view.zig"); -pub const Terminal = @import("Terminal.zig"); +pub const terminal = @import("terminal.zig"); test { _ = Pane; @@ -652,5 +652,5 @@ test { _ = mini; _ = Image; _ = Pdf; - _ = Terminal; + _ = terminal; } diff --git a/src/pardes.zig b/src/pardes.zig index 141b214e..623af3c9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1195,9 +1195,9 @@ test "Tty9p marks only the new Linux terminal for a mounted shell" { try std.testing.expect(pane.v9fs_on_spawn); try std.testing.expect(!pane.greet); try std.testing.expect(!exec.takesCommandLine(p, p.active)); - panes.Terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); + panes.terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); try std.testing.expect(exec.takesCommandLine(p, p.active)); - panes.Terminal.feedOutput(p, pane, "\x1b]133;C\x07"); + panes.terminal.feedOutput(p, pane, "\x1b]133;C\x07"); try std.testing.expect(!exec.takesCommandLine(p, p.active)); } @@ -1558,7 +1558,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st _ = exec.execute(p, 1, two); while (p.nextEffect()) |_| {} _ = try p.render(frame.allocator()); - const body = try panes.Terminal.screenTextAlloc(pane, gpa); + const body = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(body); try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null); } @@ -1878,7 +1878,7 @@ test "a command pane shows how its command ended, and the next command there run const pane = p.panes[dst].?; // Its first command is echoed as every later one is. { - const first = try panes.Terminal.screenTextAlloc(pane, gpa); + const first = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(first); try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8")); } @@ -1909,16 +1909,16 @@ test "a command pane shows how its command ended, and the next command there run // A program that crashed out of its full screen leaves the emulator // in its modes; the next command starts clear of them. p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "\x1b[?1049h\x1b[?2004h\x1b[?1000h" } }); - try std.testing.expect(panes.Terminal.bracketedPaste(pane)); + try std.testing.expect(panes.terminal.bracketedPaste(pane)); // Done, the directory's next command runs there, below what it showed. try std.testing.expectEqual(@as(?usize, dst), exec.execute(p, 1, "make test")); - try std.testing.expect(!panes.Terminal.bracketedPaste(pane)); + try std.testing.expect(!panes.terminal.bracketedPaste(pane)); var respawned = false; while (p.nextEffect()) |effect| if (effect == .spawn and effect.spawn.pane == dst) { respawned = true; }; try std.testing.expect(respawned); - const body = try panes.Terminal.screenTextAlloc(pane, gpa); + const body = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(body); const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost; const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost; @@ -4394,7 +4394,7 @@ pub const Pardes = struct { settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations.Config = .{}, locations_cache: locations.Cache = .{}, - tty_filter_palette: panes.Terminal.FilterPalette = .{}, + tty_filter_palette: panes.terminal.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, /// bodyChrome's: the theme it was worked out for, and it. @@ -4580,8 +4580,8 @@ pub const Pardes = struct { /// that still own their loop pass their own arena to `render` instead. frame_arena: std.heap.ArenaAllocator, /// the terminal motion surface, memoized against the pane it was built - /// for — see panes.Terminal.RowsCache for the lifetime rule - shell_rows: panes.Terminal.RowsCache = .{}, + /// for — see panes.terminal.RowsCache for the lifetime rule + shell_rows: panes.terminal.RowsCache = .{}, /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. @@ -4944,7 +4944,7 @@ pub const Pardes = struct { } p.shell_rows.dropPane(pane); for (0..pane.pointer_selections.len) |slot| pane.clearPointerSelection(slot); - panes.Terminal.deinitPendingCommand(pane); + panes.terminal.deinitPendingCommand(pane); if (pane.command) |line| p.gpa.free(line); if (pane.shell) |bin| p.gpa.free(bin); if (pane.image) |*iv| { @@ -4957,7 +4957,7 @@ pub const Pardes = struct { pane.tag.deinit(p.gpa); pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); - panes.Terminal.deinitEmulator(pane, p.gpa); + panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); p.gpa.destroy(pane); @@ -4986,12 +4986,12 @@ pub const Pardes = struct { pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { std.debug.assert(p.panes[id] == null); if (cwd.len > limits.host_path_cap) return error.PathTooLong; - const pane = try panes.Terminal.create(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.create(p.gpa, p.screen_w, p.screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); // out of memory for it, the shell names it when it says. if (cwd.len > 0) pane.setOwnedCwd(cwd) catch {}; - panes.Terminal.armShellSpawn(pane); + panes.terminal.armShellSpawn(pane); p.installPane(id, pane); p.emitSpawn(id, pane.serial, cwd); return pane; @@ -5017,7 +5017,7 @@ pub const Pardes = struct { if (cwd.len > limits.host_path_cap) return error.PathTooLong; const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); - const pane = try panes.Terminal.create(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.create(p.gpa, p.screen_w, p.screen_h); pane.command = owned; pane.command_pty = true; pane.body.mode = .tty; @@ -5031,7 +5031,7 @@ pub const Pardes = struct { pub fn newDocPane(p: *Pardes, id: usize) !*Pane { std.debug.assert(p.panes[id] == null); - const pane = try panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); p.installPane(id, pane); return pane; } @@ -5223,7 +5223,7 @@ pub const Pardes = struct { } else |_| {} } }; - if (id < MAX_PANES) panes.Terminal.shellSpawned(p, id, prompt_marks); + if (id < MAX_PANES) panes.terminal.shellSpawned(p, id, prompt_marks); if (p.settings.shell.effective.set(executable)) p.settings.shell.pending = false; } @@ -5358,7 +5358,7 @@ pub const Pardes = struct { /// The pane a session word runs with in an empty window. pub fn standIn(p: *Pardes) ?*Pane { - if (p.stand_in == null) p.stand_in = panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; + if (p.stand_in == null) p.stand_in = panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; return p.stand_in; } @@ -5627,7 +5627,7 @@ pub const Pardes = struct { return; } if (!pane.isTerminal()) return; - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch return; + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return; defer p.gpa.free(text); p.hostWriteFile(st.pane, st.path.slice(), text); }, @@ -5839,7 +5839,7 @@ pub const Pardes = struct { const pane = p.panes[o.pane] orelse return; pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane, o.bytes); - panes.Terminal.feedOutput(p, pane, o.bytes); + panes.terminal.feedOutput(p, pane, o.bytes); ctlfs.pty.noteMarks(p, o.pane, pane); exec.flushReplEnter(p, o.pane, true); }, @@ -5944,7 +5944,7 @@ pub const Pardes = struct { .normal => edit.enterInsert(p, &pane.body, .at, 1), .insert => { edit.exitInsert(p, &pane.body); - if (pane.isTerminal()) panes.Terminal.enterTty(p, id); + if (pane.isTerminal()) panes.terminal.enterTty(p, id); }, } } @@ -5960,7 +5960,7 @@ pub const Pardes = struct { if (pane.body.mode == .tty) { pane.body.mode = .normal; pane.body.normal.clear(); - } else panes.Terminal.enterTty(p, id); + } else panes.terminal.enterTty(p, id); } /// Type `keys` again (a macro, `.`): through the modal handling as @@ -6079,7 +6079,7 @@ pub const Pardes = struct { return exec.runBuiltin(p, .Last, p.active, "", null); if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and exec.takesCommandLine(p, p.active)) return exec.runBuiltin(p, .Last, p.active, "", null); - panes.Terminal.followOutput(pane); // typing snaps back to live output + panes.terminal.followOutput(pane); // typing snaps back to live output // Paste stays the window's, the one exception to forwarding a raw // tty's keys: Ctrl-V types the register at the program and // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, @@ -6094,7 +6094,7 @@ pub const Pardes = struct { // Ctrl-V a black hole in every full-screen application. if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.active, pane, text); } - return panes.Terminal.forwardKey(p, p.active, key); + return panes.terminal.forwardKey(p, p.active, key); } if (p.leader_on) return p.leaderKey(key); if (p.ctrl_w_pending) { @@ -6247,7 +6247,7 @@ pub const Pardes = struct { edit.exitInsert(p, t) else edit.handleInsert(p, t, key), - .tty => panes.Terminal.forwardKey(p, p.active, key), + .tty => panes.terminal.forwardKey(p, p.active, key), } // `.`'s log: the keys of the normal command that entered insert // mode, then everything typed until it is left @@ -6738,7 +6738,7 @@ pub const Pardes = struct { errdefer p.gpa.free(path); const history = try panes.File.History.create(p.gpa); errdefer p.gpa.destroy(history); - const pane = try panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); errdefer p.gpa.destroy(pane); try p.deinitPane(p.panes[0].?); p.panes[0] = null; @@ -7086,7 +7086,7 @@ pub const Pardes = struct { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { - panes.Terminal.resizeGrid(pane, p.gpa, cols, rows); + panes.terminal.resizeGrid(pane, p.gpa, cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; @@ -7095,12 +7095,12 @@ pub const Pardes = struct { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } - panes.Terminal.releasePendingCommandIfReady(p, id, pane); + panes.terminal.releasePendingCommandIfReady(p, id, pane); // The greeting `ls` of a new terminal in a directory is typed at // its shell's FIRST prompt, or never: typed later it would land // in whatever runs then, or in the middle of a line someone - // typed (panes.Terminal.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.Terminal.greeting(pane)) { + // typed (panes.terminal.greeting). + if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.terminal.greeting(pane)) { .wait => {}, .never => pane.greet = false, .now => { @@ -7381,7 +7381,7 @@ test "argv naming nothing boots an errors pane rather than failing the launch" { } test "raw terminal cursor obeys visibility without hiding modal and tag cursors" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -7426,7 +7426,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" } test "raw terminal cursor follows its active row only while that row is visible" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; for ([_]bool{ false, true }) |tag_bottom| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); @@ -7445,13 +7445,13 @@ test "raw terminal cursor follows its active row only while that row is visible" try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); try std.testing.expectEqual(body_y + 2, live.y); - panes.Terminal.scrollGrid(pane, -1); + panes.terminal.scrollGrid(pane, -1); const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, scrolled.x); try std.testing.expectEqual(live.y + 1, scrolled.y); - panes.Terminal.scrollGrid(pane, -@as(i32, pane.rows)); + panes.terminal.scrollGrid(pane, -@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); - panes.Terminal.followOutput(pane); + panes.terminal.followOutput(pane); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, returned.x); try std.testing.expectEqual(live.y, returned.y); @@ -7895,31 +7895,31 @@ test "tty output follows only from the bottom" { p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const bottom = panes.Terminal.scrollbar(sp).offset; + const bottom = panes.terminal.scrollbar(sp).offset; try std.testing.expect(bottom > 0); // Scrolled back, the reader stays put however much the shell prints. sp.scrollBy(-10); p.sync(); - const parked = panes.Terminal.scrollbar(sp).offset; + const parked = panes.terminal.scrollbar(sp).offset; try std.testing.expect(parked < bottom); for (60..70) |i| { var buf: [32]u8 = undefined; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - try std.testing.expectEqual(parked, panes.Terminal.scrollbar(sp).offset); + try std.testing.expectEqual(parked, panes.terminal.scrollbar(sp).offset); // Typing snaps back to live output, so nobody types blind. p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); p.sync(); - try std.testing.expect(panes.Terminal.scrollbar(sp).offset > parked); + try std.testing.expect(panes.terminal.scrollbar(sp).offset > parked); // ...and from there output follows again. - const live = panes.Terminal.scrollbar(sp).offset; + const live = panes.terminal.scrollbar(sp).offset; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); p.sync(); - try std.testing.expect(panes.Terminal.scrollbar(sp).offset > live); + try std.testing.expect(panes.terminal.scrollbar(sp).offset > live); } test "Esc back into a file leaves its view where it was" { @@ -8135,7 +8135,7 @@ test "an unasked desktop paste reaches a tty pane's program, not its buffer" { _ = drainWrites(p, &buf); const pane = p.panes[0].?; - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); // No request behind it: the window manager's own paste, or SDL answering a // Ctrl-Shift-V the desktop handled. It still has to reach the shell. p.update(.{ .paste = "ls -la" }); @@ -8153,7 +8153,7 @@ test "a paste larger than the effect ring reaches the program whole and in order const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @@ -8166,7 +8166,7 @@ test "a paste larger than the effect ring reaches the program whole and in order test "a bracketed paste larger than the ring still closes its bracket" { if (platform == .web) return; - if (comptime !panes.Terminal.enabled) return; + if (comptime !panes.terminal.enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8174,10 +8174,10 @@ test "a bracketed paste larger than the ring still closes its bracket" { const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expect(panes.Terminal.bracketedPaste(p.panes[0].?)); + try std.testing.expect(panes.terminal.bracketedPaste(p.panes[0].?)); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @memset(text, 'z'); @@ -8197,7 +8197,7 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @@ -8227,14 +8227,14 @@ test "leaving tty hides the prompt and keeps the command typed at it" { const rowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const rows = panes.Terminal.shellRows(pp, pane) catch return null; + const rows = panes.terminal.shellRows(pp, pane) catch return null; for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; } }.at; const bodyRowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const body = panes.Terminal.bodyText(pp.scratch.allocator(), pane) catch return null; + const body = panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null; var it = std.mem.splitScalar(u8, body, '\n'); while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; @@ -8290,7 +8290,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" p.shell_rows.stale = true; // The command shows LEFT-HUGGED, so its column 3 is the '3'... - const rows = try panes.Terminal.shellRows(p, sp); + const rows = try panes.terminal.shellRows(p, sp); var row: i32 = 0; const at = for (rows, 0..) |r, i| { if (std.mem.indexOf(u8, r, "0123456789") != null) break i; @@ -8304,7 +8304,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" sp.body.cur_col = 3; sp.body.cur_pinned = true; while (p.nextEffect()) |_| {} - panes.Terminal.enterTty(p, shell); + panes.terminal.enterTty(p, shell); // The walk is arrow keys the shell understands. Seven lefts: readline's // cursor sits past the '9' and the click was on the '3'. @@ -8347,7 +8347,7 @@ test "board heap: every inline ring the board pays for still fits its budget" { const effect_ring = 128 * @sizeOf(Effect); // ...and the undo history, the largest in `Pane` once the terminal is out: // 16 snapshots on the board against 256 on a desktop. - const undo_history = 2 * 16 * @sizeOf(panes.Terminal.Snapshot); + const undo_history = 2 * 16 * @sizeOf(panes.terminal.Snapshot); const grid = @as(usize, board_cols) * board_rows * (2 * @sizeOf(Cell) + @sizeOf(PanelCellDiff)); // Each of the three separately, so a failure names the one that grew @@ -8475,7 +8475,7 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "more output\r\n" } }); try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); - panes.Terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); + panes.terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); } diff --git a/src/terminal.zig b/src/terminal.zig new file mode 100644 index 00000000..c99a92a6 --- /dev/null +++ b/src/terminal.zig @@ -0,0 +1,2670 @@ +//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! typed over shell rows, and the Filter that recolours output to the theme. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const Surface = pardes.Surface; +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const dump = @import("dump.zig"); +const Key = pardes.Key; +const Pane = panes.Pane; +const EditText = panes.EditText; +const File = panes.File; + +pub const enabled = pardes.terminal_panes; +const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; + +pub const history_max = if (enabled) 64 else 8; + +pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; +pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; + +/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). +pub const prompt_aid = "pardes"; + +/// ghostty's handler, plus where the shell is in its command cycle as +/// its OSC 133 marks tell it: ghostty parses D's exit status and drops +/// it, and /pane//pty/run waits on exactly that. Only marks carrying +/// pardes's own `aid` move it, so fish's native marks, a nested shell's +/// and a stray `133;D` in some file being printed all pass it by. +pub const MarkedHandler = if (enabled) struct { + inner: ghostty_vt.TerminalStream.Handler, + phase: enum { none, prompt, input, running } = .none, + /// Counts commands started (C at the input phase). + started: u32 = 0, + /// Counts prompts drawn (B), so a line the shell refused without + /// running (a fish syntax error: no C, no D, a new prompt) shows. + prompts: u32 = 0, + /// D marks outside a running command: the shell handled a line + /// without starting it (bash on a syntax error prints no C). + declined: u32 = 0, + /// The newest prompt continues an unfinished line (bash's PS2, marked + /// `k=c`): the shell still holds the start of the command. + continuation: bool = false, + /// Where the newest command's output began (its C) and ended (its + /// D) on the primary screen, pinned so scrolling keeps them. + out_start: ?*ghostty_vt.Pin = null, + out_end: ?*ghostty_vt.Pin = null, + /// The running command's output was erased under it -- a clear, ED 3, + /// a reset -- so the pins no longer span what it printed: ED 3 moves + /// a pin to the next page without flagging it `garbage` + /// (PageList.erasePage). + lost: bool = false, + + /// The newest command to end: which one, and its status if given. + finished: ?struct { seq: u32, status: ?i32 } = null, + + const Action = ghostty_vt.TerminalStream.Action; + + /// Move one of the output pins to the cursor. Only the primary screen + /// is pinned: a command's own full-screen display is not its output. + fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (!now or self.inner.terminal.screens.active_key != .primary) return; + slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; + } + + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { + if (comptime action == .semantic_prompt) mark: { + const aid = value.readOption(.aid) orelse break :mark; + if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; + switch (value.action) { + .fresh_line_new_prompt => { + self.phase = .prompt; + self.continuation = value.readOption(.prompt_kind) == .continuation; + }, + .end_prompt_start_input => { + self.phase = .input; + self.prompts +%= 1; + }, + // bash's DEBUG trap also fires on its own PROMPT_COMMAND, + // outside the input phase; only a C that ends input counts + .end_input_start_output => if (self.phase == .input) { + self.phase = .running; + self.started +%= 1; + self.lost = false; + self.pinCursor(&self.out_start, true); + self.pinCursor(&self.out_end, false); + }, + .end_command => if (self.phase == .running) { + self.phase = .none; + self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + self.pinCursor(&self.out_end, true); + } else { + self.declined +%= 1; + }, + else => {}, + } + } + if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { + if (self.phase == .running) self.lost = true; + } + self.inner.vt(action, value); + } + + pub fn deinit(self: *@This()) void { + self.inner.deinit(); + } +} else void; + +pub const Replay = struct { + bytes: [1024 * 1024]u8 = undefined, + head: usize = 0, + len: usize = 0, +}; + +pub const State = struct { + vt: VtSlot, + stream: StreamSlot, + replay: Replay, + reply: [256]u8 = undefined, + reply_len: u16 = 0, +}; + +const GColor = ghostty_vt.color; + +const FilterPaletteKey = struct { + bg: GColor.RGB, + fg: GColor.RGB, + base: [16]GColor.RGB, +}; + +pub const FilterPalette = if (enabled) LivePalette else struct {}; + +const LivePalette = struct { + key: ?FilterPaletteKey = null, + colors: GColor.Palette = GColor.default, + + fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { + const bg = asGhostRgb(theme.bg orelse theme.tag_bg); + const fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var base: [16]GColor.RGB = undefined; + if (theme.palette) |palette| { + for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); + } else { + const synthesized = [16][3]u8{ + theme.bg orelse theme.tag_bg, + theme.kw, + theme.str, + theme.num, + theme.box, + theme.sel_bg, + theme.comment, + theme.fg orelse theme.tag_fg, + theme.lineno, + theme.kw, + theme.str, + theme.num, + theme.scroll_thumb, + theme.sel_fg, + theme.tag_fg, + theme.fg orelse theme.tag_fg, + }; + for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); + } + + const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; + if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; + + var seed = GColor.default; + for (base, 0..) |rgb, i| seed[i] = rgb; + self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); + self.key = key; + return &self.colors; + } +}; + +fn asGhostRgb(rgb: [3]u8) GColor.RGB { + return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; +} + +fn asPardesColor(rgb: GColor.RGB) pardes.Color { + return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; +} + +/// 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: panes.Text.CharSel, +}; + +pub const PendingCommand = struct { + bytes: []u8 = &.{}, + wait: enum { none, spawn, input } = .none, +}; + +pub fn armShellSpawn(pane: *Pane) void { + if (comptime !enabled) return; + std.debug.assert(pane.pending_command.bytes.len == 0); + pane.pending_command.wait = .spawn; +} + +/// Remembers a line pardes types into this terminal as the command it +/// started, for Kill: it runs from the shell's next C mark to its D. +/// ponytail: of several lines queued for a shell not up yet, only the last +/// is remembered, as the first of them. +pub fn noteCommand(pane: *Pane, line: []const u8) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; + var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; + sent.len = @intCast(@min(word.len, sent.word.len)); + @memcpy(sent.word[0..sent.len], word[0..sent.len]); + pane.sent_command = sent; +} + +/// Whether the command pardes last typed here is running now. +pub fn commandRunning(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const sent = pane.sent_command orelse return false; + const marks = &state.stream.handler; + return marks.phase == .running and marks.started == sent.seq; +} + +pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { + if (pane.pending_command.wait == .none) return false; + const old_len = pane.pending_command.bytes.len; + const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); + const bytes = if (old_len == 0) + try pane.gpa.alloc(u8, new_len) + else + try pane.gpa.realloc(pane.pending_command.bytes, new_len); + @memcpy(bytes[old_len..][0..command.len], command); + bytes[new_len - 1] = '\r'; + pane.pending_command.bytes = bytes; + pane.greet = false; + return true; +} + +pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { + const pane = p.panes[id] orelse return; + if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; + if (prompt_marks) { + pane.pending_command.wait = .input; + releasePendingCommand(p, id, pane, false); + } else { + pane.greet = false; + releasePendingCommand(p, id, pane, true); + } +} + +pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { + if (pane.pending_command.wait == .input) + releasePendingCommand(p, id, pane, promptInputReady(pane)); +} + +fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { + if (!ready) return; + const bytes = pane.pending_command.bytes; + pane.pending_command = .{}; + if (bytes.len > 0) { + p.emitWrite(id, bytes); + pane.gpa.free(bytes); + } +} + +pub fn deinitPendingCommand(pane: *Pane) void { + if (pane.pending_command.bytes.len > 0) + pane.gpa.free(pane.pending_command.bytes); + pane.pending_command = .{}; +} + +pub fn terminalIo() std.Io { + return if (comptime !pardes.hosted) + std.Io.failing + else + std.Io.Threaded.global_single_threaded.io(); +} + +/// The three numbers ghostty's scrollbar reports; all zero without an emulator. +pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; + +pub fn scrollbar(pane: *const Pane) Scrollbar { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const sb = state.vt.screens.active.pages.scrollbar(); + return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; +} + +/// The emulator's viewport offset, in SHELL rows: the top of what it shows. +pub fn gridOffset(pane: *const Pane) i32 { + return @intCast(scrollbar(pane).offset); +} + +/// Where the emulator itself puts the cursor, in active-area cells — the origin +/// without one, which is where an empty pane's cursor belongs anyway. +pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; + +pub fn gridCursor(pane: *const Pane) GridCursor { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const cur = state.vt.screens.active.cursor; + return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; +} + +pub fn visibleCursor(pane: *const Pane) ?GridCursor { + if (comptime !enabled) return null; + const state = pane.terminal orelse return null; + if (!state.vt.modes.get(.cursor_visible)) return null; + const cur = state.vt.screens.active.cursor; + const sb = scrollbar(pane); + const row = sb.total - sb.len + cur.y; + if (row < sb.offset or row - sb.offset >= sb.len) return null; + return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; +} + +/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). +pub fn scrollGrid(pane: *Pane, delta: i32) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.{ .delta_row = delta }); +} + +/// Is the viewport already showing the last row of output? +pub fn atBottom(pane: *const Pane) bool { + if (comptime !enabled) return true; + const sb = scrollbar(pane); + return sb.offset + sb.len >= sb.total; +} + +/// Snap the viewport back onto live output. +pub fn followOutput(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.active); +} + +/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping +/// a scrollback; the next resize retries with the same numbers. +pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + if (cols != pane.cols) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; +} + +/// DECSET 2004: the program wants its pastes bracketed. +pub fn bracketedPaste(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.bracketed_paste); +} + +/// The program tracks the mouse itself, so a click in its body is its event. +pub fn reportsMouse(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const m = &state.vt.modes; + return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); +} + +/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. +pub fn mouseFormatSgr(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.mouse_format_sgr); +} + +/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body +/// reads and `Save` writes out. Logical lines: rows the terminal wrapped +/// are joined again (ghostty's wrap flags, as pty/run's output is), and +/// the last line ends with a newline. +pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { + if (comptime !enabled) return &.{}; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try writeScreenText(pane, &out.writer); + return out.toOwnedSlice(); +} + +fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const screen = state.vt.screens.active; + const br = screen.pages.getBottomRight(.screen) orelse return; + var both: TeeWriter = .{ .a = w }; + try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); + if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); +} + +/// Passes bytes through, remembering how many and the last one. +const TeeWriter = struct { + a: *std.Io.Writer, + count: usize = 0, + final: u8 = 0, + writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, + + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); + var n: usize = 0; + for (data[0 .. data.len - 1]) |bytes| { + try t.a.writeAll(bytes); + t.note(bytes); + n += bytes.len; + } + const pattern = data[data.len - 1]; + for (0..splat) |_| { + try t.a.writeAll(pattern); + t.note(pattern); + n += pattern.len; + } + return n; + } + + fn note(t: *TeeWriter, bytes: []const u8) void { + if (bytes.len == 0) return; + t.count += bytes.len; + t.final = bytes[bytes.len - 1]; + } +}; + +/// How long `screenTextAlloc` would be, counted without keeping it: the +/// length a terminal's body reads as, which its ctl line reports. +pub fn screenTextLen(pane: *Pane) usize { + if (comptime !enabled) return 0; + var buf: [256]u8 = undefined; + var counting: std.Io.Writer.Discarding = .init(&buf); + writeScreenText(pane, &counting.writer) catch return 0; + return @intCast(counting.fullCount()); +} + +/// Release the emulator's heap. The Pane allocation itself is the core's. +pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.stream.deinit(); + state.vt.deinit(gpa); + gpa.destroy(state); + pane.terminal = null; +} + +/// Allocate the live emulator half of a terminal pane. Slot ownership, serial +/// assignment, and spawn effects remain core lifecycle invariants. +pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try createDoc(gpa, cols, rows); + errdefer gpa.destroy(pane); + if (comptime !enabled) return pane; + const state = try gpa.create(State); + errdefer gpa.destroy(state); + state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ + .cols = cols, + .rows = rows, + .max_scrollback = 16 * 1024 * 1024, + }); + state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); + state.replay.head = 0; + state.replay.len = 0; + state.reply_len = 0; + state.stream.handler.inner.effects.write_pty = ptyReport; + state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + pane.terminal = state; + pane.tty_filter = true; + return pane; +} + +pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try gpa.create(Pane); + pane.* = .{ + .gpa = gpa, + .cols = cols, + .rows = rows, + }; + return pane; +} + +/// Where a restored terminal's history ends and its new shell begins. +pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; + +/// Rebuild a dump's terminal emulator from its recorded output. `live`: a +/// shell will be spawned into it, so the history is marked off from what +/// that shell prints and the pane waits for it like any new terminal. +/// Registration and tag/cwd policy stay with the core; raw VT replay and +/// viewport restoration belong here. +pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { + const terminal = src.terminal.?; + if (comptime !enabled) { + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + errdefer p.gpa.destroy(pane); + if (terminal.stream.len > 0) + pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; + return pane; + } + // An older dump's raw output tail cannot come back live: cut off mid + // redraw, or written at sizes the pane no longer has, it replays as + // garbage. Its rendered text can. + const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; + const bytes = if (legacy_text) + try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") + else if (terminal.stream_b64.len > 0) + try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) + else + &.{}; + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + if (live) { + if (bytes.len > 0) { + ingest(pane, bytes); + ingest(pane, restored_banner); + } + followOutput(pane); + // A view left scrolled back stays on what it was showing: the + // banner's line breaks scrolled a full screen by that many more. + if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); + armShellSpawn(pane); + } else if (bytes.len > 0) { + ingest(pane, bytes); + followOutput(pane); + if (src.scroll > 0) + scrollGrid(pane, -@as(i32, @intCast(src.scroll))); + } + return pane; +} + +/// Feed the emulator and retain the bounded suffix a dump can replay. Live +/// output and restoration share this byte path, then apply different views. +fn ingest(pane: *Pane, bytes: []const u8) void { + const state = pane.terminal.?; + const replay = &state.replay; + if (bytes.len >= replay.bytes.len) { + const kept = bytes[bytes.len - replay.bytes.len ..]; + @memcpy(&replay.bytes, kept); + replay.head = 0; + replay.len = replay.bytes.len; + } else { + const overflow = bytes.len -| (replay.bytes.len - replay.len); + replay.head = (replay.head + overflow) % replay.bytes.len; + replay.len -= overflow; + const tail = (replay.head + replay.len) % replay.bytes.len; + const first = @min(bytes.len, replay.bytes.len - tail); + @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); + @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); + replay.len += bytes.len; + } + state.stream.nextSlice(bytes); +} + +/// Return the replay ring in chronological order. Wrapped records are copied +/// into `allocator`; contiguous records remain a borrowed slice of the pane. +fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { + const state = pane.terminal orelse return &.{}; + const replay = &state.replay; + if (replay.len == 0) return &.{}; + if (replay.head + replay.len <= replay.bytes.len) + return replay.bytes[replay.head..][0..replay.len]; + const out = try allocator.alloc(u8, replay.len); + const first = replay.bytes.len - replay.head; + @memcpy(out[0..first], replay.bytes[replay.head..]); + @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); + return out; +} + +test "replay ownership is terminal-only and construction rolls back on allocation failure" { + const Case = struct { + fn run(gpa: std.mem.Allocator, terminal: bool) !void { + const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqual(terminal and enabled, pane.terminal != null); + } + }; + try std.testing.expect(@sizeOf(Pane) < 128 * 1024); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); +} + +test "document construction allocates only the pane and has inert terminal defaults" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const allocator = failing.allocator(); + const pane = try createDoc(allocator, 40, 12); + defer allocator.destroy(pane); + defer deinitEmulator(pane, allocator); + try std.testing.expect(pane.terminal == null); + try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); + try std.testing.expectEqual(@as(usize, 0), failing.resize_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expect(!bracketedPaste(pane)); + try std.testing.expect(!reportsMouse(pane)); + try std.testing.expect(!mouseFormatSgr(pane)); + try std.testing.expect(!promptInputReady(pane)); + scrollGrid(pane, 100); + followOutput(pane); + resizeGrid(pane, allocator, 80, 24); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); + try std.testing.expectEqualStrings("", try replayBytes(pane, allocator)); + try std.testing.expect(!failing.has_induced_failure); +} + +test "terminal state keeps parser fragments and sends emulator replies through its owner" { + if (comptime !enabled) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + const state = pane.terminal.?; + try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); + while (p.nextEffect()) |effect| { + if (effect == .write) return error.PrematureTerminalReply; + } + p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); + var replies: usize = 0; + while (p.nextEffect()) |effect| { + if (effect != .write) continue; + try std.testing.expectEqual(@as(u8, 0), effect.write.pane); + try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); + replies += 1; + } + try std.testing.expectEqual(@as(usize, 1), replies); + try std.testing.expectEqual(@as(u16, 0), state.reply_len); + try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); +} + +test "replay keeps a bounded chronological suffix across large writes and wrapping" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const pane = try create(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); + ingest(pane, "hello"); + const small = try replayBytes(pane, gpa); + try std.testing.expectEqualStrings("hello", small); + try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); + + const capacity = pane.terminal.?.replay.bytes.len; + const input = try gpa.alloc(u8, capacity + 7); + defer gpa.free(input); + @memset(input, 0); + const ending = "\x1b[31mred\x1b[0m\r\n"; + @memcpy(input[input.len - ending.len ..], ending); + ingest(pane, input); + try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); + ingest(pane, "next\r\n"); + const wrapped = try replayBytes(pane, gpa); + defer gpa.free(wrapped); + try std.testing.expectEqual(capacity, wrapped.len); + try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); + try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); +} + +test "replay restores terminal cells from the retained stream" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + defer gpa.free(encoded); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = pane.cols, + .rows = pane.rows, + .terminal = .{ .stream_b64 = encoded }, + }, false); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + const before = try screenTextAlloc(pane, gpa); + defer gpa.free(before); + const after = try screenTextAlloc(restored, gpa); + defer gpa.free(after); + try std.testing.expectEqualStrings(before, after); + try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); +} + +test "a restored command pane comes back finished, its command not run again" { + if (comptime !enabled or pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const cmd = p.freeSlot().?; + _ = try p.newCommand(cmd, "/tmp", "make test"); + feedOutput(p, p.panes[cmd].?, "ok\r\n"); + p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); + try dump.dumpState(p); + const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); + defer restored.deinit(); + var spawns: usize = 0; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => spawns += 1, + else => {}, + }; + try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command + const again = for (restored.panes) |slot| { + if (slot) |pane| if (pane.command != null) break pane; + } else return error.CommandPaneLost; + try std.testing.expectEqualStrings("make test", again.command.?); + try std.testing.expect(again.command_done); + try std.testing.expectEqual(@as(?u8, 2), again.command_status); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); +} + +test "a restored terminal keeps its history above a marker and gets a shell where it was" { + if (comptime !enabled or pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "old output\r\n$ ls\r\n"); + try pane.setOwnedCwd("/tmp"); + pane.shell = try gpa.dupe(u8, "bash"); // `Tty bash`: it comes back as bash + try dump.dumpState(p); + const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + defer restored.deinit(); + var spawned = false; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), + else => {}, + }; + try std.testing.expect(spawned); + const again = restored.panes[0].?; + try std.testing.expectEqualStrings("bash", again.shell.?); + try std.testing.expect(again.command == null); + try std.testing.expectEqual(.spawn, again.pending_command.wait); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; + const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; + try std.testing.expect(old_at < mark_at); +} + +test "an older dump comes back live from its rendered text, not its raw output tail" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + // A tail cut mid-redraw: relative moves from a cursor it never set. + const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); + defer gpa.free(tail); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = 40, + .rows = 12, + .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, + }, true); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + defer deinitPendingCommand(restored); + const text = try screenTextAlloc(restored, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); +} + +/// Record and parse one live pty read, invalidate its motion surface, and +/// follow it only when the body (possibly parked under a tag edit) is raw. +pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { + // There are no pty reads at all without an emulator to parse them into. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or + pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or + pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, so + // a reader scrolled back into the scrollback stays where they scrolled. + const at_bottom = atBottom(pane); + if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); + p.shell_rows.markStale(pane); + if (pane.body.mode == .tty and at_bottom) followOutput(pane); +} + +const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; +const PositionPin = struct { + target: *i32, + row: RowPin, + overlay: ?*EditBuffer, + edit_row: ?i32 = null, +}; + +fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { + if (row < 0) return .{ .offset = row }; + const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); + var left = pages.total_rows - 1 - bounded; + var node = pages.pages.last.?; + while (left >= node.rows()) { + left -= node.rows(); + node = node.prev.?; + } + const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { + failed.* = true; + return .{}; + }; + return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; +} + +fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { + const pin = row.pin orelse return row.offset; + const alive = pages orelse return 0; + if (pin.garbage) return 0; + var after: usize = 0; + var node = alive.pages.last; + while (node) |item| : (node = item.prev) { + if (item == pin.node) + return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; + after += item.rows(); + } + return 0; +} + +fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { + var grid = target.*; + if (overlay) |edit| { + const lines: i32 = @intCast(modal.lineCount(edit.text)); + if (grid >= edit.row and grid < edit.row +| lines) + return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; + if (grid > edit.row) grid = grid -| lines +| edit.rows; + } + return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; +} + +fn pointerRowCount(pane: *const Pane) usize { + var count: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + count += rows.len; + }; + return count; +} + +fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { + const screens = &pane.terminal.?.vt.screens; + const key = screens.active_key; + const generation = screens.generation(key); + const pages = &screens.active.pages; + const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; + var groups: [history_max * 2 + 1]Group = undefined; + groups[0] = .{ + .overlay = if (pane.ovl) |*overlay| overlay else null, + .cursor = &pane.body.cur_row, + .selection = &pane.body.vsel, + }; + var ngroups: usize = 1; + for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { + for (history) |*snapshot| { + groups[ngroups] = .{ + .overlay = if (snapshot.ovl) |*overlay| overlay else null, + .cursor = &snapshot.cur_row, + .selection = &snapshot.vsel, + }; + ngroups += 1; + } + } + const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; + var spans: [groups.len]Span = undefined; + var nspans: usize = 0; + var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; + var npositions: usize = 0; + var failed = false; + for (groups[0..ngroups]) |group| { + if (group.overlay) |overlay| { + spans[nspans] = .{ + .overlay = overlay, + .start = trackRow(pages, overlay.row, &failed), + .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), + }; + nspans += 1; + } + positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); + npositions += 1; + if (group.selection.active) { + positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); + npositions += 1; + } + } + const overlay = groups[0].overlay; + var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; + var nextra: usize = 0; + if (pane.body.msel.active) { + extra[nextra] = &pane.body.msel.r0; + extra[nextra + 1] = &pane.body.msel.r1; + nextra += 2; + } + for (pane.body.sels[0..pane.body.nsel]) |*selection| { + extra[nextra] = &selection.row; + extra[nextra + 1] = &selection.arow; + nextra += 2; + } + if (pane.body.last_edit) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + if (pane.look_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + for (extra[0..nextra]) |target| { + positions[npositions] = trackPosition(pages, target, overlay, &failed); + npositions += 1; + } + const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; + defer if (pointer_positions) |pins| pane.gpa.free(pins); + if (pointer_positions) |pins| { + var index: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + for (rows) |*row| { + pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); + index += 1; + } + }; + } else failed = true; + ingest(pane, bytes); + // RIS can destroy the alternate screen and every pin it owned. + const alive = if (screens.generation(key) == generation) pages else null; + var moved = false; + var pointer_rows_lost = alive == null or pointer_positions == null; + if (pointer_positions) |pins| for (pins) |position| { + if (alive != null) if (position.row.pin) |pin| { + if (pin.garbage) pointer_rows_lost = true; + }; + }; + for (spans[0..nspans]) |span| { + const start = pinnedRow(alive, span.start); + const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); + moved = moved or start != span.overlay.row or rows != span.overlay.rows; + span.overlay.row = start; + span.overlay.rows = rows; + if (alive) |owner| { + if (span.start.pin) |pin| owner.untrackPin(pin); + if (span.end.pin) |pin| owner.untrackPin(pin); + } + } + for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { + var row = pinnedRow(alive, position.row); + if (position.overlay) |edit| { + if (position.edit_row) |relative| { + row = edit.row +| relative; + } else if (row > edit.row) { + row = if (row < edit.row +| edit.rows) + edit.row + else + row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); + } + } + moved = moved or row != position.target.*; + position.target.* = row; + if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); + }; + if (pointer_rows_lost) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. + if (failed) { + const message = "terminal edit position reset: out of memory"; + @memcpy(pane.msg[0..message.len], message); + pane.msg_len = message.len; + } +} + +test "raw terminal output needs no position tracking allocations" { + if (comptime !enabled) return error.SkipZigTest; + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + feedOutput(p, pane, "warm"); + const allocations = failing.alloc_index; + failing.fail_index = allocations; + const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); + feedOutput(p, pane, " output"); + try std.testing.expectEqual(allocations, failing.alloc_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); +} + +/// A full-screen program has the emulator on its alternate screen. +pub fn onAlternateScreen(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key == .alternate; +} + +/// Whether a new terminal's greeting may be typed now: only at the shell's +/// first prompt (pardes's own marks: no command started; a prompt drawn +/// again for a resize is the same first prompt), with nothing +/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or +/// been typed first, and an `ls` then would go into it. A shell pardes +/// cannot mark has no first prompt to find, and is never greeted. +pub fn greeting(pane: *const Pane) enum { wait, now, never } { + if (comptime !enabled) return .never; + if (pane.fs.unmarked) return .never; + // Text typed into the edit buffer that stands in for the prompt row. + if (pane.ovl) |o| if (o.text.len > 0) return .never; + const state = pane.terminal orelse return .wait; + const marks = &state.stream.handler; + // (Not `declined`: bash's first prompt comes after a D of its own.) + if (marks.started > 0) return .never; + // At a prompt's input (ghostty's semantic marks, pardes's or the + // shell's own), before any command pardes's marks saw run. + if (!promptInputReady(pane)) return .wait; + return if (promptInputEmpty(pane)) .now else .never; +} + +pub fn promptInputReady(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key != .alternate and + state.vt.screens.active.cursor.semantic_content == .input; +} + +pub const CommandOutput = struct { + /// Owned by the caller. + text: [:0]const u8, + /// Whether `text` starts where the command did. It does not when that + /// start is not there to read: cut off by `max_rows`, scrolled out of + /// the history (ghostty moved the pin to the oldest row it kept and + /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or + /// never pinned (a C or D that came on the alternate screen). + whole: bool, +}; + +/// What the newest finished command printed: the screen text between its +/// C and D marks, read from at most `max_rows` rows above its end, so a +/// command that printed the whole history costs no more than its tail. +/// The shell exited in the middle of a command (its `exit 3`): no end mark +/// will come, so the command's output ends where the cursor is. +pub fn endOutputHere(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const marks = &state.stream.handler; + if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); +} + +pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { + // Unless there is text to read, whether the nothing it printed is the + // whole of it. + const whole = if (comptime enabled) printed: { + const state = pane.terminal orelse break :printed true; + const marks = &state.stream.handler; + const start = marks.out_start orelse break :printed false; + const end = marks.out_end orelse break :printed false; + const screen = state.vt.screens.get(.primary) orelse break :printed false; + if (end.garbage) break :printed false; + var whole = !marks.lost and !start.garbage; + // D is where the next prompt begins: the output ends a cell before. + const last = end.leftWrap(1) orelse break :printed whole; + if (start.eql(end.*) or last.before(start.*)) break :printed whole; + var from = start.*; + if (last.up(max_rows)) |floor| if (from.before(floor)) { + from = floor; + from.x = 0; + whole = false; + }; + return .{ + .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), + .whole = whole, + }; + } else true; + return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; +} + +/// At a prompt with nothing typed on its line: no input left of the +/// cursor and none under it (text typed and then Ctrl-A'd starts at the +/// cursor). Nothing further right counts: that is where fish draws a +/// right prompt, and fish suggests nothing on an empty line. +pub fn promptInputEmpty(pane: *const Pane) bool { + if (comptime !enabled) return false; + if (!promptInputReady(pane)) return false; + const cursor = &pane.terminal.?.vt.screens.active.cursor; + const row = cursor.page_pin.cells(.all); + for (row[0..@min(cursor.x + 1, row.len)]) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) return false; + return true; +} + +/// Encode one key for the program that owns a raw terminal and queue its pty +/// write, respecting the application's keyboard protocol and terminal modes. +pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { + if (comptime enabled) { + const pane = p.panes[id] orelse return; + const state = pane.terminal orelse return; + const input = ghostty_vt.input; + const function_keys = comptime keys: { + var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; + for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); + break :keys keys; + }; + const physical: input.Key = switch (key.cp) { + Key.enter => .enter, + Key.backspace => .backspace, + Key.tab => .tab, + Key.escape => .escape, + Key.up => .arrow_up, + Key.down => .arrow_down, + Key.left => .arrow_left, + Key.right => .arrow_right, + Key.home => .home, + Key.end => .end, + Key.page_up => .page_up, + Key.page_down => .page_down, + Key.delete => .delete, + Key.insert => .insert, + Key.print_screen => .print_screen, + Key.scroll_lock => .scroll_lock, + Key.pause => .pause, + Key.menu => .context_menu, + Key.f1...Key.f25 => function_keys[key.cp - Key.f1], + else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + }; + var utf8: [4]u8 = undefined; + const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + // A key with no text of its own types its code point only when that + // is a character: the kitty keyboard protocol numbers function and + // modifier keys in the private use area (F3 is U+E016), and a shell + // was typed those as junk. + const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) + utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] + else + ""; + var buffer: [256]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + input.encodeKey(&writer, .{ + .key = physical, + .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, + .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .utf8 = text, + .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + }, options: { + var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); + // fromTerminal cannot know this one and says so, defaulting to + // "option is not alt" — right for an app that lets macOS do the + // unicode translation and hands the encoder the composed text. + // Every pardes shell resolves the modifier itself and hands the + // core the BASE key with the alt bit and no text at all (see + // PardesView.keyDown, and app.mjs doing the same with the same + // two bits), so by the time this runs alt already means alt. + // Left at the default, a macOS build drops the ESC prefix on + // the floor and forwards Alt-n to the child as a bare `n`. + opts.macos_option_as_alt = .true; + break :options opts; + }) catch return; + if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); + return; + } + var control: [1]u8 = undefined; + const bytes: ?[]const u8 = blk: { + if (key.ctrl) { + if (key.cp >= 'a' and key.cp <= 'z') { + control[0] = @intCast(key.cp - 0x60); + break :blk control[0..1]; + } + // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. + if (key.cp >= '@' and key.cp <= '_') { + control[0] = @intCast(key.cp - 0x40); + break :blk control[0..1]; + } + } + if (key.text.len > 0) break :blk key.text; + break :blk switch (key.cp) { + Key.enter => "\r", + Key.backspace => "\x7f", + Key.tab => "\t", + Key.escape => "\x1b", + Key.up => "\x1b[A", + Key.down => "\x1b[B", + Key.right => "\x1b[C", + Key.left => "\x1b[D", + Key.delete => "\x1b[3~", + else => null, + }; + }; + if (bytes) |encoded| + p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); +} + +pub fn enterTty(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; + if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { + const screen = pane.terminal.?.vt.screens.active; + const goff: i32 = @intCast(screen.pages.scrollbar().offset); + const vp_row = pane.gridRow(pane.body.cur_row) - goff; + if (vp_row < 0) break :handoff; + + var grid_col: i32 = @max(0, pane.body.cur_col); + if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { + if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { + .cut => |cols| grid_col += @intCast(cols), + .keep, .blank => {}, + }; + } + const click_pin = screen.pages.pin(.{ + .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, + }) orelse break :handoff; + const cursor_pin = screen.cursor.page_pin.*; + var prompts = cursor_pin.promptIterator(.left_up, null); + const prompt_pin = prompts.next() orelse break :handoff; + if (click_pin.before(prompt_pin)) break :handoff; + const moves = screen.promptClickMove(click_pin); + for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); + for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); + }; + + pane.body.mode = .tty; + followOutput(pane); // entering raw mode is a request for the live shell + pane.body.msel.active = false; + pane.body.vsel.active = false; + pane.body.nsel = 0; + // The raw renderer follows the live cursor. A captured mouse selection + // keeps its modal endpoint for the next return to editor mode. + pane.body.cur_pinned = selected; + pane.body.select = false; + pane.body.restore_cursor = false; + pane.body.sticky_col = -1; + pane.body.normal.clear(); +} + +// Returned slices remain valid until the next cache rebuild or reset. +pub const RowsCache = struct { + /// whose grid this describes; null = the slot is free + pane: ?*const Pane = null, + /// the rows joined by '\n' — `flatSurface` hands this back verbatim + /// instead of rebuilding the join on every keystroke + text: []const u8 = &.{}, + /// slices INTO `text`, absolute grid rows from 0 + rows: [][]const u8 = &.{}, + /// `text` is a prefix of this: blanking a prompt row shortens the join, + /// and the slack is not worth a second allocation to reclaim + text_alloc: []u8 = &.{}, + stale: bool = false, + + pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.text_alloc.len > 0) gpa.free(c.text_alloc); + if (c.rows.len > 0) gpa.free(c.rows); + c.* = .{}; + } + + /// Free a stale entry. Called at the top of `update`, and nowhere else. + pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.stale) c.reset(gpa); + } + + /// `pane`'s grid moved: the entry no longer describes it. + pub fn markStale(c: *RowsCache, pane: *const Pane) void { + if (c.pane == pane) c.stale = true; + } + + pub fn dropPane(c: *RowsCache, pane: *const Pane) void { + if (c.pane != pane) return; + c.pane = null; + c.stale = true; + } +}; + +const Rows = struct { + text_alloc: []u8, + text: []const u8, + rows: [][]const u8, +}; + +const empty_grid = [1][]const u8{""}; + +/// What LEAVING raw tty mode does to one prompt row, decided from its cells +/// alone. See config.tty_blank for why any of this happens. +const PromptCut = union(enum) { + /// show the row exactly as ghostty dumped it + keep, + /// show nothing at all + blank, + /// drop this many leading COLUMNS — the prompt — and keep the rest, which + /// is what was typed at it + cut: usize, +}; + +fn promptCut(pin: ghostty_vt.Pin) PromptCut { + if (config.tty_blank == .prompt_and_input) return .blank; + const cells = pin.cells(.all); + var cols: usize = 0; + while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; + // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or + // a repaint that has moved on. Nothing here is the prompt, so hide nothing. + if (cols == 0) return .keep; + // ...and all prompt, nothing typed yet: the row is chrome end to end. + if (cols >= cells.len) return .blank; + return .{ .cut = cols }; +} + +pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { + if (comptime !enabled) return 0; + if (row < 0) return 0; + const state = pane.terminal orelse return 0; + const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; + if (pin.rowAndCell().row.semantic_prompt == .none) return 0; + return switch (promptCut(pin)) { + .keep => 0, + .blank => raw.len, + .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), + }; +} + +fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { + const cols = switch (promptCut(pin)) { + .keep => return raw, + .blank => return "", + .cut => |n| n, + }; + const cells = pin.cells(.all); + var at: usize = 0; + var col: usize = 0; + while (col < cols and at < raw.len) { + const cell = &cells[col]; + at = @min(raw.len, at + dumpedBytes(pin, cell)); + // the tail cell of a wide glyph spells nothing of its own + col += if (cell.wide == .wide) @as(usize, 2) else 1; + } + return std.mem.trimEnd(u8, raw[at..], " \t"); +} + +fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { + switch (cell.wide) { + .spacer_head, .spacer_tail => return 0, + .narrow, .wide => {}, + } + var n: usize = switch (cell.content_tag) { + .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( + cell.codepoint(), + ) catch 1, + // A cell carrying only a colour still spells one blank in the dump. + else => 1, + }; + if (cell.content_tag == .codepoint_grapheme) { + if (pin.grapheme(cell)) |extra| for (extra) |cp| { + n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; + }; + } + return n; +} + +pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { + if (comptime !enabled) return &empty_grid; + if (pane.terminal == null) return &empty_grid; + const c = &p.shell_rows; + if (!c.stale and c.pane == pane) return c.rows; + if (c.pane != null) { + c.stale = true; + return (try buildRows(p.scratch.allocator(), p, pane)).rows; + } + const built = try buildRows(p.gpa, p, pane); + c.* = .{ + .pane = pane, + .text = built.text, + .rows = built.rows, + .text_alloc = built.text_alloc, + }; + return c.rows; +} + +/// The full modal motion surface: shell history with the live edit overlay +/// spliced into the rows it covers. +pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { + const rows = try shellRows(p, pane); + if (pane.ovl == null) return rows; + var last = rows.len; + if (pane.ovl) |overlay| + last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); + var count = last; + if (pane.ovl) |overlay| { + if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) + count = count - @min( + @as(usize, @intCast(overlay.rows)), + last - @as(usize, @intCast(overlay.row)), + ) + @max(1, modal.lineCount(overlay.text)); + } + const lines = try p.scratch.allocator().alloc([]const u8, count); + var n: usize = 0; + var grid_row: usize = 0; + while (grid_row < last) : (grid_row += 1) { + if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { + var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); + while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; + grid_row += @intCast(overlay.rows - 1); + continue; + }; + lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; + n += 1; + } + return lines[0..n]; +} + +/// Flatten `cursorLines` without rebuilding the common cached/no-overlay +/// case. Scratch-owned when a join is required. +pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { + const cache = &p.shell_rows; + if (!cache.stale and cache.pane == pane and + lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; + var total: usize = if (lines.len > 0) lines.len - 1 else 0; + for (lines) |line| total += line.len; + const text = try p.scratch.allocator().alloc(u8, total); + var at: usize = 0; + for (lines, 0..) |line, i| { + if (i > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..line.len], line); + at += line.len; + } + return text; +} + +/// Materialize or extend the terminal edit overlay with one exact allocation. +/// Row slices are scratch-owned/borrowed; only the joined text is installed. +pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { + const want_lo = @max(0, @min(lo, hi)); + const want_hi = @max(want_lo, @max(lo, hi)); + const fresh = pane.ovl == null; + const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; + const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); + const up = old.row - want_lo; + const down = want_hi - (old.row + lines - 1); + const extending = fresh or up > 0 or down > 0; + var row0 = old.row; + var covered = old.rows; + var text = old.text; + var owned = false; + if (extending) { + const rows = shellRows(p, pane) catch return null; + row0 = old.row - @max(0, up); + covered = old.rows + @max(0, up) + @max(0, down); + const up_len: usize = @intCast(@max(0, up)); + const down_len: usize = @intCast(@max(0, down)); + const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; + for (parts[0..up_len], 0..) |*part, i| { + const src = @as(usize, @intCast(row0)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + const middle: usize = @intCast(old.row); + parts[up_len] = if (fresh) + (if (middle < rows.len) rows[middle] else "") + else + old.text; + for (parts[up_len + 1 ..], 0..) |*part, i| { + const src = @as(usize, @intCast(old.row + old.rows)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + text = std.mem.join(p.gpa, "\n", parts) catch return null; + owned = true; + } + + const row: usize = @intCast(@max(0, want_lo - row0)); + const line_len: i32 = @intCast(modal.lineSlice(text, row).len); + if (col > line_len) { + const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { + if (owned) p.gpa.free(text); + return null; + }; + @memset(spaces, ' '); + const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) p.gpa.free(text); + return null; + }; + if (owned) p.gpa.free(text); + text = padded; + owned = true; + } + if (owned) { + if (pane.ovl) |overlay| p.gpa.free(overlay.text); + pane.ovl = .{ .row = row0, .rows = covered, .text = text }; + } + return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; +} + +/// Consume a rewritten overlay, freeing the terminal edit text it replaces. +pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { + const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + p.gpa.free(overlay.text); + overlay.text = new; +} + +/// The shell's screen and scrollback (the primary screen, even under a +/// full-screen program) as VT that replays to what was shown: styled +/// text, soft-wrapped lines rejoined so they reflow at another width. +fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { + const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; + var out: std.Io.Writer.Allocating = .init(arena); + try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); + return out.written(); +} + +/// Serialize terminal-only state; the core supplies shared pane metadata. +pub fn dumpPane( + pane: *Pane, + arena: std.mem.Allocator, + tag: []const u8, + body: []const u8, + scroll: usize, +) !dump.Pane { + if (!enabled or pane.terminal == null) { + const text = if (pane.ovl) |overlay| overlay.text else ""; + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .shell = try arena.dupe(u8, pane.shell orelse ""), + .command = try arena.dupe(u8, pane.command orelse ""), + .status = pane.command_status, + .stream = try arena.dupe(u8, text), + .stream_b64 = &.{}, + .cursor = .{ .col = 0, .row = 0 }, + }, + }; + } + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); + const extra = if (pane.ovl) |overlay| overlay.text.len else 0; + const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); + var len: usize = 0; + var lines = std.mem.splitAny(u8, full, "\n"); + var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + var row: i32 = 0; + var skip: i32 = 0; + while (lines.next()) |raw| : (row += 1) { + // Hidden overlay rows still consume prompt pins to keep them aligned. + const prompt = if (pane.body.mode != .tty) prompts.next() else null; + if (skip > 0) { + skip -= 1; + continue; + } + if (row > 0) { + stream[len] = '\n'; + len += 1; + } + if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { + @memcpy(stream[len..][0..overlay.text.len], overlay.text); + len += overlay.text.len; + skip = overlay.rows - 1; + continue; + }; + const shown = if (prompt) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + @memcpy(stream[len..][0..shown.len], shown); + len += shown.len; + } + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .shell = try arena.dupe(u8, pane.shell orelse ""), + .command = try arena.dupe(u8, pane.command orelse ""), + .status = pane.command_status, + .stream = stream[0..len], + .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), + .stream_is_screen = true, + .cursor = .{ + .col = pane.terminal.?.vt.screens.active.cursor.x, + .row = pane.terminal.?.vt.screens.active.cursor.y, + }, + }, + }; +} + +fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); + var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + // split yields one more item than delimiters; the extra final slot is the + // cursor row retained below. + const n_rows = std.mem.count(u8, full, "\n") + 2; + const rows = try alloc.alloc([]const u8, n_rows); + errdefer alloc.free(rows); + // Blanking a prompt row only ever SHORTENS it and the retained cursor row + // adds one separator, so the dump's length plus one bounds the join. + const text = try alloc.alloc(u8, full.len + 1); + errdefer alloc.free(text); + var at: usize = 0; + var n: usize = 0; + var it = std.mem.splitScalar(u8, full, '\n'); + while (it.next()) |raw| { + const shown = if (pit.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + if (n > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..shown.len], shown); + rows[n] = text[at..][0..shown.len]; + at += shown.len; + n += 1; + } + text[at] = '\n'; + at += 1; + rows[n] = text[at..][0..0]; + n += 1; + std.debug.assert(n == n_rows); + return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; +} + +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { + const state = pane.terminal orelse break :vp &.{}; + const screen = state.vt.screens.active; + var tl = screen.pages.getTopLeft(.viewport); + tl.x = 0; + const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; + var rows_out: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const raw = try rows_out.toOwnedSlice(); + var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); + var lines = std.mem.splitScalar(u8, raw, '\n'); + var n: usize = 0; + while (lines.next()) |ln| { + vp[n] = if (pane.body.mode != .tty) + if (prompts.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln + else + ln + else + ln; + n += 1; + } + std.debug.assert(n == vp.len); + break :vp vp; + }; + + const len = fillBody(null, pane, vp); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, vp); + std.debug.assert(filled == out.len); + return out; +} + +pub const BodyRow = union(enum) { + grid: i32, + edit: struct { line: []const u8, idx: usize }, +}; + +const BodyWalk = struct { + pane: *Pane, + goff: i32, + g: i32, + /// the buffer can start above the viewport: drop the lines scrolled past + skip: usize, + n: usize = 0, + lines: ?std.mem.SplitIterator(u8, .scalar) = null, + covered: i32 = 0, + line_idx: usize = 0, + + fn init(pane: *Pane) BodyWalk { + const off = pane.scroll(); + const goff = gridOffset(pane); + return .{ + .pane = pane, + .goff = goff, + .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), + .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, + }; + } + + fn next(w: *BodyWalk) ?BodyRow { + while (w.n < w.pane.rows) { + if (w.lines) |*it| { + if (it.next()) |line| { + const idx = w.line_idx; + w.line_idx += 1; + // Lines scrolled off the top still count: the index names a + // line of the BUFFER, not of the visible body. + if (w.skip > 0) { + w.skip -= 1; + continue; + } + w.n += 1; + return .{ .edit = .{ .line = line, .idx = idx } }; + } + // The buffer stands in for `rows` shell rows however many lines + // it actually spelled, which is the whole slide. + w.g += w.covered; + w.skip = 0; + w.lines = null; + continue; + } + if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + w.lines = std.mem.splitScalar(u8, o.text, '\n'); + w.covered = o.rows; + w.line_idx = 0; + continue; + }; + const vi = w.g - w.goff; + w.g += 1; + w.n += 1; + return .{ .grid = vi }; + } + return null; + } +}; + +/// Run the terminal body row walk. A null destination counts bytes; a slice +/// fills the exact allocation made from that count. +fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { + var walk: BodyWalk = .init(pane); + var written: usize = 0; + var first = true; + while (walk.next()) |row| { + if (!first) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + first = false; + const bytes = switch (row) { + .edit => |e| e.line, + .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) + viewport[@intCast(vi)] + else + "", + }; + if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); + written += bytes.len; + } + return written; +} + +// Match surviving edit-buffer rows to their original terminal styles. +const EditAnchors = struct { + /// the buffer's own text, walked in order: a line the VIEWPORT skipped still + /// consumes the row it came from, so the lines below it stay aligned + text: []const u8 = &.{}, + at: usize = 0, + shell: []const []const u8 = &.{}, + /// the covered span, absolute grid rows, as `[first, end)` + first: usize = 0, + end: usize = 0, + lines: usize = 0, + /// the line `at` names, and the first row still unclaimed + idx: usize = 0, + cursor: usize = 0, + budget: usize = 0, + active: bool = false, + + fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { + if (o.rows <= 0 or o.row < 0) return .{}; + const first: usize = @intCast(o.row); + const screen = pane.terminal.?.vt.screens.active; + const total = screen.pages.scrollbar().total; + if (first >= total) return .{}; + const covered: usize = @intCast(o.rows); + const count = @min(covered, total - first); + const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; + const br = screen.pages.pin(.{ .screen = .{ + .x = screen.pages.cols - 1, + .y = @intCast(first + count - 1), + } }) orelse return .{}; + const arena = p.scratch.allocator(); + var output: std.Io.Writer.Allocating = .init(arena); + screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; + const shell = arena.alloc([]const u8, count) catch return .{}; + var raw = std.mem.splitScalar(u8, output.written(), '\n'); + var pins = tl.rowIterator(.right_down, br); + for (shell) |*row| { + const text = raw.next() orelse ""; + row.* = if (pins.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text + else + text; + } + const lines = std.mem.count(u8, o.text, "\n") + 1; + return .{ + .text = o.text, + .shell = shell, + .first = first, + .end = first + count, + .lines = lines, + .cursor = first, + .budget = covered + 4 * lines, + .active = true, + }; + } + + fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { + if (!a.active or idx >= a.lines) return null; + var found: ?Anchor = null; + while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); + return found; + } + + fn nextLine(a: *EditAnchors) ?[]const u8 { + if (a.at > a.text.len) return null; + const rest = a.text[a.at..]; + if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { + a.at += n + 1; + return rest[0..n]; + } + // The last line has no terminator; one past the end ends the walk. + a.at = a.text.len + 1; + return rest; + } + + /// Where this line still stands over the grid, if anywhere. + fn claim(a: *EditAnchors, line: []const u8) ?Anchor { + const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; + var k = a.cursor; + while (k < end) : (k += 1) { + if (a.budget == 0) return null; + a.budget -= 1; + if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; + a.cursor = k + 1; + return .{ .row = @intCast(k) }; + } + if (a.cursor >= a.end) return null; + const shell = a.shell[a.cursor - a.first]; + var p: usize = 0; + while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; + var s: usize = 0; + const room = @min(line.len, shell.len) - p; + while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; + if (p + s == 0) return null; + if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; + const row = a.cursor; + if (s > 0 or p >= shell.len) a.cursor += 1; + return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; + } +}; + +const Anchor = struct { + /// the row, absolute while it comes from `EditAnchors`, viewport once + /// `recolorAnsi` has subtracted the walk's offset + row: i32, + prefix: usize = std.math.maxInt(usize), + suffix: usize = 0, + /// the row's own dumped length — what the suffix is measured from on the + /// GRID side, where the edit may have changed the byte count + shell_len: usize = 0, + + fn whole(an: Anchor) bool { + return an.prefix == std.math.maxInt(usize); + } +}; + +pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + // No emulator, no ANSI cells: the whole pass — and the 256-colour theme + // projection behind it — is compiled out. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const body_y = p.bodyTop(pane, r); + var filtered_storage: FilteredColors = undefined; + const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { + const tz_filter = tracy.zone(@src(), "filterInit"); + defer tz_filter.end(); + filtered_storage = FilteredColors.init(p, pane); + break :blk &filtered_storage; + } else null; + // DECSCNM, read once: the filtered palette folds it in itself, the raw + // path needs it per cell. + const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); + const pages = &pane.terminal.?.vt.screens.active.pages; + const vp_rows: i32 = @intCast(scrollbar(pane).len); + // Which buffer lines the user has not actually changed, so a row swallowed + // by a growing buffer keeps the colour it still stands over. + var anchors: ?EditAnchors = null; + var walk: BodyWalk = .init(pane); + var lines = std.mem.splitScalar(u8, body, '\n'); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + // Before any early exit below, or the lines fall out of step with rows. + const text = lines.next() orelse ""; + const anchor: Anchor = switch (row) { + .edit => |e| blk: { + if (anchors == null) anchors = .init(p, pane, pane.ovl.?); + var an = anchors.?.shellRow(e.idx) orelse continue; + an.row -= walk.goff; + break :blk an; + }, + .grid => |v| .{ .row = v }, + }; + const vi = anchor.row; + if (vi < 0 or vi >= vp_rows) continue; + const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { + if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; + break :cut switch (promptCut(row_pin)) { + .keep => 0, + // Blanked end to end: the row shows nothing of the grid, so + // projecting the prompt's own colours onto it would be a lie. + .blank => continue, + .cut => |n| std.math.cast(u16, n) orelse continue, + }; + }; + if (cut > 0 and text.len == 0) continue; + var at: usize = 0; + var sc: u16 = 0; + var gc: u16 = cut; + var sb: usize = 0; + const mine_from = @min(anchor.prefix, text.len); + const mine_to = text.len - @min(anchor.suffix, text.len); + var crossed = false; + while (at < text.len and sc < tw) { + const stop = modal.nextGrapheme(text, at); + if (stop <= at) break; + const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; + if (at >= mine_from and at < mine_to) { + sc += span; + at = stop; + continue; + } + if (at >= mine_to and !crossed) { + crossed = true; + const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); + while (sb < upto) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + sb += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + } + } + const want = stop - at; + // Consume every cell that contributed to this grapheme. A cluster + // ghostty split across several cells is still ONE printed glyph. + var covered: usize = 0; + var style: ?pardes.CellStyle = null; + while (covered < want) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) + style = cellStyle(p, ci, filtered, scnm); + covered += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + // A spacer contributes no bytes; without this the loop would + // spin on a row that ends in one. + if (covered == 0 and gc >= pane.cols) break; + } + while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { + if (t.cell.wide != .spacer_tail) break; + gc = std.math.add(u16, gc, 1) catch break; + } + if (style) |st| for (0..span) |k| { + const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = st; + }; + sb += covered; + sc += span; + at = stop; + } + var tail: ?pardes.CellStyle = null; + if (anchor.whole() or anchor.suffix > 0) { + while (sc < tw) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + gc = std.math.add(u16, gc, 1) catch break; + if (ci.cell.wide == .spacer_tail) continue; + const cell = s.at(tx + sc, body_y + vr); + sc += 1; + const style = cellStyle(p, ci, filtered, scnm); + tail = style; + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + } + if (tail) |style| while (sc < tw) : (sc += 1) { + const cell = s.at(tx + sc, body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + }; + } + } +} + +fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { + const style = ci.style(); + var cs: pardes.CellStyle = .{ + .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), + .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), + .bold = style.flags.bold, + .dim = style.flags.faint, + .italic = style.flags.italic, + .blink = style.flags.blink, + .reverse = style.flags.inverse, + .invisible = style.flags.invisible, + .strikethrough = style.flags.strikethrough, + .ul = switch (style.flags.underline) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + }; + if (filtered == null) switch (ci.cell.content_tag) { + .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), + .bg_color_rgb => { + const rgb = ci.cell.content.color_rgb; + cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; + }, + else => {}, + }; + return cs; +} + +const FilteredColors = struct { + source: GColor.Palette, + target: *const GColor.Palette, + theme_bg: GColor.RGB, + theme_fg: GColor.RGB, + dynamic_bg: ?GColor.RGB, + dynamic_fg: ?GColor.RGB, + default_bg: GColor.RGB, + /// What a foreground too near `default_bg` becomes instead. + fallback_fg: GColor.RGB, + default_bg_luminance: f64, + fg_for_palette: [256]pardes.Color = undefined, + bg_for_palette: [256]pardes.Color = undefined, + /// The two answers for a cell that names no colour of its own. + fg_default: pardes.Color = undefined, + bg_default: pardes.Color = undefined, + cache_rgb: [256]GColor.RGB = undefined, + cache_key: [256]u8 = undefined, + cache_valid: [256]bool = @splat(false), + + fn init(p: *Pardes, pane: *const Pane) FilteredColors { + var source = GColor.default; + for (&source, 0..) |*rgb, i| + rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + const theme = p.theme(); + var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); + var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); + var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); + if (pane.terminal.?.vt.modes.get(.reverse_colors)) { + std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); + std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); + } + var self: FilteredColors = .{ + .source = source, + .target = p.tty_filter_palette.get(theme), + .theme_bg = theme_bg, + .theme_fg = theme_fg, + .dynamic_bg = dynamic_bg, + .dynamic_fg = dynamic_fg, + .default_bg = theme_bg, + .fallback_fg = theme_fg, + .default_bg_luminance = luminanceOf(theme_bg), + }; + if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); + self.default_bg_luminance = luminanceOf(self.default_bg); + if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) + self.fallback_fg = self.theme_bg; + + self.fg_default = asPardesColor(self.legible( + if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, + )); + self.bg_default = asPardesColor(self.default_bg); + for (&self.source, 0..) |current, i| { + const idx: u8 = @intCast(i); + const mapped = self.paletteRgb(idx, current); + self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); + self.bg_for_palette[idx] = asPardesColor(mapped); + } + return self; + } + + fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { + return switch (style.fg_color) { + .none => self.fg_default, + .palette => |idx| self.fg_for_palette[idx], + .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ + .default = self.dynamic_fg orelse self.theme_fg, + .palette = &self.source, + .bold = null, + })))), + }; + } + + fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { + switch (cell.content_tag) { + .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], + .bg_color_rgb => {}, + else => switch (style.bg_color) { + .none => return self.bg_default, + .palette => |idx| return self.bg_for_palette[idx], + .rgb => {}, + }, + } + // Truecolour, from either the cell or its style. + return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); + } + + fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { + if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= + config.tty_filter_min_contrast) return rgb; + return self.fallback_fg; + } + + fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { + if (current.eql(GColor.default[idx])) return self.target[idx]; + return self.keyedRgb(current); + } + + fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { + return self.target[self.nearestKey(rgb)]; + } + + fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { + const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; + const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); + if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) + return self.cache_key[slot]; + + var best: u8 = 0; + var best_distance: u32 = std.math.maxInt(u32); + for (GColor.default, 0..) |candidate, i| { + const distance = colorDistance(rgb, candidate); + // Strict comparison makes duplicate-colour ties stable at the + // lowest canonical xterm key. + if (distance < best_distance) { + best_distance = distance; + best = @intCast(i); + } + } + self.cache_rgb[slot] = rgb; + self.cache_key[slot] = best; + self.cache_valid[slot] = true; + return best; + } +}; + +const channel_luminance: [256]f64 = blk: { + @setEvalBranchQuota(20000); + var table: [256]f64 = undefined; + for (&table, 0..) |*slot, c| { + const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; + slot.* = if (normalized <= 0.03928) + normalized / 12.92 + else + std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); + } + break :blk table; +}; + +fn luminanceOf(rgb: GColor.RGB) f64 { + return 0.2126 * channel_luminance[rgb.r] + + 0.7152 * channel_luminance[rgb.g] + + 0.0722 * channel_luminance[rgb.b]; +} + +/// ghostty's `RGB.contrast` with both luminances already in hand. +fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { + const lighter = @max(a_luminance, b_luminance); + const darker = @min(a_luminance, b_luminance); + return (lighter + 0.05) / (darker + 0.05); +} + +fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { + const dr = @as(i32, a.r) - @as(i32, b.r); + const dg = @as(i32, a.g) - @as(i32, b.g); + const db = @as(i32, a.b) - @as(i32, b.b); + return @intCast(dr * dr + dg * dg + db * db); +} + +test "the luminance table answers exactly what ghostty computes" { + for (0..256) |i| { + const c: u8 = @intCast(i); + const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; + try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); + } + // Channel weights are asymmetric, so a grey ramp alone would not catch a + // transposed coefficient. The palette is what the tables enumerate. + for (GColor.default) |candidate| { + try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); + for (GColor.default) |page| { + try std.testing.expectEqual( + candidate.contrast(page), + contrastOf(luminanceOf(candidate), luminanceOf(page)), + ); + } + } +} + +test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { + const testing = std.testing; + // Raw index assertions require a theme that inherits the ANSI palette. + const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a one-row tag keeps this small screen's rows + p.sync(); + try testing.expect(pane.tty_filter); + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ + "\x1b[38;5;196mB" ++ + "\x1b[38;2;255;0;0mC" ++ + "\x1b[0;48;5;25mD" ++ + "\x1b[0;48;2;0;95;175mE" ++ + "\x1b[0;1;2;3;4;5;7;8;9mF" ++ + "\x1b[0;48;5;25m\x1b[K" ++ + "\r\n\x1b[0;38;5;2m界" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + const raw = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); + + pane.tty_filter = true; + _ = frame.reset(.retain_capacity); + const filtered = try p.render(frame.allocator()); + var expected_cache: FilterPalette = .{}; + const expected = expected_cache.get(p.theme()); + try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); + try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); + try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); + + const attrs = filtered.at(tx + 5, body_y).style; + try testing.expect(attrs.bold); + try testing.expect(attrs.dim); + try testing.expect(attrs.italic); + try testing.expect(attrs.blink); + try testing.expect(attrs.reverse); + try testing.expect(attrs.invisible); + try testing.expect(attrs.strikethrough); + try testing.expectEqual(.single, attrs.ul); + + const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; + try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); + try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); + try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); + // A filtered terminal never delegates either colour to a backend palette, + // including cells which were empty/default before the pass. + for (0..r.w - config.GUTTER) |col| { + const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); + try testing.expect(!cell.default); + switch (cell.style.fg) { + .rgb => {}, + else => return error.FilteredForegroundWasNotRgb, + } + switch (cell.style.bg) { + .rgb => {}, + else => return error.FilteredBackgroundWasNotRgb, + } + } + + // Colors remains the global master gate. The pane remembers Filter while + // ANSI projection is dormant, and resumes it without replaying VT bytes. + p.settings.colors = false; + _ = frame.reset(.retain_capacity); + const plain = try p.render(frame.allocator()); + try testing.expect(pane.tty_filter); + try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); + p.settings.colors = true; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); + const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; + try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); + pane.tty_filter = false; + pane.tty_filter = true; + try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); + _ = frame.reset(.retain_capacity); + const osc_palette = try p.render(frame.allocator()); + try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); + + // Dynamic default foreground/background colours key every default cell, + // including the otherwise blank end of the row. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ + "\x1b]11;#5f5f5f\x1b\\" } }); + const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; + const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; + try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); + try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); + _ = frame.reset(.retain_capacity); + const dynamic = try p.render(frame.allocator()); + const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), blank.bg); + + const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; + try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); + const reversed_explicit = reversed.at(tx, body_y).style; + try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); + try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); + _ = frame.reset(.retain_capacity); + const unreversed = try p.render(frame.allocator()); + const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); + + // The cache is keyed by values, not a theme name. Replacing a custom + // theme in place immediately recolours already-rendered indexed cells. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); + var custom = p.theme().*; + custom.name = try p.gpa.dupe(u8, "same-name"); + custom.palette = null; + custom.kw = .{ 1, 2, 3 }; + p.custom_theme = custom; + _ = frame.reset(.retain_capacity); + const custom_first = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); + if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; + _ = frame.reset(.retain_capacity); + const custom_second = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); +} + +test "terminal Filter keeps extended keys dark-to-light on a light theme" { + const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); + defer p.deinit(); + try std.testing.expectEqualStrings("acme", p.theme().name); + var cache: FilterPalette = .{}; + const palette = cache.get(p.theme()); + try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); + try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); +} + +test "terminal Filter preserves exact palette-null light theme default roles" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + var light = p.theme().*; + light.name = try p.gpa.dupe(u8, "filter-light-defaults"); + light.bg = .{ 0xf8, 0xf8, 0xf8 }; + light.fg = .{ 0x38, 0x38, 0x38 }; + light.palette = null; + p.custom_theme = light; + + const pane = p.panes[0].?; + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); + pane.tty_filter = true; + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const ordinary = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); +} + +test "terminal Filter maps the default roles before it maps anything else" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + // Native dark/light palettes plus legacy helix/dark/acme, including + // the null-page fallback that only the legacy dark theme exercises. + for (0..9) |t| { + p.settings.theme = @intCast(t); + const stage_one = FilteredColors.init(p, pane); + // `dark` declares no background of its own, which is exactly why the + // resolver reads the tag colours as the fallback rather than `.?`. + const theme = p.theme(); + try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); + try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); + // With no OSC 11 in play the mapped page IS that anchor, and the + // fallback is the other one: a background never contrasts with itself. + try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); + try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); + } + + p.settings.theme = 0; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); + var moved = FilteredColors.init(p, pane); + try testing.expect(!moved.default_bg.eql(moved.theme_bg)); + try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); +} + +test "terminal Filter refuses a foreground that would collapse onto the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ + "\x1b[0;30mB" ++ + "\x1b[0;31mR" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + const page = asPardesColor(fc.default_bg); + const rescued = asPardesColor(fc.fallback_fg); + _ = frame.reset(.retain_capacity); + const g = try p.render(frame.allocator()); + + // The colour each of the three would have been given with no floor. + const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); + const raw_black = fc.paletteRgb(0, GColor.default[0]); + const raw_red = fc.paletteRgb(1, GColor.default[1]); + + for ([_]struct { at: u16, raw: GColor.RGB }{ + .{ .at = 0, .raw = raw_white }, + .{ .at = 1, .raw = raw_black }, + .{ .at = 2, .raw = raw_red }, + }) |case| { + const cell = g.at(tx + case.at, body_y).style; + try testing.expectEqual(page, cell.bg); + if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { + // Refused: the projection's answer is not painted, the anchor is. + try testing.expectEqual(rescued, cell.fg); + try testing.expect(!std.meta.eql(cell.fg, cell.bg)); + } else { + // Cleared the floor, so stage two leaves it exactly alone. + try testing.expectEqual(asPardesColor(case.raw), cell.fg); + } + // Either way a filtered cell delegates neither colour to a backend. + switch (cell.fg) { + .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= + config.tty_filter_min_contrast), + else => return error.FilteredForegroundWasNotRgb, + } + } + + // At least one of the three has to have been a real collapse, or this + // theme proved nothing: white on the light theme, black on the dark. + try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or + raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); + // A saturated red is never the page on any curated theme. + try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + } +} + +test "terminal Filter holds every projected foreground off the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + var refused: usize = 0; + for (fc.target, 0..) |projected, key| { + const ink = fc.legible(projected); + try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + if (!ink.eql(projected)) { + refused += 1; + try testing.expect(ink.eql(fc.fallback_fg)); + // Only ever refused for being too near the page. + try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); + } + // The key a background asks for is handed back untouched, including + // the one whose value is the page itself. + try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); + } + // Every curated theme owns at least one collapsing key — that is why + // the floor exists — and the floor must not be flattening the palette. + try testing.expect(refused > 0); + try testing.expect(refused < fc.target.len / 8); + } +} + +test "tty ansi colors follow the prompt hug into normal mode" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; + const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; + + // tty mode projects the emulator's ansi colours cell for cell. + pane.body.mode = .tty; + p.shell_rows.stale = true; + const tty = try p.render(frame.allocator()); + try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); + try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); + + pane.body.mode = .normal; + p.shell_rows.stale = true; + _ = frame.reset(.retain_capacity); + const norm = try p.render(frame.allocator()); + try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); + try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); + try testing.expectEqual(red, norm.at(tx, body_y).style.fg); + try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); +} + +test "a prompt row hidden end to end paints nothing at all" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a 12x8 screen: the body, not the tag + p.sync(); + pane.tty_filter = false; + pane.body.mode = .normal; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + p.shell_rows.stale = true; + const s = try p.render(frame.allocator()); + + try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); + try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); +} + +pub fn palColor(p: *Pardes, idx: u8) pardes.Color { + if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; + return .{ .index = idx }; +} + +pub fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { + return switch (color) { + .none => blk: { + const t = if (is_bg) p.theme().bg else p.theme().fg; + break :blk if (t) |c| .{ .rgb = c } else .default; + }, + .palette => |idx| palColor(p, idx), + .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, + }; +} + +/// executing at a prompt with typed text below it: pad the output area +/// with newlines so the command's output doesn't overwrite the buffer +pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { + // Nothing to pad away from: with no emulator there is no prompt and no + // child whose output could land on top of the edit buffer. + if (comptime !enabled) return; + const pane = p.panes[id] orelse return; + const o = pane.ovl orelse return; + if (!pane.isTerminal()) return; + const state = pane.terminal orelse return; + if (!state.vt.cursorIsAtPrompt()) return; + // the buffer's LAST surface row: its lines may outnumber the shell + // rows it covers, and it is the bottom one output must clear + const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; + const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); + const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); + const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); + var i: i32 = 0; + while (i < pad) : (i += 1) p.emitWrite(id, "\r"); +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + pane.body.remember(p.gpa, pane.ovl); +} + +pub fn undo(p: *Pardes, pane: *Pane) void { + const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = back_to.ovl; + pane.ensureCursorVisible(); +} + +pub fn redo(p: *Pardes, pane: *Pane) void { + const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = forward_to.ovl; + pane.ensureCursorVisible(); +} + +pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + const n = @min(room, data.len); + @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); + state.reply_len += @intCast(n); +} + +const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( + @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), +).optional.child).pointer.child).@"fn".return_type.?; +pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { + return .{}; +} diff --git a/src/tty/tty.zig b/src/tty/tty.zig index f5ae078a..3902271c 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1915,7 +1915,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { shell.gens[0] = 2; _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.Terminal.screenTextAlloc(core.panes[0].?, gpa); + const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); diff --git a/test/mode.zig b/test/mode.zig index cba93c30..767cda93 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -26,7 +26,7 @@ fn customTag(pane: *pardes.Pane, text: []const u8) !void { } test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100 }); defer p.deinit(); p.presentation.enabled = false; diff --git a/test/panes.zig b/test/panes.zig index 3b2bea0a..f7ca9fc5 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -864,7 +864,7 @@ const TtySelectionTests = struct { } test "tty selection yields to a new modal cursor selection" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); p.presentation.enabled = false; @@ -889,7 +889,7 @@ const TtySelectionTests = struct { } test "tty selection preserves its exact stream through yank clipboard and mode changes" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |prompt| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -949,7 +949,7 @@ const TtySelectionTests = struct { } test "tty selection pastes across panes once with existing bracket and mouse protocols" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |bracketed| { for ([_]bool{ false, true }) |reports_mouse| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 24 }); @@ -1028,14 +1028,14 @@ const TtySelectionTests = struct { // than the text goes and reads the desktop clipboard on its own account, // and a coding agent reading it is looking for an image, not for words. test "raw tty paste chords type at the program instead of reaching it as keys" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |bracketed| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const pane = p.panes[0].?; try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); + try std.testing.expectEqual(bracketed, panes.terminal.bracketedPaste(pane)); p.registers.put(p.gpa, '"', "one\ntwo", 0, 1, true); // what a `y` anywhere left behind var buf: [256]u8 = undefined; _ = childInput(p, &buf); @@ -1833,7 +1833,7 @@ test "terminal overlay recoloring never materializes unrelated history" { _ = try p.render(frame.allocator()); try testing.expect(p.shell_rows.pane == null); - pane.ovl.?.row = panes.Terminal.gridOffset(pane); + pane.ovl.?.row = panes.terminal.gridOffset(pane); p.gpa.free(pane.ovl.?.text); pane.ovl.?.text = try p.gpa.dupe(u8, "caf\xc3\xa9 \xe7\x95\x8c"); _ = frame.reset(.retain_capacity); @@ -1847,7 +1847,7 @@ test "terminal overlay recoloring never materializes unrelated history" { } test "terminal output keeps following new rows after scrollback eviction" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1863,9 +1863,9 @@ test "terminal output keeps following new rows after scrollback eviction" { for (0..3) |phase| { if (phase > 0) { pane.body.mode = .normal; - panes.Terminal.scrollGrid(pane, -30); + panes.terminal.scrollGrid(pane, -30); try std.testing.expect(pages.scrollbar().offset < pages.scrollbar().total - pane.rows); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); } for (phase * 20_000..(phase + 1) * 20_000) |n| { var buf: [64]u8 = undefined; @@ -1878,7 +1878,7 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expect(pages.page_size <= pages.maxSize()); const sb = pages.scrollbar(); try std.testing.expectEqual(sb.total - pane.rows, sb.offset); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); var last_buf: [16]u8 = undefined; const last = try std.fmt.bufPrint(&last_buf, "row-{d:0>5}", .{(phase + 1) * 20_000 - 1}); @@ -1908,7 +1908,7 @@ test "terminal output keeps following new rows after scrollback eviction" { } test "terminal edit stays on its surviving row when old scrollback is evicted" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1946,7 +1946,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } } try std.testing.expect(removed > 0 and removed < original_row); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); const row = original_row - @as(i32, @intCast(removed)); try std.testing.expectEqualStrings(last, modal.lineSlice(full, @intCast(row))); @@ -1956,7 +1956,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } test "terminal edits and undo survive partial history clearing and whole-screen loss" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const Action = enum { clear_history, partial_clear_history, reset_primary, reset_alternate, evict_all, hidden_undo }; for (std.enums.values(Action)) |action| { @@ -1978,7 +1978,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.cur_col = 4; pane.body.cur_pinned = true; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); const overlay = pane.ovl.?; pane.body.ed_redo[0] = .{ .ovl = .{ .row = overlay.row, .rows = overlay.rows, .text = try gpa.dupe(u8, overlay.text) }, @@ -1990,7 +1990,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen if (action == .hidden_undo) { gpa.free(pane.ovl.?.text); pane.ovl = null; - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); } const bytes = switch (action) { .clear_history, .partial_clear_history => "\x1b[3J", @@ -2006,20 +2006,20 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqual(expected + 1, pane.body.cur_row); try std.testing.expectEqual(expected, pane.body.vsel.row); } - for ([_]panes.Terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { + for ([_]panes.terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { try std.testing.expectEqual(expected, snapshot.ovl.?.row); try std.testing.expectEqual(expected + 1, snapshot.cur_row); try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); } try std.testing.expectEqual(@as(usize, 2), pane.terminal.?.vt.screens.active.pages.countTrackedPins()); - panes.Terminal.undo(p, pane); + panes.terminal.undo(p, pane); try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text); try std.testing.expectEqual(expected, pane.ovl.?.row); } } test "terminal lower scroll regions do not move edits above them" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -2030,23 +2030,23 @@ test "terminal lower scroll regions do not move edits above them" { pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "unsent") }; pane.body.cur_row = 1; pane.body.cur_pinned = true; - panes.Terminal.pushUndo(p, pane); - const total = panes.Terminal.scrollbar(pane).total; + panes.terminal.pushUndo(p, pane); + const total = panes.terminal.scrollbar(pane).total; var setup: [64]u8 = undefined; const bytes = try std.fmt.bufPrint(&setup, "\x1b[4;{d}r\x1b[{d};1H", .{ pane.rows, pane.rows }); p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); p.update(.{ .output = .{ .pane = 0, .bytes = "tail\r\n" ** 50 } }); - try std.testing.expectEqual(total, panes.Terminal.scrollbar(pane).total); + try std.testing.expectEqual(total, panes.terminal.scrollbar(pane).total); try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 1), pane.body.ed_undo[0].ovl.?.row); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); try std.testing.expect(std.mem.startsWith(u8, full, "top\nsecond\nthird\n")); } test "terminal eviction and lower-region scrolling in one read preserve a surviving edit" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -2071,7 +2071,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv pane.ovl = .{ .row = old_row, .rows = 1, .text = try gpa.dupe(u8, "kept edit") }; pane.body.cur_row = old_row; pane.body.cur_pinned = true; - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); const old_total = pages.total_rows; var buf: [128]u8 = undefined; const bytes = try std.fmt.bufPrint(&buf, "new\r\n\x1b[4;{d}r\x1b[{d};1Hregion\r\n", .{ pane.rows, pane.rows }); @@ -3342,11 +3342,11 @@ const TerminalTests = struct { // Tests asserting raw ANSI indices explicitly select helix, whose palette // is inherited. Native-palette coverage lives in the overlay/eviction and // trailing-blank tests and checks their concrete RGB values instead. - const gridOffset = panes.Terminal.gridOffset; - const scrollGrid = panes.Terminal.scrollGrid; - const promptInputReady = panes.Terminal.promptInputReady; - const forwardKey = panes.Terminal.forwardKey; - const enterTty = panes.Terminal.enterTty; + const gridOffset = panes.terminal.gridOffset; + const scrollGrid = panes.terminal.scrollGrid; + const promptInputReady = panes.terminal.promptInputReady; + const forwardKey = panes.terminal.forwardKey; + const enterTty = panes.terminal.enterTty; // Align normal-mode glyphs with the VT grid and compare their styles. fn modeStyleDiffs(p: *Pardes, pane: *Pane, gpa: std.mem.Allocator, note: []const u8) !usize { @@ -4798,7 +4798,7 @@ test "Zig keywords keep every rendered byte colored across line-number widths" { } test "terminal overlays preserve trailing blank styles without coloring inserted rows" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 56a5da91..567a8b02 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index 9c4b5ebe..8ba0cdec 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 984d480a..ab5ed3b6 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} diff --git a/test/perf.zig b/test/perf.zig index 38c640b4..fca4a3b0 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -275,12 +275,12 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { const allocator = counter.allocator(); const begin = nowNs(); const pane = if (terminal) - try pardes.panes.Terminal.create(allocator, screen_cols, screen_rows) + try pardes.panes.terminal.create(allocator, screen_cols, screen_rows) else - try pardes.panes.Terminal.createDoc(allocator, screen_cols, screen_rows); + try pardes.panes.terminal.createDoc(allocator, screen_cols, screen_rows); const constructed = nowNs(); const retained = counter.live; - pardes.panes.Terminal.deinitEmulator(pane, allocator); + pardes.panes.terminal.deinitEmulator(pane, allocator); allocator.destroy(pane); const destroyed = nowNs(); if (counter.live != 0) return error.LeakedPaneMemory; @@ -707,7 +707,7 @@ fn checkTerminalTail(core: *pardes.Pardes, surface: *pardes.Surface, batch: usiz const pane = core.panes[0] orelse return error.MissingTerminal; const rect = core.rects[0]; const x = rect.x + pardes.config.GUTTER; - const y = (if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + pardes.panes.Terminal.gridCursor(pane).y; + const y = (if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + pardes.panes.terminal.gridCursor(pane).y; var expected_buffer: [32]u8 = undefined; const expected = try std.fmt.bufPrint(&expected_buffer, "TURN {d:0>10} READY", .{batch}); for (expected, 0..) |byte, col| { @@ -773,7 +773,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he pane.body.cur_row = first + 1; pane.body.cur_col = 1; pane.body.vsel = .{ .active = true, .row = first, .col = 0 }; - pardes.panes.Terminal.pushUndo(core, pane); + pardes.panes.terminal.pushUndo(core, pane); core.gpa.free(pane.ovl.?.text); pane.ovl = null; if (pane.body.ed_undo_len != index + 1) return error.TerminalUndoSnapshotFailed; @@ -782,7 +782,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |snapshot| if (snapshot.ovl) |overlay| core.gpa.free(overlay.text); pane.body.ed_undo_len = 0; } - pardes.panes.Terminal.enterTty(core, 0); + pardes.panes.terminal.enterTty(core, 0); pump(core); const tracked_before = pages.countTrackedPins(); const start = try pages.trackPin(pages.pin(.{ .screen = .{ .y = @intCast(first) } }).?); @@ -895,7 +895,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void } const stream_wall_ns = nowNs() - stream_begin; const live_after_output = counter.live; - const first_row = @as(i32, @intCast(state.vt.screens.active.pages.scrollbar().offset)) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); + const first_row = @as(i32, @intCast(state.vt.screens.active.pages.scrollbar().offset)) + @as(i32, pardes.panes.terminal.gridCursor(pane).y); _ = arena.reset(.retain_capacity); const modal_begin = nowNs(); core.update(.{ .key = .{ .cp = core.opts.tty_toggle, .ctrl = true } }); @@ -943,7 +943,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void const begin = nowNs(); core.update(.{ .output = .{ .pane = 0, .bytes = update } }); pump(core); - const cursor_row = pardes.panes.Terminal.gridOffset(pane) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); + const cursor_row = pardes.panes.terminal.gridOffset(pane) + @as(i32, pardes.panes.terminal.gridCursor(pane).y); pane.ovl.?.row = if (phase == 0) 0 else cursor_row - 1; pane.body.cur_row = pane.ovl.?.row; pane.body.cur_col = 0; -- cgit v1.3 From 51903dd947f90381d1a908c488a019289a1c8413 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 11:57:26 -0300 Subject: Search converge 3/6: the query pane, line 1 the query and its first word the source, rows made live like Callstack's, the owner's places showing the set, a +Preview promoted in place, Enter freezes, Esc restores --- docs/typ/builtins-gui.json | 7 +- docs/typ/builtins-tty.json | 7 +- src/File.zig | 2 + src/Names.zig | 446 +++++++++ src/Output.zig | 8 +- src/Places.zig | 39 +- src/Query.zig | 2155 ++++++++++++++++++++++++++++++++++++++++++++ src/Text.zig | 5 +- src/body_layer.zig | 1 + src/builtins.zig | 35 +- src/config.zig | 54 +- src/edit.zig | 20 + src/exec.zig | 20 + src/fs.zig | 2 +- src/layout.zig | 18 +- src/look.zig | 2 + src/mouse.zig | 9 + src/ninep/ctl.zig | 16 +- src/normal.zig | 16 +- src/panes.zig | 7 + src/pardes.zig | 54 +- src/tagline.zig | 8 + test/output.zig | 59 +- 23 files changed, 2921 insertions(+), 69 deletions(-) create mode 100644 src/Names.zig create mode 100644 src/Query.zig (limited to 'src/Text.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index de8fde9c..a502836e 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -102,6 +102,7 @@ {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, {"name": "Parallax", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A theme's page pattern moves with the text at a quarter of its speed, on or off."}, {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, @@ -111,7 +112,7 @@ {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, @@ -119,6 +120,10 @@ {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, {"name": "SelectionGlow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A soft halo of the selection's colour round it in the body, on or off."}, {"name": "Shader", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A Shadertoy file into the post chain, or out of it, compiled again when saved; off empties the chain."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 4db29e6e..7e9ba678 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -91,6 +91,7 @@ {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."}, @@ -98,7 +99,7 @@ {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, @@ -106,6 +107,10 @@ {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, {"name": "Shell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The shell new terminals run; bare, $SHELL if it is executable, else /bin/sh."}, {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, diff --git a/src/File.zig b/src/File.zig index 3db22f95..f633cad0 100644 --- a/src/File.zig +++ b/src/File.zig @@ -598,6 +598,8 @@ pub fn gutterWidth(pane: *const Pane) u16 { // pager and delta show none. if (file.pager) return 0; if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; + // A query pane's rows carry their own line numbers (Query.zig). + if (pane.query != null) return 0; var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; diff --git a/src/Names.zig b/src/Names.zig new file mode 100644 index 00000000..48447f56 --- /dev/null +++ b/src/Names.zig @@ -0,0 +1,446 @@ +//! Names a query pane picks from by a fuzzy query: the files under a +//! directory (walked a slice a frame), the recent files, the open panes, +//! a file's declarations. Each keystroke scores them again with a small +//! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses +//! at the starts of words and path segments), a frame's budget at a time, +//! the best kept first. Lifted from the pick prototype (Pick.zig), whose +//! scorer took ~1 ms for 20k paths in a release build. Embedded in a +//! Query; the rows it shows are the Query's to make. +const Names = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const Pardes = pardes.Pardes; + +/// The candidates' rows, back to back, no newlines. +bytes: std.ArrayList(u8) = .empty, +/// `bytes` in lowercase, for a lowercase query to match without folding. +lower: std.ArrayList(u8) = .empty, +cands: std.ArrayList(Cand) = .empty, +/// The candidates `query` matches, best first. +hits: std.ArrayList(Hit) = .empty, +/// `cands[0..scored]` were scored against `query` (in `hits` or not): the +/// ones a walk adds past it are scored as they come. +scored: u32 = 0, +/// Candidates to score before `cands[scored..]`: what the last query +/// matched, when this one only grew from it. +pending: std.ArrayList(u32) = .empty, +pending_at: usize = 0, +query_buf: [max_query]u8 = undefined, +query_len: u8 = 0, +/// The files walk, while it lasts (Find in a query pane until the disk +/// engine has it). +walk: ?Walk = null, +/// Bumped whenever `hits` change: the rows are made again only then. +gen: u32 = 0, + +pub const Cand = struct { + /// The row: `bytes[start..][0..len]`. + start: u32, + len: u16, + /// What is scored: the row's `[key..][0..key_len]` (a path, a + /// declaration's text, a name), its basename from `base` within it. + key: u16, + key_len: u16, + base: u16, + /// What the row is of: a line of the owner (Symbols, 1-based), a + /// pane's serial (Panes); 0 for a path. + ref: u32 = 0, +}; + +pub const Hit = struct { cand: u32, score: i32 }; + +/// The most rows shown: the rest are counted. +pub const max_rows = 200; +pub const max_query = 64; +/// A candidate is scored over its first this many bytes. +const max_text = 512; +const max_cands = 200_000; +/// Entries a walk reads a frame: ~1-3 ms warm. +const walk_slice = 2000; +const walk_max_depth = 16; +/// A keystroke's scoring, and a frame's: what is left waits a frame. +const score_budget_ns = 4 * std.time.ns_per_ms; + +const Walk = struct { + root: std.Io.Dir, + walker: std.Io.Dir.SelectiveWalker, + done: bool = false, + skipped: u32 = 0, + + fn deinit(w: *Walk) void { + const io = std.Io.Threaded.global_single_threaded.io(); + // The walker closes a directory only as it leaves it: the ones it + // is still in (all but the root, which is ours) are closed here. + if (w.walker.stack.items.len > 1) for (w.walker.stack.items[1..]) |*item| item.iter.reader.dir.close(io); + w.walker.deinit(); + w.root.close(io); + } +}; + +pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { + if (n.walk) |*w| w.deinit(); + n.bytes.deinit(gpa); + n.lower.deinit(gpa); + n.cands.deinit(gpa); + n.hits.deinit(gpa); + n.pending.deinit(gpa); + n.* = .{}; +} + +/// No candidates, no walk: for a source filled again. +pub fn reset(n: *Names) void { + if (n.walk) |*w| w.deinit(); + n.walk = null; + n.bytes.clearRetainingCapacity(); + n.lower.clearRetainingCapacity(); + n.cands.clearRetainingCapacity(); + n.hits.clearRetainingCapacity(); + n.pending.clearRetainingCapacity(); + n.pending_at = 0; + n.scored = 0; + n.gen +%= 1; +} + +pub fn queryText(n: *const Names) []const u8 { + return n.query_buf[0..n.query_len]; +} + +pub fn add(n: *Names, gpa: std.mem.Allocator, row_in: []const u8, key: usize, key_len: usize, base: u16, ref: u32) !void { + if (n.cands.items.len >= max_cands) return; + const text = row_in[0..@min(row_in.len, std.math.maxInt(u16))]; + try n.cands.append(gpa, .{ + .start = @intCast(n.bytes.items.len), + .len = @intCast(text.len), + .key = @intCast(@min(key, text.len)), + .key_len = @intCast(@min(key_len, text.len - @min(key, text.len))), + .base = base, + .ref = ref, + }); + try n.bytes.appendSlice(gpa, text); + try n.lower.ensureUnusedCapacity(gpa, text.len); + for (text) |c| n.lower.appendAssumeCapacity(std.ascii.toLower(c)); +} + +pub fn relative(path: []const u8, dir: []const u8) []const u8 { + const d = std.mem.trimEnd(u8, dir, "/"); + if (d.len > 0 and path.len > d.len + 1 and std.mem.startsWith(u8, path, d) and path[d.len] == '/') return path[d.len + 1 ..]; + return path; +} + +pub fn baseOf(path: []const u8) u16 { + const slash = std.mem.lastIndexOfScalar(u8, std.mem.trimEnd(u8, path, "/"), '/') orelse return 0; + return @intCast(@min(slash + 1, max_text)); +} + +/// The files under `dir`, walked from now on a slice a frame (`walkSlice`): +/// the first slice now, so a small tree is whole before the first frame. +pub fn startWalk(n: *Names, gpa: std.mem.Allocator, dir: []const u8) !void { + if (comptime !filesystem.platform_has_fs) return error.NoFilesystem; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var dir_handle = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); + errdefer dir_handle.close(io); + n.walk = .{ .root = dir_handle, .walker = try dir_handle.walkSelectively(gpa) }; + n.walkSlice(gpa); +} + +/// One frame's slice of a walk: up to `walk_slice` entries, files kept, +/// what a Find skips skipped and dot-directories too. +pub fn walkSlice(n: *Names, gpa: std.mem.Allocator) void { + const w = if (n.walk) |*w| w else return; + if (w.done) return; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var steps: usize = 0; + walk: while (steps < walk_slice) : (steps += 1) { + const e = (w.walker.next(io) catch { + w.skipped += 1; + continue; + }) orelse { + w.done = true; + break; + }; + if (e.kind != .directory) { + n.add(gpa, e.path, 0, e.path.len, baseOf(e.path), 0) catch { + w.done = true; + break; + }; + if (n.cands.items.len >= max_cands) { + w.done = true; + break; + } + continue; + } + if (e.depth() >= walk_max_depth or e.basename[0] == '.') continue; + for (filesystem.find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; + w.walker.enter(io, e) catch { + w.skipped += 1; + }; + } +} + +pub fn walking(n: *const Names) bool { + return if (n.walk) |w| !w.done else false; +} + +/// Still walking, or still scoring what it has: it wants the next frame. +pub fn busy(n: *const Names) bool { + return n.walking() or n.scored < n.cands.items.len or n.pending_at < n.pending.items.len; +} + +/// A new query: scored again, from what the last one matched when it only +/// grew from it. +pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void { + const q = text[0..@min(text.len, max_query)]; + if (std.mem.eql(u8, q, n.queryText()) and n.scored > 0) return; + // A query that only grew matches a subset of what the last one did: + // only those are scored again (and then the ones not yet scored). + const grew = n.query_len > 0 and std.mem.startsWith(u8, q, n.queryText()) and std.mem.indexOfScalar(u8, q[n.query_len..], ' ') == null; + n.query_len = @intCast(q.len); + @memcpy(n.query_buf[0..q.len], q); + if (grew) { + const pending = n.pending.items[n.pending_at..]; + std.mem.copyForwards(u32, n.pending.items[0..pending.len], pending); + n.pending.items.len = pending.len; + n.pending.ensureUnusedCapacity(gpa, n.hits.items.len) catch return; + for (n.hits.items) |h| n.pending.appendAssumeCapacity(h.cand); + } else { + n.scored = 0; + n.pending.clearRetainingCapacity(); + } + n.pending_at = 0; + n.hits.clearRetainingCapacity(); + n.rescore(gpa); +} + +/// Scores the pending candidates, then `cands[scored..]`, into `hits`, and +/// sorts them: at most `score_budget_ns` of it a call, the rest on the +/// next frames while the best so far is shown. +pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { + const q = n.queryText(); + const empty = std.mem.trim(u8, q, " ").len == 0; + const io = std.Io.Threaded.global_single_threaded.io(); + const started = std.Io.Clock.awake.now(io); + const had = n.hits.items.len; + const was_scored = n.scored; + var count: usize = 0; + while (true) : (count += 1) { + const i: u32 = if (n.pending_at < n.pending.items.len) blk: { + n.pending_at += 1; + break :blk n.pending.items[n.pending_at - 1]; + } else if (n.scored < n.cands.items.len) blk: { + n.scored += 1; + break :blk n.scored - 1; + } else break; + const c = n.cands.items[i]; + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null, null); + if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break; + // The clock every 256 candidates: reading it is not free either. + if (!empty and count % 256 == 255 and + started.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds() > score_budget_ns) break; + } + // An empty query keeps the source's order (the walk's, recency): no + // row moves as the walk goes on, it only grows at the foot. + if (!empty) std.sort.pdq(Hit, n.hits.items, n.cands.items, struct { + fn lt(cands: []const Cand, a: Hit, b: Hit) bool { + if (a.score != b.score) return a.score > b.score; + const la = cands[a.cand].key_len; + const lb = cands[b.cand].key_len; + if (la != lb) return la < lb; + return a.cand < b.cand; + } + }.lt); + if (n.hits.items.len != had or n.scored != was_scored or count > 0) n.gen +%= 1; +} + +/// The row of hit `i` and, in `marks`, the bytes of it the query matched. +pub fn row(n: *const Names, i: usize, marks: []u16, nmarks: *usize) []const u8 { + const c = n.cands.items[n.hits.items[i].cand]; + nmarks.* = 0; + const q = n.queryText(); + if (std.mem.trim(u8, q, " ").len > 0) { + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + _ = match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, marks, nmarks, &dp_trace); + for (marks[0..nmarks.*]) |*m| m.* += c.key; + } + return n.bytes.items[c.start..][0..c.len]; +} + +// ---- the scorer (pick's) ---- + +const neg: i32 = -(1 << 24); +const score_match = 16; +const gap_start = 3; +const gap_ext = 1; +const bonus_consecutive = 7; +/// At the start of the text or of a path segment. +const bonus_start = 12; +/// After `_ - . : space`. +const bonus_delim = 9; +/// A camelCase hump, or a word after other punctuation. +const bonus_camel = 8; +/// Each matched character in the basename. +const bonus_base = 2; + +/// The scorer's two rows, and the whole table the marks are backtracked +/// through: the main loop's, one score at a time. Not locals: a safe build +/// fills an undefined local, 4 KB a candidate, which was most of a +/// keystroke's time. +var dp_rows: [2][max_text]i32 = undefined; +var dp_trace: [max_query * max_text]i32 = undefined; + +fn bonusAt(text: []const u8, j: usize) i32 { + if (j == 0) return bonus_start; + const prev = text[j - 1]; + const c = text[j]; + if (prev == '/') return bonus_start; + switch (prev) { + '_', '-', '.', ':', ' ', '\t' => return bonus_delim, + else => {}, + } + if (std.ascii.isLower(prev) and std.ascii.isUpper(c)) return bonus_camel; + if (!std.ascii.isAlphanumeric(prev) and std.ascii.isAlphanumeric(c)) return bonus_camel; + return 0; +} + +/// `query`'s score against `text` (`lower` its lowercase copy, its +/// basename from `base`), null if some term of it is not a subsequence of +/// `text`. Terms split on spaces are ANDed; smart case per term. With +/// `marks`, the bytes matched are written there, ascending. +pub fn match(query: []const u8, text_in: []const u8, lower_in: []const u8, base: usize, marks: ?[]u16, marks_len: ?*usize, trace: ?[]i32) ?i32 { + const text = text_in[0..@min(text_in.len, max_text)]; + const lower = lower_in[0..text.len]; + var total: i32 = 0; + var nmarks: usize = 0; + var terms = std.mem.tokenizeScalar(u8, query, ' '); + while (terms.next()) |term_in| { + const term = term_in[0..@min(term_in.len, max_query)]; + const m = term.len; + const sensitive = for (term) |c| { + if (std.ascii.isUpper(c)) break true; + } else false; + // A lowercase term is matched against the lowercase copy. + var low_buf: [max_query]u8 = undefined; + const want = if (sensitive) term else std.ascii.lowerString(&low_buf, term); + const hay = if (sensitive) text else lower; + // The window a match can be in: from the first character's first + // place to the last one's last place, else no match at all. + const lo = std.mem.indexOfScalar(u8, hay, want[0]) orelse return null; + var pos = lo + 1; + for (want[1..]) |c| pos = (std.mem.indexOfScalarPos(u8, hay, pos, c) orelse return null) + 1; + const end = std.mem.lastIndexOfScalar(u8, hay, want[m - 1]).? + 1; + // D[i][j]: the best score with term[i] matched at text[j]. + var prev = &dp_rows[0]; + var cur = &dp_rows[1]; + const width = text.len; + const keep = if (trace) |t| t.len >= m * width else false; + for (0..m) |i| { + var gapped: i32 = neg; // max over k <= j-2 of D[i-1][k], less the gap to j + for (lo..end) |col| { + var best: i32 = neg; + if (i > 0 and col >= lo + 2) gapped = @max(gapped - gap_ext, prev[col - 2] - gap_start); + if (hay[col] == want[i]) { + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (i == 0) { + best = own; + } else if (col > lo) { + const from = @max(if (prev[col - 1] > neg) prev[col - 1] + bonus_consecutive else neg, gapped); + if (from > neg) best = from + own; + } + } + cur[col] = best; + if (keep) trace.?[i * width + col] = best; + } + const t = prev; + prev = cur; + cur = t; + } + var best: i32 = neg; + var at: usize = lo; + for (lo..end) |col| if (prev[col] > best) { + best = prev[col]; + at = col; + }; + if (best <= neg) return null; + total += best; + // Back from the best end, the place each character was matched at. + if (keep and marks != null) { + const out = marks.?; + const t = trace.?; + var i = m; + var col = at; + while (i > 0) { + i -= 1; + if (nmarks < out.len) { + out[nmarks] = @intCast(col); + nmarks += 1; + } + if (i == 0) break; + const here = t[i * width + col]; + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (col > lo and t[(i - 1) * width + col - 1] > neg and t[(i - 1) * width + col - 1] + bonus_consecutive + own == here) { + col -= 1; + continue; + } + var found = col - 1; + if (col >= lo + 2) { + var k = col - 2; + while (true) { + const d = t[(i - 1) * width + k]; + if (d > neg and d - gap_start - @as(i32, @intCast(col - 2 - k)) * gap_ext + own == here) { + found = k; + break; + } + if (k == lo) break; + k -= 1; + } + } + col = found; + } + } + } + if (marks_len) |count| { + if (marks) |out| std.mem.sort(u16, out[0..nmarks], {}, std.sort.asc(u16)); + count.* = nmarks; + } + return total; +} + +const test_paths = [_][]const u8{ + "src/layout.zig", "src/locations.zig", "src/Output.zig", "src/hunks.zig", + "src/pardes.zig", "src/pdf.zig", "src/look.zig", "src/syntax.zig", + "src/body_layer.zig", "build.zig", "src/ninep/ctl.zig", "docs/helix-keys.md", + "notes/helix-keys.md", "src/gui/Post.zig", "cmd/tool/ui_review.py", +}; + +fn topFor(q: []const u8) []const u8 { + var best: ?[]const u8 = null; + var best_score: i32 = std.math.minInt(i32); + for (test_paths) |path| { + var low: [256]u8 = undefined; + const s = match(q, path, std.ascii.lowerString(&low, path), baseOf(path), null, null, null) orelse continue; + if (s > best_score or (s == best_score and path.len < best.?.len)) { + best = path; + best_score = s; + } + } + return best orelse ""; +} + +test "Names ranks real paths as the pick prototype did" { + try std.testing.expectEqualStrings("src/layout.zig", topFor("layout")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("out")); + try std.testing.expectEqualStrings("src/pardes.zig", topFor("prz")); + try std.testing.expectEqualStrings("src/body_layer.zig", topFor("bl")); + try std.testing.expectEqualStrings("src/ninep/ctl.zig", topFor("ctl ninep")); + try std.testing.expectEqualStrings("docs/helix-keys.md", topFor("helkey")); + try std.testing.expectEqualStrings("src/gui/Post.zig", topFor("gui/po")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("Out")); +} diff --git a/src/Output.zig b/src/Output.zig index 9a11b2fc..1e62b04a 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -35,6 +35,9 @@ pub const Origin = union(enum) { unsaved, /// A directory's entries (Dir.zig), the pane named for it. dir, + /// A query pane's +Preview (Query.zig): a file's text shown, not yet + /// its pane; Enter promotes it to one where it stands. + preview, }; pub const max_arg = dump.max_origin_arg; @@ -259,6 +262,7 @@ pub fn traits(o: Origin) Traits { .errors => .{ .name = config.errors_buffer, .doc = true }, .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, + .preview => .{ .name = config.preview_buffer, .doc = true }, // Named for its directory, not a `+` name in it. .dir => .{ .name = "", .doc = true }, .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, @@ -324,6 +328,7 @@ pub fn word(o: Origin) []const u8 { .pdf_links => config.pdf_links_buffer, .unsaved => config.unsaved_buffer, .dir => dir_word, + .preview => config.preview_buffer, }; } @@ -337,6 +342,7 @@ pub fn fromWord(w: []const u8) ?Origin { if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; if (std.mem.eql(u8, w, config.unsaved_buffer)) return .unsaved; if (std.mem.eql(u8, w, dir_word)) return .dir; + if (std.mem.eql(u8, w, config.preview_buffer)) return .preview; if (std.meta.stringToEnum(Builtin, w)) |b| if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; @@ -399,7 +405,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u => {}, else => return anchor, }, - .errors, .pdf_links, .unsaved, .dir => return anchor, + .errors, .pdf_links, .unsaved, .dir, .preview => return anchor, } if (content.len == 0) return anchor; const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); diff --git a/src/Places.zig b/src/Places.zig index 435a138a..cff7c22e 100644 --- a/src/Places.zig +++ b/src/Places.zig @@ -207,7 +207,8 @@ pub fn search(set: *Places, p: *Pardes, pane: *Pane, provenance: Provenance, fro set.revision = f.revision +% 1; // `fill` starts it over for the text as it is set.seek = seek; set.seek_moves = moves; - set.fill(p, pane, frame_bytes, frame_steps); + // The keystroke's share: the view; the rest a frame's slice a tick. + set.fill(p, pane, 0, frame_steps); } /// A list's places in this text, as it gives them (sorted here), in place @@ -589,7 +590,7 @@ pub fn step(set: *Places, p: *Pardes, pane: *Pane, forward: bool, count: u32, ad /// Whether n and N in this pane are these places' to step: a list's or a /// query's always; a search's while it is what the register says (an `s`, /// a `/` elsewhere or `"a` since makes them helix's register search again). -pub fn answersN(set: *const Places, p: *Pardes, pane: *const Pane) bool { +pub fn answersN(set: *const Places, p: *Pardes, pane: *Pane) bool { if (!set.shows(pane) and !set.started) return false; if (set.provenance != .search) return p.register == 0; const name = if (p.register != 0) p.register else p.registers.last_search; @@ -634,10 +635,11 @@ pub fn forget(set: *Places, gpa: std.mem.Allocator) void { set.snap = &.{}; } -/// Where the query began: the primary selection's end when it was -/// remembered, else now. -pub fn origin(set: *const Places, pane: *const Pane) usize { - if (set.snap.len > 0) return @max(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); +/// Where the query began: the primary selection's start when it was +/// remembered, else now; a place there counts (helix's `/` from the +/// cursor). +pub fn origin(set: *const Places, pane: *Pane) usize { + if (set.snap.len > 0) return @min(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); const f = pane.file orelse return 0; const r = pane.body.primaryRange(f.content, 0); return @min(r.anchor, r.head); @@ -847,3 +849,28 @@ test "places: a big file costs a keystroke its view, the ticks find the rest, an if (std.c.getenv("PLACES_TIMES") != null) std.debug.print("places: first key {d} us, {d} ticks, an edit {d} us (the text's own splice {d} us)\n", .{ first_ns / 1000, ticks, edit_ns / 1000, text_ns / 1000 }); } + +test "zz stress analysis cost" { + const path = "/home/goblin/00-projects/0x4200.cafe/pardes-s-converge/.scratch/stress/src/layout.zig"; + if (std.c.getenv("PLACES_TIMES") == null) return error.SkipZigTest; + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(4 << 20)); + defer std.testing.allocator.free(bytes); + const syntax = @import("syntax.zig"); + syntax.start(std.testing.allocator); + defer syntax.stop(); + const tp = nowNs(); + const tree = syntax.parseTree(path, bytes); + const tq = nowNs(); + if (tree) |t| syntax.freeTree(t); + std.debug.print("parse alone {d} us\n", .{(tq - tp) / 1000}); + const t0 = nowNs(); + const d = try syntax.contextDeclarations(std.testing.allocator, path, bytes); + const t1 = nowNs(); + std.testing.allocator.free(d); + const a = try syntax.analyzeSource(std.testing.allocator, path, bytes, true, true); + const t2 = nowNs(); + std.testing.allocator.free(a.declarations); + std.testing.allocator.free(a.colors); + std.debug.print("decls {d} us ({d}), analysis with colours {d} us\n", .{ (t1 - t0) / 1000, d.len, (t2 - t1) / 1000 }); +} diff --git a/src/Query.zig b/src/Query.zig new file mode 100644 index 00000000..fbce95b2 --- /dev/null +++ b/src/Query.zig @@ -0,0 +1,2155 @@ +//! The query pane: the one pane search is. A +Search attached under the +//! pane that asked (its owner, layout.zig "Attached panes"), born at a +//! fixed height, whose body's line 1 is the query, editable text, and +//! whose rows below are made live from a source, read-only while live. +//! Line 1's first word names the source: `/pat` the owner's text (smart- +//! case regex), `Find pat` the files under its directory, `Grep pat` the +//! lines of those files, `Recent pat`, `Panes pat`, `Symbols pat` (the +//! owner's declarations), `All pat` (every open pane's text), and the +//! language server's `Refs`, `Def`, `Impl`, `Diagnostics`. Names are +//! matched fuzzy (Names.zig), text by regex. Editing the word changes +//! the source. +//! +//! The rows look like a Callstack's: the hit line with the match tinted +//! under a gutter line number, under the declaration it is in (when the +//! owner's parse exists: never made here on the loop), under its file +//! (Grep) or under `@pN name (count)` (All). They are addresses, all text: +//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into +//! an open pane's text, that pane's places (Places.zig) show the set: +//! tints, rail ticks, the current one selected. A row pointing at a file +//! no pane shows is shown in the +Preview attached under this pane; Enter +//! promotes the preview to the file's pane where it stands. +//! +//! Nothing moves while you type: the pane never closes, resizes or +//! rewrites line 1 on its own; zero hits is a state (`0` in the tag). +//! Enter lands on the current hit and freezes the rows into ordinary text; +//! Esc while typing puts every view back and closes the pane (or brings a +//! reused pane's frozen rows back); Del closes it. One per owner, reused +//! (SearchPane reuse|new). +const Query = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const edit = @import("edit.zig"); +const exec = @import("exec.zig"); +const layout = @import("layout.zig"); +const locations = @import("locations.zig"); +const look = @import("look.zig"); +const modal = @import("modal.zig"); +const normal = @import("normal.zig"); +const syntax = @import("syntax.zig"); +const tagline = @import("tagline.zig"); +const filesystem = @import("fs.zig"); +const colors = @import("colors.zig"); +const memory = @import("memory.zig"); +const Names = @import("Names.zig"); +const Places = @import("Places.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; +const Output = panes.Output; +const Key = pardes.Key; +const hit = pardes.hit; + +pub const Source = enum { text, find, grep, recent, panes, symbols, all, refs, defs, impls, diagnostics }; + +/// Line 1's words, each the source it names. `/` is vim's spelling, no +/// space after it; the others take one. +pub const words = [_]struct { word: []const u8, source: Source }{ + .{ .word = "Find", .source = .find }, + .{ .word = "Grep", .source = .grep }, + .{ .word = "Recent", .source = .recent }, + .{ .word = "Panes", .source = .panes }, + .{ .word = "Symbols", .source = .symbols }, + .{ .word = "All", .source = .all }, + .{ .word = "Refs", .source = .refs }, + .{ .word = "Def", .source = .defs }, + .{ .word = "Impl", .source = .impls }, + .{ .word = "Diagnostics", .source = .diagnostics }, +}; + +/// What a line 1 asks: its source and what follows its word. Null when it +/// starts with no word this knows (the user rewrote it): the rows say so. +pub fn parse(line: []const u8) ?struct { source: Source, pat: []const u8 } { + if (line.len > 0 and line[0] == '/') return .{ .source = .text, .pat = line[1..] }; + for (words) |w| { + if (std.mem.startsWith(u8, line, w.word) and (line.len == w.word.len or line[w.word.len] == ' ')) + return .{ .source = w.source, .pat = std.mem.trim(u8, line[w.word.len..], " \t") }; + } + return null; +} + +/// The word line 1 starts with for `source`, as typed after it. +pub fn wordOf(source: Source) []const u8 { + if (source == .text) return "/"; + for (words) |w| if (w.source == source) return w.word; + unreachable; +} + +/// A source whose rows can point at files no pane shows: its group is +/// made with a +Preview from the start, so nothing moves later. +fn previews(source: Source) bool { + return switch (source) { + .find, .grep, .recent, .refs, .defs, .impls, .diagnostics => true, + .text, .panes, .symbols, .all => false, + }; +} + +/// The most rows of hits a frozen list keeps: the rest are counted, and +/// said in a row. +pub const max_rows = 2000; +/// While typed, the rows are a window of this many around the current +/// place: the pane shows a few, and a row is two allocations a refill. +pub const live_rows = 100; + +/// One row's model, row `i + 1` of the pane (line 1 is the query): a hit, +/// a header (a declaration, a file, a pane) or a note. Where a row points +/// is in its locations.Row (path, at); a hit in an open pane's text also +/// knows its places there, `hit` and the `n` of them on its line. +pub const Item = struct { + kind: enum { hit, header, note }, + /// The pane whose text it is in (by serial), 0 when it is a file's. + serial: u32 = 0, + hit: usize = 0, + n: usize = 0, + /// A Panes row's pane, a Symbols row's line: Names.Cand.ref. + ref: u32 = 0, +}; + +/// A line a Grep found: its path and code in `found_bytes`. +pub const Found = struct { path: u32, path_len: u16, line: u32, col: u32, end: u32, code: u32, code_len: u32 }; + +/// The pane it answers for, by serial. +owner: u32, +/// Line 1 as the rows were last made for (gpa). +asked: []u8 = &.{}, +source: Source = .text, +/// Enter answered it: its rows are ordinary text from here, nothing remade. +frozen: bool = false, +items: std.ArrayList(Item) = .empty, +/// The current item, which Enter lands on and the places show. +current: ?usize = null, +/// The tag's `k/N`: how many places or names the rows are of, and where +/// the current one is among them (1-based; 0, none); `more` while counting. +total: usize = 0, +k: usize = 0, +more: bool = false, +/// What the rows were made of: the places' or names' generation and the +/// owner's text, so that a frame with nothing new makes nothing. +made_gen: u64 = std.math.maxInt(u64), +made_rev: u32 = 0, +/// The owner's revision seen last tick: rows follow an edit of the owner +/// once it has stood a frame (the rows refresh on idle frames). +seen_rev: u32 = 0, +/// The body cursor's row as last seen: B1, j or k on a row makes it current. +seen_row: i32 = 0, +/// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits. +window: struct { lo: usize = 0, hi: usize = 0 } = .{}, +/// Ticks the rows waited while the places are still being found: they are +/// made every third, the frame's time going to the finding. +waited: u8 = 0, +names: Names = .{}, +/// A Grep's lines, found a slice a frame (Query.grepSlice). +found: std.ArrayList(Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +grep_next: usize = 0, +grep_gen: u32 = 0, +/// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave +/// them (`path:line:col text`, gpa), filtered by what follows the word. +lsp_rows: []u8 = &.{}, +/// The +Preview under this pane, by serial; 0, none. +preview: u32 = 0, +/// A reused pane's frozen rows when a new query began in it: Esc brings +/// them back. +saved: ?Saved = null, + +pub const Saved = struct { + content: []u8, + rows: []locations.Row, + asked: []u8, + source: Source, + items: []Item, + current: ?usize, + total: usize, + k: usize, +}; + +pub fn deinit(q: *Query, gpa: std.mem.Allocator) void { + gpa.free(q.asked); + q.items.deinit(gpa); + q.names.deinit(gpa); + q.found.deinit(gpa); + q.found_bytes.deinit(gpa); + gpa.free(q.lsp_rows); + if (q.saved) |s| freeSaved(gpa, s); + q.* = undefined; +} + +fn freeSaved(gpa: std.mem.Allocator, s: Saved) void { + gpa.free(s.content); + locations.freeRows(gpa, s.rows); + gpa.free(s.asked); + gpa.free(s.items); +} + +/// The query pane `pane` is, if it is one. +pub fn of(pane: *Pane) ?*Query { + return pane.query; +} + +/// The owner's query pane (attached to it, or left where it was by +/// SearchPane new): the one a later search from it reuses. +pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize { + var found: ?usize = null; + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.owner != owner_serial) continue; + // the attached one first: an unattached one is a kept result + if (pane.attached_to == owner_serial) return i; + found = found orelse i; + } + return found; +} + +fn lineOne(content: []const u8) []const u8 { + return content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; +} + +// ---- opening ---- + +/// A search from pane `from`: its owner's query pane, made under the owner +/// (with a +Preview when `source` can need one) or reused, line 1 the +/// source's word and `arg`. With `focus` the keyboard goes to line 1's end +/// in insert mode, as to a prompt; without (`*`), it stays where it is. +pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: bool) void { + const asker = p.panes[from] orelse return; + // Asked from a query pane (`/` in it, its own SPC f g): its own line 1; + // from a +Preview, its query pane's. + var owner_id = from; + if (asker.query) |q| owner_id = p.paneBySerial(q.owner) orelse from else if (isPreview(p, asker)) |qid| { + owner_id = p.paneBySerial(p.panes[qid].?.query.?.owner) orelse from; + } + const owner = p.panes[owner_id] orelse return; + if (asker.query != null and arg.len == 0 and asker.query.?.source == source and !asker.query.?.frozen) { + // Back to typing the query it has. + if (focus) toLineOne(p, from); + return; + } + const line = std.mem.concat(p.scratch.allocator(), u8, &.{ wordOf(source), if (source == .text) "" else " ", arg }) catch return; + var id: usize = undefined; + const existing = ofOwner(p, owner.serial); + if (existing != null and (p.settings.search_pane == .reuse or existing.? == from)) { + id = existing.?; + const rp = p.panes[id].?; + const q = rp.query.?; + // Its frozen rows, kept for an Esc to bring back. + if (q.frozen and q.saved == null) q.saved = save(p, rp, q) catch null; + q.frozen = false; + const f = &rp.file.?; + const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return; + File.setContent(p, f, new); + q.reset(p); + if (rp.collapsed) layout.toggleCollapse(p, id); + } else { + if (existing) |old| { + // SearchPane new: the last one stays where it is, a result of + // its own; its places are the new one's to feed. + p.panes[old].?.attached_to = null; + } + id = create(p, owner_id, line, source) orelse return; + } + // Every view as the search found it, for Esc to put back. + owner.places.remember(p, owner); + // Before the first key: a names source lists every candidate at once. + produce(p, id, false); + // What a 9P exec reads back: the pane it filled (ninep/ctl.zig). + p.fs.refilled = p.panes[id].?.serial; + if (focus) toLineOne(p, id) else p.active = from; +} + +/// A new query pane under pane `owner_id`, `rows` of the owner's rows (the +/// SearchRows setting), its +Preview under it when `source` can need one. +fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize { + const owner = p.panes[owner_id] orelse return null; + const free = p.freeSlot() orelse { + p.reportError(owner_id, "search", error.NoPaneSlots); + return null; + }; + const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(owner); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return null; + const np = Output.open(p, free, dir, .search, "", content) catch |err| { + p.gpa.free(content); + p.reportError(owner_id, "search", err); + return null; + }; + const q = p.gpa.create(Query) catch { + p.reportError(owner_id, "search", error.OutOfMemory); + return null; + }; + q.* = .{ .owner = owner.serial }; + np.query = q; + const body: u16 = 1 + p.settings.search_rows; + const tag = @max(pardes.BOX_H, np.tag_rows); + const with_preview = previews(source); + // The preview, made right after, takes its own rows from the owner. + const want = tag + body; + if (p.settings.search_place == .column) { + // The finder column (phase 6): until it exists, under the owner. + if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + } else if (!layout.attach(p, owner_id, free, want)) { + // An owner too short to give a query pane its rows: placed as any + // new pane is, the one place a search moves another pane. + exec.placeNew(p, owner_id, owner_id, free, .doc); + } + if (with_preview) _ = makePreview(p, free); + return free; +} + +/// The keyboard to the end of line 1 of query pane `id`, in insert mode. +pub fn toLineOne(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + tagline.exitHeader(p); + p.active = id; + if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col); + rp.focus = .body; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + t.cur_row = 0; + t.cur_col = @intCast(lineOne(rp.file.?.content).len); + t.vsel.active = false; + t.nsel = 0; + t.cur_pinned = true; + rp.query.?.seen_row = 0; + edit.enterInsert(p, t, .line_end, 1); + showCurrent(rp); +} + +/// The rows' state for a new question: nothing found yet. +fn reset(q: *Query, p: *Pardes) void { + q.items.clearRetainingCapacity(); + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + q.made_gen = std.math.maxInt(u64); + p.gpa.free(q.asked); + q.asked = &.{}; +} + +fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { + const f = &rp.file.?; + const content = try p.gpa.dupe(u8, f.content); + errdefer p.gpa.free(content); + const rows = try p.gpa.alloc(locations.Row, f.location_rows.len); + var made: usize = 0; + errdefer { + for (rows[0..made]) |r| { + p.gpa.free(r.path); + p.gpa.free(r.colors); + } + p.gpa.free(rows); + } + for (f.location_rows, 0..) |r, i| { + rows[i] = r; + rows[i].path = try p.gpa.dupe(u8, r.path); + rows[i].colors = p.gpa.dupe(u8, r.colors) catch |err| { + p.gpa.free(rows[i].path); + return err; + }; + made += 1; + } + const asked = try p.gpa.dupe(u8, q.asked); + errdefer p.gpa.free(asked); + return .{ .content = content, .rows = rows, .asked = asked, .source = q.source, .items = try p.gpa.dupe(Item, q.items.items), .current = q.current, .total = q.total, .k = q.k }; +} + +// ---- making the rows ---- + +/// After every step: each live query pane whose line 1 changed, or whose +/// source has something new, has its rows made again. A walk takes a slice +/// on a tick. Nothing here is synchronous with an edit of the owner: its +/// places shift (Places.shift) and the rows follow once it stands a frame. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + if (pane.query == null) continue; + produce(p, id, tick); + } +} + +/// The frames a query pane still owes (a walk, scoring): nextWake's. +pub fn busy(p: *const Pardes) bool { + for (p.panes) |slot| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.frozen) continue; + if (q.names.busy() or (q.source == .grep and q.grep_next < q.names.cands.items.len) or q.made_rev != q.seen_rev) return true; + } + return false; +} + +fn produce(p: *Pardes, id: usize, tick: bool) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const f = if (rp.file) |*file| file else return; + const line = lineOne(f.content); + const changed = !std.mem.eql(u8, line, q.asked); + if (q.frozen and !changed) return; + if (q.frozen) { + // Line 1 of a frozen pane edited: it is a live query again. + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + q.frozen = false; + } + const owner_id = p.paneBySerial(q.owner); + const asked = parse(line); + if (changed) { + const was = q.source; + const new_asked = p.gpa.dupe(u8, line) catch return; + p.gpa.free(q.asked); + q.asked = new_asked; + q.made_gen = std.math.maxInt(u64); + if (asked) |a| { + if (a.source != was or q.names.cands.items.len == 0) startSource(p, id, q, a.source, owner_id); + q.source = a.source; + } + // The places this fed are another question's now. + if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked); + } + const a = asked orelse return noteRows(p, id, " line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n"); + // A row clicked or stepped onto (B1, j, k): current, and shown. + if (rp.body.cur_row != q.seen_row) { + q.seen_row = rp.body.cur_row; + if (rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { + const i: usize = @intCast(rp.body.cur_row - 1); + if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true); + } + } + switch (a.source) { + .text => { + const oid = owner_id orelse return noteRows(p, id, " the pane this searched is gone: Del, or / in another\n"); + const owner = p.panes[oid].?; + const of_ = owner.file orelse return noteRows(p, id, " a terminal's text is not searched here yet: / in a file\n"); + const set = &owner.places; + if (changed) { + if (a.pat.len == 0) { + if (set.from == rp.serial) set.clear(p.gpa); + set.restore(p, owner); + } else set.search(p, owner, .typed, rp.serial, a.pat, false, set.origin(owner), p.active == id); + } + // The owner edited: its places shifted at once; the rows follow + // once its text has stood a frame. + if (!changed and of_.revision != q.made_rev) { + if (!tick or of_.revision != q.seen_rev) { + q.seen_rev = of_.revision; + return; + } + } + q.seen_rev = of_.revision; + const gen: u64 = (@as(u64, set.hits_gen) << 32) | of_.revision; + if (gen == q.made_gen and !changed) return showPlacesCurrent(p, id); + if (a.pat.len > 0 and set.from != rp.serial) return; + if (!changed and !set.complete() and q.made_gen != std.math.maxInt(u64) and q.waited < 2) { + q.waited += 1; + return showPlacesCurrent(p, id); + } + q.waited = 0; + q.made_gen = gen; + q.made_rev = of_.revision; + makeTextRows(p, id, oid, false) catch |err| p.reportError(id, "search", err); + }, + .all => { + if (changed) for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (a.pat.len == 0) { + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + continue; + } + tp.places.search(p, tp, .list, rp.serial, a.pat, false, null, false); + }; + var gen: u64 = 0; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial) { + gen +%= tp.places.hits_gen +% (@as(u64, tp.serial) << 20); + }; + if (gen == q.made_gen and !changed) return; + if (!changed and !tick) return; + q.made_gen = gen; + makeAllRows(p, id) catch |err| p.reportError(id, "search", err); + }, + .find, .recent, .panes, .symbols => { + if (tick) q.names.walkSlice(p.gpa); + if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa); + if (q.names.gen == q.made_gen and !changed) return; + q.made_gen = q.names.gen; + makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + .grep => { + if (changed) { + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + q.grep_gen +%= 1; + } + if (a.pat.len == 0) { + if (changed) makeGrepRows(p, id) catch {}; + return; + } + if (tick or changed) { + q.names.walkSlice(p.gpa); + grepSlice(p, q, rp, a.pat); + } + const gen: u64 = (@as(u64, q.grep_gen) << 32) | q.found.items.len; + if (gen == q.made_gen and !changed and !(q.grep_next >= q.names.cands.items.len and q.more)) return; + q.made_gen = gen; + makeGrepRows(p, id) catch |err| p.reportError(id, "search", err); + if (changed or q.current == null) feedGrepPlaces(p, q, rp.serial, a.pat); + }, + .refs, .defs, .impls, .diagnostics => { + if (changed and q.lsp_rows.len == 0) { + // Typed, not answered: asked of the language server at the + // owner's cursor; its answer fills these rows (fillList). + // An answer opening the pane is no typing. + if (p.active != id) return; + if (owner_id) |oid| p.lspRequest(oid, switch (a.source) { + .refs => .references, + .defs => .definition, + .impls => .implementation, + else => .diagnostics, + }, ""); + return noteRows(p, id, " asked of the language server...\n"); + } + if (!changed) return; + makeListRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + } +} + +/// Whether pane `tp`'s text is one All searches: a file's or a list's, +/// not a query pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// A source begun: its candidates gathered (names), its walk started. +fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usize) void { + const rp = p.panes[id].?; + q.names.reset(); + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const gpa = p.gpa; + switch (source) { + .find, .grep => q.names.startWalk(gpa, dir) catch |err| p.reportError(id, "search", err), + .recent => { + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + Output.recentText(p, &out.writer, true) catch {}; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |ln| { + if (ln.len == 0) continue; + const rel = Names.relative(ln, dir); + const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len; + q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; + } + }, + .panes => for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + }, + .symbols => { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const f = if (owner.file) |*file| file else return; + const decls = ownerDecls(p, f, true) orelse return; + for (decls) |d| { + const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)]; + const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); + var buf: [256 + 16]u8 = undefined; + const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue; + q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; + } + }, + else => {}, + } +} + +/// The owner's declarations, from a parse that already exists: its sticky +/// headers' (TreeContext) at this revision, or the locations cache's. None +/// is made here, on the loop, unless `small` and the text is small: a +/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build. +/// ponytail: no grouping for a big file until the disk engine's worker +/// parses it (phase 4). +fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { + if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations; + const cache = &p.locations_cache; + for (cache.entries[0..cache.len]) |entry| { + if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; + } + if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null; + var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null; + if (got.owned) { + got.deinit(p.tree_sitter_gpa); + return null; + } + return got.analysis.declarations; +} + +/// A text this small is parsed on the loop for its declarations when a +/// Symbols query asks (about 40 ms in a Debug build). +const small_parse_bytes = 64 << 10; + +/// The rows as `note` says, and nothing else: no hits. +fn noteRows(p: *Pardes, id: usize, note: []const u8) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.items.append(p.gpa, .{ .kind = .note }) catch return; + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + writeRow(p, &out, &rows, note[0 .. note.len - 1], .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }) catch return; + setRows(p, rp, &out, &rows); +} + +/// One row: its text and its metadata, the path copied. +fn writeRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8, meta: locations.Row) !void { + try out.appendSlice(p.gpa, text); + try out.append(p.gpa, '\n'); + var m = meta; + m.path = try p.gpa.dupe(u8, meta.path); + errdefer p.gpa.free(m.path); + // Coloured whole (zeros where nothing coloured it): the pane's syntax + // pass then parses no fragment of it, per refill. + const code = text[@min(meta.code_start, text.len)..]; + m.colors = if (meta.colors.len >= code.len) try p.gpa.dupe(u8, meta.colors[0..code.len]) else blk: { + const c = try p.gpa.alloc(u8, code.len); + @memset(c, 0); + @memcpy(c[0..meta.colors.len], meta.colors); + break :blk c; + }; + rows.append(p.gpa, m) catch |err| { + p.gpa.free(m.path); + p.gpa.free(m.colors); + return err; + }; +} + +/// The rows made into the pane: line 1 as it is (the user's), then `out`, +/// with `rows` their metadata. The keyboard's place is left where it was. +fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) void { + defer locations.freeRowList(p.gpa, rows); + const f = &rp.file.?; + const line = lineOne(f.content); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n", out.items }) catch return; + const meta = p.gpa.alloc(locations.Row, rows.items.len + 1) catch { + p.gpa.free(content); + return; + }; + meta[0] = .{ .kind = .context, .path = p.gpa.dupe(u8, "") catch &.{}, .at = .{}, .location_end = 0, .code_start = 0 }; + @memcpy(meta[1..], rows.items); + rows.clearRetainingCapacity(); + const kept_row = rp.body.cur_row; + const kept_col = rp.body.cur_col; + if (std.mem.eql(u8, content, f.content)) { + // Same text: the metadata alone, no undo step, no syntax pass. + p.gpa.free(content); + if (locations.equalRows(f.location_rows, meta)) { + locations.freeRows(p.gpa, meta); + } else { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.syntax_dirty = true; + } + } else { + File.setContent(p, f, content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.saved_revision = f.revision; + } + gpa_free_pager(p, f); + // The cursor stays where it was typing; on a row that went, the last. + const last: i32 = @intCast(File.nlines(p.gpa, f) -| 1); + rp.body.cur_row = @min(kept_row, last); + rp.body.cur_col = if (rp.body.cur_row == kept_row) kept_col else 0; + if (rp.body.cur_row == 0 and rp.body.cur_col > line.len) rp.body.cur_col = @intCast(line.len); + rp.query.?.seen_row = rp.body.cur_row; +} + +fn gpa_free_pager(p: *Pardes, f: *File.State) void { + if (f.pager_spans.len == 0) return; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; +} + +/// The gutter a file of `nlines` lines numbers its rows in: two spaces, +/// the number right-aligned, two spaces. +fn gutterWidth(nlines: usize) usize { + var digits: usize = 1; + var n = nlines; + while (n >= 10) : (n /= 10) digits += 1; + return 2 + @max(3, digits) + 2; +} + +fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { + var lead: usize = 0; + while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1; + const code = std.mem.trimEnd(u8, whole[lead..], "\r"); + var buf: [4096 + 32]u8 = undefined; + var num: [24]u8 = undefined; + const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch ""; + const pad = width -| 2 -| number.len; + if (pad + number.len + 2 + code.len > buf.len) return; + @memset(buf[0..pad], ' '); + @memcpy(buf[pad..][0..number.len], number); + @memcpy(buf[pad + number.len ..][0..2], " "); + @memcpy(buf[pad + number.len + 2 ..][0..code.len], code); + const text = buf[0 .. pad + number.len + 2 + code.len]; + const gutter = pad + number.len + 2; + try writeRow(p, out, rows, text, .{ + .kind = .match, + .source_column = lead, + .path = @constCast(path), + .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, + .location_end = gutter, + .code_start = gutter, + .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}), + }); +} + +/// The path a row of pane `tp`'s text says: its file's, or `@pN` for a +/// text that is no file (a list, a scratch). +fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { + const f = tp.file orelse return ""; + if (f.output == null and !std.mem.startsWith(u8, std.fs.path.basename(f.path), "+")) return f.path; + return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch ""; +} + +/// Rows from pane `tp`'s places: one a line with any (two on a line are +/// one row: everywhere's bug), the declaration they are in over them when +/// its parse exists, from place `from` on, `budget` rows at most. The +/// place it stopped before. +fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize { + const f = &tp.file.?; + const set = &tp.places; + const hits = set.hits.items; + const index = try File.lineIndex(p.gpa, f); + const width = gutterWidth(index.len); + const path = addressOf(p.scratch.allocator(), tp); + const decls = ownerDecls(p, f, false) orelse &.{}; + var decl_now: ?usize = null; + var i: usize = @min(from, hits.len); + // the line of the first, found in the index + var line: usize = if (i < hits.len) blk: { + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= hits[i].start) lo = mid + 1 else hi = mid; + } + break :blk lo -| 1; + } else 0; + // a window begins at a line's first place + while (i > 0 and hits[i - 1].start >= index[line]) i -= 1; + while (i < hits.len) { + while (line + 1 < index.len and index[line + 1] <= hits[i].start) line += 1; + // the places on this line + var n: usize = 1; + const ls = index[line]; + const le = if (line + 1 < index.len) index[line + 1] - 1 else f.content.len; + while (i + n < hits.len and hits[i + n].start <= le) n += 1; + if (budget.* == 0) { + q.more = true; + break; + } + budget.* -= 1; + // the innermost declaration around it, its first line once + var inner: ?usize = null; + for (decls, 0..) |d, di| { + if (d.start_line > line) break; + if (d.end_line < line) continue; + inner = di; + } + if (inner != decl_now) { + decl_now = inner; + if (inner) |di| if (decls[di].start_line != line) { + const head_ls = index[decls[di].start_line]; + const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len; + const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r"); + var hb: [600]u8 = undefined; + const text = std.fmt.bufPrint(&hb, " {s}", .{head[0..@min(head.len, 560)]}) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 }); + }; + } + const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; + try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); + try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + i += n; + } + return i; +} + +/// The rows of a `/`: while typed, a window of `live_rows` around the +/// current place; `full` (frozen), the whole list up to `max_rows`. +fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[oid].?; + const set = &owner.places; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var budget: usize = if (full) max_rows else live_rows; + const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); + const from = if (full) 0 else at -| live_rows / 2; + q.window = .{ .lo = from, .hi = from }; + if (set.started and set.from == rp.serial) { + if (from > 0) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} places before these", .{from}) catch " ..."); + } + q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget); + q.window.lo = @min(from, q.window.hi); + } + if (q.more) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + showPlacesCurrent(p, id); +} + +fn noteRow(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8) !void { + try q.items.append(p.gpa, .{ .kind = .note }); + try writeRow(p, out, rows, text, .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }); +} + +/// The current row from the places of the pane its rows are in, the count +/// with them: for `/`, the owner's. +fn showPlacesCurrent(p: *Pardes, id: usize) void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; + const set = &owner.places; + q.total = if (set.from == rp.serial) set.hits.items.len else 0; + q.more = q.more or (set.from == rp.serial and !set.complete()); + q.k = if (set.current) |c| c + 1 else 0; + if (set.from != rp.serial) q.k = 0; + q.current = null; + // By line, not by the rows' place indices: the rows may lag the places + // a tick while they are still being found. + if (set.current) |c| if (c < set.hits.items.len) { + const at = lineOfOffset(p, &owner.file.?, set.hits.items[c].start) + 1; + const rows = rp.file.?.location_rows; + for (q.items.items, 0..) |it, i| { + if (it.kind != .hit or it.serial != owner.serial or i + 1 >= rows.len) continue; + if (rows[i + 1].at.line == at) { + q.current = i; + break; + } + } + }; + // Stepped out of the window the live rows are: made again around it. + if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); + showCurrent(rp); +} + +/// Every open pane's rows for All, grouped under `@pN name (count)` in +/// the order of the panes' serials (everywhere's other bug: it went by +/// column). +fn makeAllRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { + order[n] = i; + n += 1; + }; + std.mem.sort(usize, order[0..n], p, struct { + fn lt(pp: *Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + var budget: usize = max_rows; + q.total = 0; + for (order[0..n]) |tid| { + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp) or set.hits.items.len == 0) { + q.more = q.more or !set.complete(); + continue; + } + q.total += set.hits.items.len; + q.more = q.more or !set.complete(); + var hb: [600]u8 = undefined; + const name = if (tp.file) |f| Names.relative(f.path, std.fs.path.dirname(rp.file.?.path) orelse "") else ""; + const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); + _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget); + } + if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + // The current one: the first hit row, until a step moves it. + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +fn firstHit(q: *const Query) ?usize { + for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i; + return null; +} + +/// `k` from the current row: the hits on the rows before it, and its own. +fn countCurrent(q: *Query) void { + q.k = 0; + const c = q.current orelse return; + for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0; + q.k += 1; +} + +/// The names the query matches, best first, `Names.max_rows` of them: each +/// a row as its source has it, the matched bytes tinted. +fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { + _ = pat; + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const was_current: ?u32 = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].ref else null) else null; + _ = was_current; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var spans: std.ArrayList(pardes.pager.Span) = .empty; + errdefer spans.deinit(p.gpa); + const chrome = p.bodyChrome(); + const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; + const shown = @min(q.names.hits.items.len, Names.max_rows); + var marks: [Names.max_query * 4]u16 = undefined; + const base = lineOne(rp.file.?.content).len + 1; + for (0..shown) |i| { + var nmarks: usize = 0; + const row = q.names.row(i, &marks, &nmarks); + const cand = q.names.cands.items[q.names.hits.items[i].cand]; + const at = base + out.items.len; + // Where it points: a path (Find, Recent), a pane (Panes), a line + // of the owner (Symbols). + var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; + var pathbuf: [4096 + 32]u8 = undefined; + switch (q.source) { + .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .recent => { + const t = look.parsePathLine(row); + meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); + meta.at = t.at; + }, + .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch ""), + .symbols => { + const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; + meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); + meta.at = .{ .line = cand.ref }; + }, + else => {}, + } + try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); + try writeRow(p, &out, &rows, row, meta); + var k: usize = 0; + while (k < nmarks) { + var e = k + 1; + while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + k = e; + } + } + if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + setRows(p, rp, &out, &rows); + const f = &rp.file.?; + f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; + q.total = q.names.hits.items.len; + q.more = q.names.busy(); + // The best is current until a step or a click moves it. + q.current = if (shown > 0) 0 else null; + countCurrent(q); + showCurrent(rp); + showTarget(p, id); +} + +/// A slice of a Grep: the files the walk has found so far read and +/// searched, about 4 ms of them a frame, each line holding the pattern +/// (a literal, smart case: a capital makes it exact) kept. +/// ponytail: on the loop, a file a step; the disk engine's worker (phase +/// 4) takes this over. +fn grepSlice(p: *Pardes, q: *Query, rp: *Pane, pat: []const u8) void { + const started = Places.nowNs(); + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const fold = for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true; + var low_buf: [256]u8 = undefined; + const needle = if (fold) std.ascii.lowerString(low_buf[0..@min(pat.len, low_buf.len)], pat[0..@min(pat.len, low_buf.len)]) else pat; + while (q.grep_next < q.names.cands.items.len) { + if (q.found.items.len >= grep_cap) break; + const c = q.names.cands.items[q.grep_next]; + q.grep_next += 1; + const rel = q.names.bytes.items[c.start..][0..c.len]; + var pathbuf: [4096 + 8]u8 = undefined; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch continue; + }; + defer p.gpa.free(bytes); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) continue; + var line_no: u32 = 1; + var ls: usize = 0; + while (ls <= bytes.len) { + const le = std.mem.indexOfScalarPos(u8, bytes, ls, '\n') orelse bytes.len; + const ln = bytes[ls..le]; + const at = if (fold) std.ascii.findIgnoreCase(ln, needle) else std.mem.indexOf(u8, ln, needle); + if (at) |col| { + const path_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, rel) catch return; + const code_at: u32 = @intCast(q.found_bytes.items.len); + const code = ln[0..@min(ln.len, 400)]; + q.found_bytes.appendSlice(p.gpa, code) catch return; + q.found.append(p.gpa, .{ .path = path_at, .path_len = @intCast(rel.len), .line = line_no, .col = @intCast(col), .end = @intCast(col + needle.len), .code = code_at, .code_len = @intCast(code.len) }) catch return; + if (q.found.items.len >= grep_cap) break; + } + if (le == bytes.len) break; + ls = le + 1; + line_no += 1; + } + if (started != 0 and Places.nowNs() - started > Places.frame_ns) break; + } +} + +/// A Grep keeps this many lines: the rest wait (the disk engine's `More`). +pub const grep_cap = 2000; + +fn makeGrepRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + for (q.found.items, 0..) |fd, i| { + const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + if (!std.mem.eql(u8, rel, last_path)) { + last_path = rel; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); + try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); + } + const walking = q.names.walking() or q.grep_next < q.names.cands.items.len; + if (q.found.items.len >= grep_cap) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: type more of it"); + setRows(p, rp, &out, &rows); + q.total = q.found.items.len; + q.more = walking and q.found.items.len < grep_cap; + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +/// A Grep's hits in each open file are that pane's places: its tints, +/// ticks and n/N. +fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void { + _ = q; + for (p.panes) |slot| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output != null or tp.query != null) continue; + tp.places.search(p, tp, .list, serial, pat, true, null, false); + } +} + +/// The language server's answer for an owner's Refs, Def, Impl or +/// Diagnostics, into its query pane (made or reused) with line 1 the word: +/// what follows the word filters the rows; the places in the owner's text +/// are its places. `rows` are `path:line:col text`, as the server's +/// answer is written (lsp_client). +pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) void { + const owner = p.panes[owner_id] orelse return; + var id = ofOwner(p, owner.serial); + if (id == null or p.panes[id.?].?.query.?.source != source) { + open(p, owner_id, source, "", false); + id = ofOwner(p, owner.serial); + } + const qid = id orelse return; + const rp = p.panes[qid].?; + const q = rp.query.?; + const copy = p.gpa.dupe(u8, rows) catch return; + p.gpa.free(q.lsp_rows); + q.lsp_rows = copy; + const line = lineOne(rp.file.?.content); + const a = parse(line) orelse return; + makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); + toLineOne(p, qid); +} + +fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + const owner_id = p.paneBySerial(q.owner); + const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; + var feed: std.ArrayList(Places.Hit) = .empty; + defer feed.deinit(p.gpa); + // In order: by path, then place, as a list of places reads. + var sorted: std.ArrayList([]const u8) = .empty; + defer sorted.deinit(p.gpa); + var split = std.mem.splitScalar(u8, q.lsp_rows, '\n'); + while (split.next()) |ln| if (ln.len > 0) try sorted.append(p.gpa, ln); + std.mem.sort([]const u8, sorted.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + const ta = look.parsePathLine(a); + const tb = look.parsePathLine(b); + const order = std.mem.order(u8, ta.path, tb.path); + if (order != .eq) return order == .lt; + if (ta.at.line != tb.at.line) return ta.at.line < tb.at.line; + return ta.at.col < tb.at.col; + } + }.lt); + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + var n: usize = 0; + for (sorted.items) |ln| { + if (ln.len == 0) continue; + if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; + const t = look.parsePathLine(ln); + if (t.at.line == 0) continue; + const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + if (!std.mem.eql(u8, t.path, last_path)) { + last_path = t.path; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); + const col0 = t.at.col -| 1; + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); + // The row's text: the line in the owner when it is the owner's, + // else as the server said it. + var code: []const u8 = rest; + var col = col0; + var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; + if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { + const owner_f = &p.panes[oid].?.file.?; + if (t.at.line <= File.nlines(p.gpa, owner_f)) { + const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); + const nx = File.lineStart(p.gpa, owner_f, t.at.line); + const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; + code = owner_f.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + } + } else { + col = 0; + end = 0; + }; + try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); + n += 1; + } + if (n == 0) try noteRow(p, q, &out, &rows, " nothing"); + setRows(p, rp, &out, &rows); + q.total = n; + q.more = false; + q.current = firstHit(q); + if (owner_id) |oid| { + const owner = p.panes[oid].?; + // Current: the first place after where it was asked (the answer + // may come after the cursor moved), shown in the owner. + const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); + owner.places.feed(p, owner, rp.serial, feed.items, null); + const hits = owner.places.hits.items; + var next: ?usize = null; + for (hits, 0..) |h, i| if (h.start > asked_at) { + next = i; + break; + }; + if (next == null and hits.len > 0) next = 0; + if (next) |hi| { + owner.places.goTo(owner, hi, false); + for (q.items.items, 0..) |it, i| if (it.kind == .hit and i + 1 < rp.file.?.location_rows.len) { + const meta = rp.file.?.location_rows[i + 1]; + if (!std.mem.eql(u8, meta.path, owner_path)) continue; + const ls = File.lineStart(p.gpa, &owner.file.?, meta.at.line -| 1); + if (ls + meta.at.col -| 1 == hits[hi].start) { + q.current = i; + break; + } + }; + } + } + countCurrent(q); + showCurrent(rp); +} + +/// The places query `serial` fed in panes other than the owner, cleared +/// (a new source or pattern makes its own); the owner's too when the new +/// line is no `/`. +fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anytype) void { + _ = q; + _ = asked; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (tp.places.from != serial) continue; + if (owner_id != null and owner_id.? == i) tp.places.restore(p, tp); + tp.places.clear(p.gpa); + } +} + +// ---- the current row ---- + +/// The current row drawn as the visited row is (a line selection), while +/// the keyboard is on line 1 or elsewhere; on the rows, the cursor itself +/// is current. Scrolled into view, line 1 kept when it can be. +fn showCurrent(rp: *Pane) void { + const q = rp.query orelse return; + if (rp.body.cur_row != 0 and rp.focus == .body) return; + const c = q.current orelse { + rp.body.msel.active = false; + return; + }; + const r: i32 = @intCast(c + 1); + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + const off = rp.scroll(); + const shown = off + @as(i32, rp.rows) - 1; + if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); +} + +/// The line (0-based) of byte `at` of `f`'s text. +fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize { + const index = File.lineIndex(p.gpa, f) catch return 0; + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= at) lo = mid + 1 else hi = mid; + } + return lo -| 1; +} + +/// The first of pane `tp`'s places on line `line` (1-based), if any. +fn placeOnLine(p: *Pardes, tp: *Pane, line: usize) ?usize { + const f = &tp.file.?; + if (line == 0 or line > File.nlines(p.gpa, f)) return null; + const ls = File.lineStart(p.gpa, f, line - 1); + const next = File.lineStart(p.gpa, f, line); + const hits = tp.places.hits.items; + const i = Places.firstFrom(hits, ls); + if (i < hits.len and (hits[i].start < next or (next == ls))) return i; + return null; +} + +/// Item `i` current, and shown where it points (`show`). +fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.current = i; + const it = q.items.items[i]; + const rows = rp.file.?.location_rows; + if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { + const tp = p.panes[tid].?; + if (placeOnLine(p, tp, rows[i + 1].at.line)) |hi| { + tp.places.current = hi; + tp.places.gen +%= 1; + if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); + } else countCurrent(q); + } else countCurrent(q) else countCurrent(q); + showCurrent(rp); + if (show) showTarget(p, id); +} + +/// Step the current row `delta` hits on, round the end silently: Ctrl-n, +/// Ctrl-p, Down and Up on line 1, n and N in the pane. +pub fn step(p: *Pardes, id: usize, delta: i32) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + // A `/`: the owner's places step, the rows follow them. + if (q.source == .text) if (p.paneBySerial(q.owner)) |oid| { + const owner = p.panes[oid].?; + if (owner.places.from == rp.serial) { + const keyboard = p.active; + owner.places.step(p, owner, delta > 0, 1, false); + p.active = keyboard; + showPlacesCurrent(p, id); + return; + } + }; + const items = q.items.items; + if (items.len == 0) return; + var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); + for (0..items.len) |_| { + if (delta > 0) i = if (i + 1 >= items.len) 0 else i + 1 else i = if (i == 0) items.len - 1 else i - 1; + if (items[i].kind == .hit) break; + } else return; + setCurrent(p, id, i, true); +} + +/// Where the current row points, shown with the keyboard left where it is: +/// a place in an open pane's text selected there (its places' current), +/// in view; a file an open pane shows, its line there; any other file in +/// the +Preview under this pane. Every pane it moves remembers its view +/// first, for Esc. +fn showTarget(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const c = q.current orelse return; + const f = &rp.file.?; + if (c + 1 >= f.location_rows.len) return; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + const keyboard = p.active; + defer p.active = keyboard; + if (it.serial != 0) { + const tid = p.paneBySerial(it.serial) orelse return; + const tp = p.panes[tid].?; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + if (placeOnLine(p, tp, meta.at.line)) |hi| tp.places.goTo(tp, hi, false); + return; + } + if (q.source == .symbols) { + const oid = p.paneBySerial(q.owner) orelse return; + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + } + if (q.source == .panes) return; + if (meta.path.len == 0) return; + // A file open in a pane: shown there. + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, meta.path)) continue; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + const line0 = meta.at.line -| 1; + const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows; + if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center); + return; + } + displayPreview(p, id, meta.path, meta.at); +} + +// ---- the +Preview ---- + +/// The +Preview under query pane `qid`, if it has one: by serial. +fn previewOf(p: *Pardes, qid: usize) ?usize { + const q = p.panes[qid].?.query.?; + if (q.preview == 0) return null; + return p.paneBySerial(q.preview) orelse { + q.preview = 0; + return null; + }; +} + +/// Whether `pane` is a query pane's +Preview: that query pane's slot. +pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { + const f = pane.file orelse return null; + const o = f.output orelse return null; + if (o.from != .preview) return null; + for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; + return null; +} + +/// A +Preview made under query pane `qid`, out of its rows alone. +fn makePreview(p: *Pardes, qid: usize) ?usize { + const rp = p.panes[qid].?; + const free = p.freeSlot() orelse return null; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const content = p.gpa.dupe(u8, "") catch return null; + const np = Output.open(p, free, dir, .preview, "", content) catch { + p.gpa.free(content); + return null; + }; + layout.compute(p); + const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; + // Out of the group's root, the text that asked: the query pane keeps + // the rows it was typed into with (made later, for a reused pane). + if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + p.removePane(free, qid) catch {}; + return null; + } + rp.query.?.preview = np.serial; + return free; +} + +/// File `path` at `at` in the +Preview: its text read (once a file: a +/// file open in a pane would be shown there instead), the place centred +/// and selected. Made when the pane has none and its owner has the rows. +fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { + const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const pane = p.panes[id].?; + const f = &pane.file.?; + if (!std.mem.eql(u8, f.path, path)) { + if (exec.kindOf(path)) |kind| if (kind != .file) return; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch return; + }; + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const owned_path = p.gpa.dupe(u8, path) catch { + p.gpa.free(bytes); + return; + }; + p.gpa.free(f.path); + f.path = owned_path; + File.setContent(p, f, bytes); + f.saved_revision = f.revision; + f.scroll = 0; + f.syntax_dirty = true; + pane.hscroll = 0; + p.sync(); + } + look.clearNavigationSelection(p, pane); + if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { + f.scroll = 0; + f.syntax_dirty = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + return; + } + look.focusPaneLine(p, id, at, .center); + if (at.end_line == 0 or at.end_col <= at.col) + pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) }; +} + +/// The +Preview becomes the file's pane where it stands: same slot, same +/// serial, same rect, its scroll and selection as the preview left them. +/// It is a file pane from here: an empty undo history, the Recent entry, +/// the watch, a file's tag; and a pane of its own, no longer attached (it +/// stays when its query pane goes). +fn promote(p: *Pardes, qid: usize, id: usize) void { + const pane = p.panes[id] orelse return; + const f = &pane.file.?; + f.output = null; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; + f.saved_revision = f.revision; + f.saved_hash = null; + f.saved_len = null; + f.disk_gone = false; + f.syntax_dirty = true; + pane.attached_to = null; + if (Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path); + if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + pardes.ctlfs.events.noteLog(p, .rename, pane); + p.panes[qid].?.query.?.preview = 0; +} + +// ---- Enter, Esc ---- + +/// Enter on line 1 (or on a row, `row`): the keyboard to the current hit +/// in its pane (the +Preview promoted to the file's pane when it shows +/// it), a `/` into the register, and the rows frozen into ordinary text. +pub fn land(p: *Pardes, id: usize, row: ?usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true); + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + freeze(p, id); + const owner_id = p.paneBySerial(q.owner); + if (q.source == .text) { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const set = &owner.places; + // The whole list now, once, every place found: a result from here. + if (set.started and set.from == rp.serial) { + set.fill(p, owner, std.math.maxInt(usize), @import("regexp.zig").Regex.budget); + makeTextRows(p, id, oid, true) catch {}; + } + if (set.started and set.from == rp.serial) { + if (set.literal) { + var escaped: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&escaped, p.scratch.allocator(), set.pattern) catch {}; + p.registers.put(p.gpa, '/', escaped.items, 0, 1, true); + } else p.registers.put(p.gpa, '/', set.pattern, 0, 1, true); + p.registers.last_search = '/'; + set.provenance = .search; + } + p.jump_force = true; + p.active = oid; + return; + } + const c = q.current orelse { + if (owner_id) |oid| p.active = oid; + return; + }; + const f = &rp.file.?; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + p.jump_force = true; + if (it.serial != 0) { + if (p.paneBySerial(it.serial)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + } + return; + } + switch (q.source) { + .symbols => if (owner_id) |oid| { + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + }, + .panes => if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + }, + else => {}, + } + // The preview shows it: promoted where it stands. + if (previewOf(p, id)) |pid| if (std.mem.eql(u8, p.panes[pid].?.file.?.path, meta.path)) { + promote(p, id, pid); + p.active = pid; + if (q.source == .grep) { + const a = parse(q.asked) orelse return; + const pp = p.panes[pid].?; + pp.places.search(p, pp, .list, rp.serial, a.pat, true, null, false); + } + return; + }; + var buf: [4096 + 64]u8 = undefined; + const address = if (meta.at.line > 0) + std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path + else + meta.path; + look.lookAt(p, id, address); +} + +/// The rows frozen: ordinary text from here, Save works on them; the +/// places they fed stay, while the pane lives; every view stays where the +/// search left it; the preview, of no more use, goes. +fn freeze(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + q.frozen = true; + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial or tp.serial == q.owner) tp.places.forget(p.gpa); + if (previewOf(p, id)) |pid| { + const pv = p.panes[pid].?; + // A preview showing the current row is promoted by `land`: one + // showing another file goes. + _ = pv; + } +} + +/// Esc on line 1 while typing: every view as the search found it, the +/// places it fed gone, and the pane closed (nothing was answered); a +/// reused pane's frozen rows come back instead, and their places. +pub fn cancel(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + const owner_id = p.paneBySerial(q.owner); + for (p.panes) |slot| if (slot) |tp| { + if (tp.places.from != rp.serial and tp.serial != q.owner) continue; + tp.places.restore(p, tp); + tp.places.forget(p.gpa); + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; + if (q.saved) |s| { + q.saved = null; + // A preview made for the query Esc took back has no use: its rows + // go to the text whose rows they were. + if (previewOf(p, id)) |pid| { + p.panes[pid].?.attached_to = null; + p.removePane(pid, owner_id) catch {}; + q.preview = 0; + } + const f = &rp.file.?; + File.setContent(p, f, s.content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = s.rows; + p.gpa.free(q.asked); + q.asked = s.asked; + q.source = s.source; + q.items.clearRetainingCapacity(); + q.items.appendSlice(p.gpa, s.items) catch {}; + p.gpa.free(s.items); + q.current = s.current; + q.total = s.total; + q.k = s.k; + q.frozen = true; + rp.body.cur_row = 0; + rp.body.cur_col = 0; + showCurrent(rp); + // Its places again, as Enter left them. + if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { + const owner = p.panes[oid].?; + owner.places.search(p, owner, .search, rp.serial, a.pat, false, null, false); + }; + if (owner_id) |oid| p.active = oid; + return; + } + if (owner_id) |oid| { + p.removePane(id, oid) catch {}; + p.active = oid; + if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); + } else p.removePane(id, null) catch {}; +} + +/// The pane going (Del, its owner's Del): the places it fed go with it. +pub fn release(p: *Pardes, pane: *Pane) void { + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) { + tp.places.forget(p.gpa); + tp.places.clear(p.gpa); + }; +} + +// ---- keys, the mouse, edits ---- + +/// The keys a query pane answers itself, before its text has them. On +/// line 1, typing: Enter lands, Esc cancels, Ctrl-n, Ctrl-p, Down and Up +/// step the current row. In normal mode: Enter on a hit row lands on it, +/// n and N step. Anything else is ordinary text editing (line 1) or is +/// refused (the rows, while live: clampEdit). Tab stays the exec chord. +pub fn key(p: *Pardes, id: usize, k: Key) bool { + const rp = p.panes[id] orelse return false; + const q = rp.query orelse return false; + if (rp.focus != .body) return false; + const t = &rp.body; + if (q.frozen) return false; + if (t.mode == .normal) { + if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; + if (k.cp == 'n' or k.cp == 'N') { + step(p, id, if (k.cp == 'n') 1 else -1); + return true; + } + if (hit(k, config.look_key) and t.cur_row > 0) { + land(p, id, @intCast(t.cur_row - 1)); + return true; + } + return false; + } + if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false; + if (hit(k, config.escape)) { + cancel(p, id); + return true; + } + if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) { + land(p, id, null); + return true; + } + const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); + const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + if (down or up) { + step(p, id, if (down) 1 else -1); + return true; + } + return false; +} + +/// An edit of a live query pane's text (edit.setEditTextSpan): inside line +/// 1, as typed; one from line 1 into the rows, cut at line 1's end (and a +/// newline put in it, a blank); one wholly in the rows refused, as a tag's +/// prefix refuses one. Null: refused. Lifted from queryline. +pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { + const end = std.mem.indexOfScalar(u8, old, '\n') orelse old.len; + const span = File.spanOf(old, new); + const old_to = old.len - span.tail; + const put = new[span.head .. new.len - span.tail]; + const rows_same = old_to <= end and std.mem.indexOfScalar(u8, put, '\n') == null; + if (rows_same) return new; + if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) { + t.refused = true; + if (t.pane()) |pane| if (p.paneIdOf(pane)) |id| + p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)"); + return null; + } + // From inside line 1 into the rows: what it put in, flat, and what is + // left of line 1 after it; the rows as they were. + const kept = if (old_to < end) old[old_to..end] else ""; + const out = std.mem.concat(p.gpa, u8, &.{ old[0..span.head], put, kept, old[end..] }) catch return null; + for (out[0 .. span.head + put.len + kept.len]) |*c| if (c.* == '\n') { + c.* = ' '; + }; + return out; +} + +/// B3 on a row's gutter (its line number): the row's address, as a +Diff +/// line's prefix is its place (exec.operandAt). Null off a gutter. +pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 { + if (pane.query == null) return null; + const f = pane.file orelse return null; + if (row == 0 or row >= f.location_rows.len) return null; + const meta = f.location_rows[row]; + if (meta.kind != .match or meta.path.len == 0 or meta.location_end == 0 or col >= meta.location_end) return null; + if (meta.at.line == 0) return std.fmt.bufPrint(buf, "{s}", .{meta.path}) catch null; + return std.fmt.bufPrint(buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch null; +} + +/// The tag's start for a query pane: its name and where it is, `+Search +/// 3/27`, `0` with nothing found, `+` while it still counts. +pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![]const u8 { + const name = std.fs.path.basename(path); + const more = if (q.more and !q.frozen) "+" else ""; + if (q.total == 0) return std.fmt.allocPrint(arena, "{s} 0{s}", .{ name, more }); + if (q.k == 0) return std.fmt.allocPrint(arena, "{s} {d}{s}", .{ name, q.total, more }); + return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more }); +} + +/// The other places on a hit row's line tinted, from the pane its rows are +/// in (the first is the row's own mark, Output.decorateRow): the current +/// one strongest, as in that pane's text. +pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const q = pane.query orelse return; + const f = if (pane.file) |*file| file else return; + const th = p.theme(); + const strong = p.chromeTheme().search_bg; + const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + var vr: i32 = 0; + var last: i32 = -1; + while (vr < body_h) : (vr += 1) { + const row = pane.wrapAt(vr).line; + if (row == last or row < 1) continue; + last = row; + const i: usize = @intCast(row - 1); + if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue; + const it = q.items.items[i]; + if (it.kind != .hit or it.serial == 0) continue; + const tid = p.paneBySerial(it.serial) orelse continue; + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp)) continue; + const tf = &tp.file.?; + const meta = f.location_rows[@intCast(row)]; + // Its line's places as they are now, found by the line: the rows + // may be a tick behind the places. + if (meta.at.line == 0 or meta.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, meta.at.line - 1); + const next = File.lineStart(p.gpa, tf, meta.at.line); + const line = modal.lineSlice(f.content, @intCast(row)); + var hi = Places.firstFrom(set.hits.items, ls); + while (hi < set.hits.items.len and set.hits.items[hi].start < next) : (hi += 1) { + const h = set.hits.items[hi]; + if (h.start < ls + meta.source_column) continue; + const a = meta.code_start + (h.start - ls - meta.source_column); + const b = @min(line.len, meta.code_start + (@min(h.end, next) - ls - meta.source_column)); + if (b <= a or a >= line.len) continue; + const current = set.current != null and set.current.? == hi; + File.paintWordSelection(p, s, pane, r, row, @intCast(a), @intCast(b), if (current) strong else quiet); + } + } +} + +// ---- tests ---- + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn queryPane(p: *Pardes) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null) return i; + return null; +} + +test "parse: line 1's first word names the source" { + try std.testing.expectEqual(Source.text, parse("/alpha").?.source); + try std.testing.expectEqualStrings("alpha", parse("/alpha").?.pat); + try std.testing.expectEqual(Source.find, parse("Find lay").?.source); + try std.testing.expectEqualStrings("lay", parse("Find lay").?.pat); + try std.testing.expectEqual(Source.grep, parse("Grep").?.source); + try std.testing.expectEqual(Source.all, parse("All x y").?.source); + try std.testing.expectEqualStrings("x y", parse("All x y").?.pat); + try std.testing.expectEqual(Source.refs, parse("Refs").?.source); + try std.testing.expect(parse("Findx") == null); + try std.testing.expect(parse("grep x") == null); + try std.testing.expect(parse("") == null); +} + +test "a / query: keystroke by keystroke, the owner shows the set, rows from its own rows alone, zero hits a state, Esc puts all back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + p.newScratchBelow(0); + const below = p.col_panes[0][1]; + p.active = 0; + layout.compute(p); + const before = p.rects; + // cursor on line 3 (row 2) + pane.body.cur_row = 2; + pane.body.cur_col = 0; + typeKeys(p, "/"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid)); + try std.testing.expectEqual(qid, p.active); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + const born = p.rects[qid]; + try std.testing.expectEqualStrings("/", lineOne(qp.file.?.content)); + // keystroke 1 + typeKeys(p, "a"); + const q = qp.query.?; + try std.testing.expectEqual(Source.text, q.source); + try std.testing.expect(pane.places.started and pane.places.from == qp.serial); + try std.testing.expect(q.total > 0); + try std.testing.expectEqualDeep(born, p.rects[qid]); + // keystroke 2 .. `alph`: four places on four lines (rows), the + // current the first at or after the cursor (line 3's alphabet) + typeKeys(p, "lph"); + try std.testing.expectEqual(@as(usize, 4), q.total); + try std.testing.expectEqual(@as(usize, 2), q.k); + try std.testing.expectEqual(@as(?usize, 1), pane.places.current); + const sel = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 15), @min(sel.anchor, sel.head)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expectEqual(qid, p.active); + // Ctrl-n steps, the owner follows + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(usize, 3), q.k); + // drawn: rows, tints, ticks + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + try std.testing.expect(p.surface.nrail_ticks > 0); + // zero hits: a state, the pane stays where it was, line 1 as typed + typeKeys(p, "zz"); + try std.testing.expectEqual(@as(usize, 0), q.total); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expectEqualStrings("/alphzz", lineOne(qp.file.?.content)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + const tag = try tagline.pathPrefix(p, p.scratch.allocator(), qp); + try std.testing.expectEqualStrings("+Search 0", tag); + // Esc: the pane gone, its rows back to the owner, the owner as it was + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expectEqual(@as(usize, 0), p.active); + layout.compute(p); + try std.testing.expectEqualDeep(before[0], p.rects[0]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expect(!pane.places.started); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); +} + +test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + typeKeys(p, "/alpha"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(q.frozen); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("alpha", p.registers.value('/', 0).?); + try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance); + const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content); + defer std.testing.allocator.free(frozen); + // the rows: one a line (gamma alpha has one), a gutter number each + try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); + // n and N in the owner step the same set, round the end silently + const logged = p.messages.len; + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + typeKeys(p, "nnn"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + try std.testing.expect(pane.places.wrapped); + try std.testing.expectEqual(logged, p.messages.len); + typeKeys(p, "N"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + // a later `/` reuses the pane: line 1 fresh, the rows the new query's + typeKeys(p, "/"); + try std.testing.expectEqual(qid, queryPane(p).?); + try std.testing.expectEqual(qid, p.active); + try std.testing.expect(!q.frozen); + typeKeys(p, "beta"); + try std.testing.expectEqual(@as(usize, 1), q.total); + // Esc: the frozen rows of `/alpha` again, the owner's places with them + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expect(q.frozen); + try std.testing.expectEqualStrings(frozen, qp.file.?.content); + try std.testing.expectEqualStrings("alpha", pane.places.pattern); + // Del closes it, its places with it + exec.runBuiltin(p, .Del, qid, "", null); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!pane.places.started); +} + +/// A test's file pane in `tmp`, named `name`, holding `text`. +fn testFileIn(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) !*Pane { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, name }); + return pane; +} + +fn leader(p: *Pardes, keys: []const u8) void { + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + typeKeys(p, keys); +} + +fn settle(p: *Pardes) void { + var frames: usize = 0; + while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick); + p.update(.tick); +} + +test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "src"); + for ([_][]const u8{ "src/layout.zig", "src/look.zig", "notes.md" }) |name| + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "pub fn split() void {}\nconst x = 1;\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "x.txt", "x\n"); + p.newScratchBelow(0); + const other = p.col_panes[0][1]; + try std.testing.expect(layout.splitColumn(p, other, other, false)); + p.active = 0; + layout.compute(p); + const before = p.rects; + leader(p, "ff"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + try std.testing.expectEqual(Source.find, q.source); + try std.testing.expectEqualStrings("Find ", lineOne(p.panes[qid].?.file.?.content)); + // the group: owner, query pane, +Preview, out of the owner's rows alone + const pv = previewOf(p, qid).?; + try std.testing.expectEqual(@as(usize, 0), layout.groupRoot(p, pv)); + try std.testing.expectEqualDeep(before[other], p.rects[other]); + try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[qid].h + p.rects[pv].h); + settle(p); + // an empty query lists every name + try std.testing.expectEqual(@as(usize, 4), q.total); + const born = p.rects; + typeKeys(p, "lay"); + settle(p); + try std.testing.expectEqual(@as(usize, 1), q.total); + try std.testing.expectEqualDeep(born[qid], p.rects[qid]); + try std.testing.expectEqualDeep(born[pv], p.rects[pv]); + // the current one in the preview, never by the pointer + try std.testing.expect(std.mem.endsWith(u8, p.panes[pv].?.file.?.path, "src/layout.zig")); + try std.testing.expectEqual(qid, p.active); + const serial = p.panes[pv].?.serial; + const rect = p.rects[pv]; + p.update(.{ .key = .{ .cp = Key.enter } }); + // promoted where it stands: same slot, serial, rect; a file pane now + try std.testing.expectEqual(pv, p.active); + try std.testing.expectEqual(serial, p.panes[pv].?.serial); + try std.testing.expect(p.panes[pv].?.file.?.output == null); + try std.testing.expect(p.panes[pv].?.attached_to == null); + layout.compute(p); + try std.testing.expectEqualDeep(rect, p.rects[pv]); + try std.testing.expect(q.frozen); + try std.testing.expectEqualDeep(before[other], p.rects[other]); +} + +test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "one needle\ntwo\n"); + leader(p, "fg"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + typeKeys(p, "needle"); + settle(p); + // a.txt's one, b.zig's three lines + try std.testing.expectEqual(@as(usize, 3), q.total); + const body = p.panes[qid].?.file.?.content; + try std.testing.expect(std.mem.indexOf(u8, body, "\nb.zig\n") != null); + // the open file's hits are its places + try std.testing.expect(a.places.started and a.places.hits.items.len == 1); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!a.places.started); + + // All: a second pane, both searched, grouped by serial + p.newScratchBelow(0); + const s = p.active; + const sf = &p.panes[s].?.file.?; + File.setContent(p, sf, try p.gpa.dupe(u8, "needle needle twice\n")); + p.active = 0; + leader(p, "/"); + const aid = queryPane(p).?; + const aq = p.panes[aid].?.query.?; + try std.testing.expectEqual(Source.all, aq.source); + typeKeys(p, "needle"); + settle(p); + try std.testing.expectEqual(@as(usize, 3), aq.total); + const all = p.panes[aid].?.file.?.content; + var hb: [32]u8 = undefined; + const first = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{a.serial})).?; + const second = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{p.panes[s].?.serial})).?; + try std.testing.expect(a.serial < p.panes[s].?.serial and first < second); + try std.testing.expect(second < std.mem.indexOf(u8, all, "twice").?); + // two places on one line are one row + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all, "twice")); +} + +test "zz query timings on the 1.2 MB stress file (QUERY_TIMES=)" { + const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(8 << 20)); + defer std.testing.allocator.free(bytes); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + pane.body.cur_row = 15000; + pane.ensureCursorVisible(); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const Clock = struct { + fn step(pp: *Pardes, fr: *std.heap.ArenaAllocator, ev: pardes.Event) !u64 { + const t0 = Places.nowNs(); + pp.update(ev); + _ = fr.reset(.retain_capacity); + _ = try pp.render(fr.allocator()); + return Places.nowNs() - t0; + } + }; + var report: std.ArrayList(u8) = .empty; + defer report.deinit(std.testing.allocator); + var base: u64 = 0; + for (0..10) |_| base += try Clock.step(p, &frame, .{ .key = .{ .cp = 'j', .text = "j" } }); + try report.print(std.testing.allocator, "a cursor move and its frame, no search: {d} us\n", .{base / 10 / 1000}); + const t_open = try Clock.step(p, &frame, .{ .key = .{ .cp = '/', .text = "/" } }); + try report.print(std.testing.allocator, "open / {d} us\n", .{t_open / 1000}); + for ("pane.v") |c| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + var ticks: usize = 0; + var worst: u64 = 0; + while (busy(p) or pane.places.busy(pane)) : (ticks += 1) { + if (ticks > 500) break; + worst = @max(worst, try Clock.step(p, &frame, .tick)); + } + const qid = queryPane(p).?; + try report.print(std.testing.allocator, "key '{c}': {d} us, then {d} ticks (worst {d} us), {d} places\n", .{ c, t / 1000, ticks, worst / 1000, p.panes[qid].?.query.?.total }); + } + // Enter: frozen; then edits in the owner with the pane open. + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = Key.enter } }); + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = 'i', .text = "i" } }); + var worst_edit: u64 = 0; + var sum: u64 = 0; + for (0..20) |_| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + worst_edit = @max(worst_edit, t); + sum += t; + const t2 = try Clock.step(p, &frame, .tick); + worst_edit = @max(worst_edit, t2); + } + try report.print(std.testing.allocator, "edit in the owner (insert x, then a tick): mean {d} us, worst {d} us\n", .{ sum / 20 / 1000, worst_edit / 1000 }); + // The same edits with no query pane at all, for the editor's own cost. + p.update(.{ .key = .{ .cp = Key.escape } }); + exec.runBuiltin(p, .Del, queryPane(p).?, "", null); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + sum = 0; + for (0..20) |_| sum += try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + try report.print(std.testing.allocator, "the same edit, no search: mean {d} us\n", .{sum / 20 / 1000}); + std.debug.print("{s}", .{report.items}); +} + +test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration; SearchPane new leaves the last where it is" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text + typeKeys(p, "e*"); + const qid = queryPane(p).?; + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/")); + try std.testing.expect(pane.places.started); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + // SPC b b: the open panes by name; Enter goes to the marked one + p.newScratchBelow(0); + const other = p.active; + p.active = 0; + leader(p, "bb"); + const bid = queryPane(p).?; + try std.testing.expectEqual(bid, qid); + try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source); + try std.testing.expect(p.panes[bid].?.query.?.total >= 1); + // SPC s s: the declarations, fuzzy; Enter lands on the line + p.update(.{ .key = .{ .cp = Key.escape } }); + p.active = 0; + leader(p, "ss"); + const sid = queryPane(p).?; + try std.testing.expectEqual(Source.symbols, p.panes[sid].?.query.?.source); + // (context declarations span lines: a one-line fn is none of them) + typeKeys(p, "bet"); + try std.testing.expectEqual(@as(usize, 1), p.panes[sid].?.query.?.total); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + _ = other; + // SearchPane new: the frozen one stays, unattached; a new one under the owner + p.settings.search_pane = .new; + typeKeys(p, "/"); + const nid = queryPane2(p, sid).?; + try std.testing.expect(nid != sid); + try std.testing.expect(p.panes[sid].?.attached_to == null); + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, nid)); +} + +fn queryPane2(p: *Pardes, not: usize) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i; + return null; +} diff --git a/src/Text.zig b/src/Text.zig index cef76b3b..88630f83 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -182,7 +182,10 @@ pub fn primaryRange(t: *Text, text: []const u8, row0: i32) modal.Selection { const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; } - if (t.vsel.active) return cellRange(text, t.vsel.row - row0, t.vsel.col, t.cur_row - row0, 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) }; } diff --git a/src/body_layer.zig b/src/body_layer.zig index d44045a6..e50b7e3e 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -275,6 +275,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); pane.places.paint(p, s, pane, r, body_h); + panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal() and p.settings.colors) { panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); diff --git a/src/builtins.zig b/src/builtins.zig index 1ec33d88..7cdee9de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -210,7 +210,7 @@ pub const registry = struct { .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, // bare, it says the current value (exec.applySettingBuiltin) - .tab, .callstack_depth => false, + .tab, .callstack_depth, .search_rows => false, }; return declOr(b, "requires_arg", false, false); } @@ -1721,7 +1721,8 @@ pub const Find = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.find_marker }); + // Bare (SPC f f): the query pane, line 1 `Find `, typed into. + panes.Query.open(c.p, c.id, .find, "", true); } }; @@ -1738,7 +1739,29 @@ pub const Grep = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.grep_marker }); + // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. + panes.Query.open(c.p, c.id, .grep, "", true); + } +}; + +/// Search in a query pane under this pane, line 1 the argument (`Panes`, +/// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. +pub const Search = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?; + panes.Query.open(c.p, c.id, asked.source, asked.pat, true); + } +}; + +/// Pick an open pane by its name in a query pane under this one (SPC b b). +pub const Panes = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; @@ -1866,9 +1889,13 @@ pub const Last = struct { /// List the files opened lately, closed ones too, each a place to open again. pub const Recent = struct { pub const scope: Scope = .session; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // From a pane: the query pane under it, line 1 `Recent `, typed + // into; from a header, which no pane owns, the +Recent list. + if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 06eec2d9..2fa4a55d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -26,6 +26,26 @@ pub const leader_help: u8 = '?'; const undecided: []const u8 = ""; +/// Leader paths that run a builtin WITH an argument (the pick prototype's): +/// the query pane's sources that have no word of their own, `Search` and +/// line 1. `SPC s` is the session group (Dump, Restore, Attach), so the +/// declarations are `SPC s s`, a key from helix's. +pub const leader_args = [_]struct { path: []const u8, cmd: Builtin, arg: []const u8 }{ + .{ .path = "bb", .cmd = .Search, .arg = "Panes" }, + .{ .path = "ss", .cmd = .Search, .arg = "Symbols" }, + .{ .path = "/", .cmd = .Search, .arg = "All" }, +}; + +comptime { + @setEvalBranchQuota(20_000); + // A path here is a leaf: no builtin's path is it or runs past it, and + // none of it is a builtin's whole path. + for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) + @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); + }; +} + // null means word/chord-only. Every enabled builtin must explicitly choose a path. pub const leader_path = paths: { @setEvalBranchQuota(10_000); // a check per builtin, and they grow @@ -94,6 +114,11 @@ pub const leader_path = paths: { .Delcol = "cd", .Joincol = "cj", .Placement = "cp", + .SearchPlace = null, + .SearchPane = null, + .SearchRows = null, + .Search = null, + .Panes = null, .BootShell = null, .LookWord = null, .DirLook = null, @@ -517,6 +542,7 @@ pub const dump_config_buffer = "+DumpConfig"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; pub const recent_buffer = "+Recent"; +pub const preview_buffer = "+Preview"; pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; @@ -846,6 +872,15 @@ pub const Runtime = struct { callstack_layout: CallstackLayout = .stacked, callstack_corners: CallstackCorners = .rounded, callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, + /// Where a query pane goes (Query.zig): `attached`, under the pane that + /// asked, out of its rows alone; `column`, in the finder column. + search_place: SearchPlace = .attached, + /// A search from a pane that has a query pane: `reuse` it (its frozen + /// rows back on Esc), or open a `new` one, the last left where it is. + search_pane: SearchPane = .reuse, + /// The body rows a query pane is born with under its line 1 (and its + /// +Preview with): it never resizes itself after. + search_rows: u16 = 8, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; @@ -858,8 +893,10 @@ pub const Runtime = struct { pub const JumpScope = enum { file, all }; pub const CallstackLayout = enum { @"inline", stacked }; pub const CallstackCorners = @import("lsp/lsp.zig").CallstackCorners; + pub const SearchPlace = enum { attached, column }; + pub const SearchPane = enum { reuse, new }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners, search_place, search_pane }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1048,6 +1085,7 @@ pub const Runtime = struct { grip_width, tab, callstack_depth, + search_rows, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1137,6 +1175,9 @@ pub const Runtime = struct { .{ .word = "CallstackCorners", .action = .{ .choice = .callstack_corners }, .doc = "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query." }, .{ .word = "CallstackDepth", .action = .callstack_depth, .doc = "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit." }, .{ .word = "Tab", .action = .tab, .doc = "A tab's width in cells, 1 through 16, in every pane; bare, it says the width." }, + .{ .word = "SearchPlace", .action = .{ .choice = .search_place }, .doc = "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column." }, + .{ .word = "SearchPane", .action = .{ .choice = .search_pane }, .doc = "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is." }, + .{ .word = "SearchRows", .action = .search_rows, .doc = "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself." }, }; pub fn find(name: []const u8) ?Setting { @@ -1311,6 +1352,7 @@ pub const Runtime = struct { .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, + .search_rows => state.search_rows = number(u16, argument, " \t\r\n", 1, 100) orelse return false, .theme, .font => return false, } return true; @@ -1348,6 +1390,7 @@ pub const Runtime = struct { .grip_width => "50-300 (a percentage)", .tab => "1-16 (cells)", .callstack_depth => "1-64 (levels)", + .search_rows => "1-100 (rows)", .tagline_size => std.fmt.comptimePrint("{d}-{d} (a percentage)", .{ tagline_percent_min, tagline_percent_max }), .message_ms => std.fmt.comptimePrint("0-{d} (milliseconds)", .{message_ms_max}), .shell => "a path of at most 255 bytes; bare, $SHELL, else /bin/sh", @@ -1490,6 +1533,7 @@ pub const Runtime = struct { .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), + .search_rows => try out.print("{s} {d}\n", .{ setting.word, state.search_rows }), .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1773,6 +1817,8 @@ pub const Runtime = struct { .jump_scope => "all", .callstack_layout => "inline", .callstack_corners => "square", + .search_place => "column", + .search_pane => "new", }, .lift => "rim", .motion => "playful", @@ -1780,6 +1826,7 @@ pub const Runtime = struct { .grip_width => "200", .callstack_depth => "16", .tab => "8", + .search_rows => "12", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1853,6 +1900,8 @@ pub const Runtime = struct { .jump_scope => "JumpScope all\n", .callstack_layout => "CallstackLayout inline\n", .callstack_corners => "CallstackCorners square\n", + .search_place => "SearchPlace column\n", + .search_pane => "SearchPane new\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", @@ -1860,6 +1909,7 @@ pub const Runtime = struct { .grip_width => "GripWidth 200\n", .callstack_depth => "CallstackDepth 16\n", .tab => "Tab 8\n", + .search_rows => "SearchRows 12\n", .theme, .font => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, report, expected) != null); @@ -2212,6 +2262,7 @@ const doc_typ = struct { if (n == 0) return leader.len == 1 and leader[0].cp == ' '; for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.eql(u8, p, path[0..n])) return true; + for (leader_args) |la| if (std.mem.eql(u8, la.path, path[0..n])) return true; return false; } toks.reset(); @@ -2308,6 +2359,7 @@ const doc_tutor = struct { fn path(keys: []const u8) bool { for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.startsWith(u8, p, keys)) return true; + for (leader_args) |la| if (std.mem.startsWith(u8, la.path, keys)) return true; return false; } diff --git a/src/edit.zig b/src/edit.zig index c9477c29..a06f5f2d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -568,6 +568,26 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp return; } const pane = t.pane() orelse return retireEditText(p, new); + // A live query pane's rows are its line 1's (Query.zig): an edit there + // is refused, as a tag's prefix refuses one, and one from line 1 into + // them is cut at its end. The rows' metadata stays theirs across an + // edit of the line, which moves no row. + if (pane.file) |*f| if (pane.query) |q| if (!q.frozen) { + const kept = panes.Query.clampEdit(p, t, f.content, new) orelse return retireEditText(p, new); + if (kept.ptr != new.ptr) retireEditText(p, new); + const end = modal.positionAt(kept, kept.len - panes.File.spanOf(f.content, kept).tail); + t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; + const rows = f.location_rows; + const spans = f.pager_spans; + f.location_rows = &.{}; + f.pager_spans = &.{}; + panes.File.setContentSpan(p, f, kept, null); + if (f.location_rows.len > 0) @import("locations.zig").freeRows(p.gpa, f.location_rows); + p.gpa.free(f.pager_spans); + f.location_rows = rows; + f.pager_spans = spans; + return; + }; // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; // ponytail: O(file), for the edits that do not say what they changed diff --git a/src/exec.zig b/src/exec.zig index a9c11049..2bc1a3e5 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -194,6 +194,20 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l // the look is of the address it names (look.diffAddress), a regular // look from there. A hunk line's code is words, looked at as ever: // the code's, the prefix never one of them. + // A query pane's row pointed at on its gutter (its line number): the + // look is of the row's address (Query.rowAddress), as a +Diff line's + // prefix is its place; the row's code is words, looked at as ever. + if (for_look and pane.query != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and col >= 0) gutter: { + var address_buf: [4096 + 32]u8 = undefined; + const address = panes.Query.rowAddress(pane, @intCast(row), @intCast(col), &address_buf) orelse break :gutter; + const meta = pane.file.?.location_rows[@intCast(row)]; + result.text = p.scratch.allocator().dupe(u8, address) catch break :gutter; + result.file_word = .{ .row = row, .lo = 0, .hi = @intCast(meta.location_end) }; + const expanded = fileWordCells(pane, clicked, row, 0, @intCast(meta.location_end)) orelse return result; + result.preview = expanded; + result.expanded = expanded; + return result; + } var word_from: usize = 0; if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0) diff: { var address_buf: [4096 + 32]u8 = undefined; @@ -1118,6 +1132,12 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } else if (!p.settings.apply(setting, arg)) { p.reportFailure(p.active, "CallstackDepth: takes " ++ comptime config.Runtime.takes(.callstack_depth).?); }, + .search_rows => if (arg == null) { + var said: [40]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "SearchRows {d}", .{p.settings.search_rows}) catch "SearchRows"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "SearchRows: takes " ++ comptime config.Runtime.takes(.search_rows).?); + }, // Bare, it says the width, as acme's Tab does. .tab => if (arg == null) { var said: [32]u8 = undefined; diff --git a/src/fs.zig b/src/fs.zig index e809eda5..cb813262 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1119,7 +1119,7 @@ const find_max_steps = 100_000; /// One root's Find or Grep rows at most: its hits, each a path and a line. pub const search_root_output_bytes = find_max_hits * (4096 + 320); -const find_skip = [_][]const u8{ +pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; diff --git a/src/layout.zig b/src/layout.zig index f0689b10..dac0aa7e 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1016,21 +1016,31 @@ pub fn keepGroups(p: *Pardes) void { /// False, `id` in no column, when the owner has not the rows for its tag /// and the attachment's minimum. pub fn attach(p: *Pardes, owner: usize, id: usize, rows: u16) bool { + return attachFrom(p, owner, id, rows, owner); +} + +/// attach, the rows given by `giver`: the owner itself or a pane of its +/// group (a +Preview added under a query pane later takes the text's rows, +/// so the query pane, typed into, keeps its own). +pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool { const o = p.panes[owner] orelse return false; + const g = p.panes[giver] orelse return false; const nw = p.panes[id] orelse return false; if (o.collapsed) toggleCollapse(p, owner); + if (g.collapsed) toggleCollapse(p, giver); compute(p); const f = findPane(p, owner) orelse return false; + if (giver != owner and groupRoot(p, owner) != groupRoot(p, giver)) return false; // Its tag wraps at the column's width: measured there. p.rects[id].w = p.col_w[f.col]; - const oh = p.rects[owner].h; + const oh = p.rects[giver].h; const least = minRows(p, id); if (oh < least + BOX_H) return false; - const owner_keeps = if (oh >= least + minRows(p, owner)) minRows(p, owner) else BOX_H; - const give = std.math.clamp(rows, least, oh - owner_keeps); + const giver_keeps = if (oh >= least + minRows(p, giver)) minRows(p, giver) else BOX_H; + const give = std.math.clamp(rows, least, oh - giver_keeps); snapColWeights(p, f.col); insert(p, f.col, groupEnd(p, f.col, f.idx), id); - o.vweight = @floatFromInt(oh - give); + g.vweight = @floatFromInt(oh - give); nw.vweight = @floatFromInt(give); nw.attached_to = o.serial; compute(p); diff --git a/src/look.zig b/src/look.zig index 2d97cb9f..eed3dbd9 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1719,6 +1719,8 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void { /// Whether `pane` is the +Recent or the Jumplist list, whose rows are /// remembered places: a look at one clamps to the file as it is now. fn isRecentList(pane: *const Pane) bool { + // A query pane over the recent files: its rows are remembered places. + if (pane.query) |q| if (q.source == .recent) return true; const f = pane.file orelse return false; const o = f.output orelse return false; return std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Recent }) or std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Jumplist }); diff --git a/src/mouse.zig b/src/mouse.zig index ec5560d0..3400afbe 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1083,6 +1083,15 @@ pub fn dispatchPointerBuiltin( // nothing, as acme's look3 and execute return on an empty expansion. const operand = text orelse return; if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg)) return; + // B2 anywhere on a query pane's line 1 is the line: run again, whatever + // word of it was clicked (Query.zig). + if (gesture) |g| if (!g.on_tag and g.operand.row == 0 and cmd == config.exec_cmd) if (p.panes[id]) |pane| if (pane.query) |q| { + p.gpa.free(q.asked); + q.asked = &.{}; + q.frozen = false; + panes.Query.produceAll(p, false); + return; + }; // A middle click on a body is the exec a bound REPL may take. exec.runBuiltinFrom(p, cmd, id, "", exec.withArg(p, operand, arg), gesture != null and !gesture.?.on_tag); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f9bec775..45336a1e 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -89,6 +89,8 @@ pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) vo const after = Serials.snapshot(p); var created = false; for (after.list[0..after.len]) |serial| if (std.mem.indexOfScalar(u32, before.list[0..before.len], serial) == null) { + // A query pane's +Preview is its query pane's: that answers. + if (p.paneBySerial(serial)) |made| if (p.panes[made].?.file) |f| if (f.output) |o| if (o.from == .preview) continue; // A look that made a +Search pane (LookWord list, a terminal) // answers it: that is where the places it found are. noteResult(p, serial); @@ -555,6 +557,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? // Bare, it says the width, as from a pane's exec. .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, + .search_rows => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 100, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -664,6 +667,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .inactive_dim => try w.print("{s} {d}\n", .{ word, s.inactive_dim }), .grip_width => try w.print("{s} {d}\n", .{ word, s.grip_width }), .callstack_depth => try w.print("{s} {d}\n", .{ word, s.callstack_depth }), + .search_rows => try w.print("{s} {d}\n", .{ word, s.search_rows }), .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } @@ -3890,8 +3894,10 @@ test "Recent's row for a file still open is where its dot is now, not where it l pane.body.cur_col = 2; try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}/a.txt:2:3 open\n", .{dir})) != null); + // A query pane under the file (line 1 `Recent `), its rows said from + // its directory. + try testing.expect(std.mem.startsWith(u8, rows.file.?.content, "Recent \n")); + try testing.expect(std.mem.indexOf(u8, rows.file.?.content, "\na.txt:2:3 open\n") != null); } test "a closed file is found again: Recent and /recent list it closed, a look at its row reopens it at its dot, and a jump back does too" { @@ -3924,7 +3930,8 @@ test "a closed file is found again: Recent and /recent list it closed, a look at // Recent lists it, closed, at its dot; a look at the row opens it there. try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - const at = std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}:3:", .{a})).?; + // Its query pane's rows are said from its directory, a.txt's. + const at = std.mem.indexOf(u8, rows.file.?.content, "\na.txt:3:").? + 1; const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; try testing.expect(std.mem.endsWith(u8, row, " (closed)")); try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), try std.fmt.bufPrint(&line, "{s}\n", .{row[0 .. row.len - " (closed)".len]})).reply.status); @@ -3939,6 +3946,9 @@ test "a closed file is found again: Recent and /recent list it closed, a look at var closed_entry = false; for (p.jumps[0..p.njumps]) |j| closed_entry = closed_entry or j.serial == 0; try testing.expect(closed_entry); + // Every entry in order (JumpScope all): which file has the focus after + // a Del is the layout's to choose, and Back keeps to it first. + p.settings.jump_scope = .all; var tries: usize = 0; while (tries < p.njumps) : (tries += 1) { p.jumpBy(-1); diff --git a/src/normal.zig b/src/normal.zig index 808ac886..ebace536 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -930,7 +930,12 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), - .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), + // `/` in a text is its query pane's line 1 (Query.zig); a + // terminal's still asks on the notice band. + .search => if (pane.file != null and t.what == .body) + panes.Query.open(p, p.active, .text, "", true) + else + return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for // the register (Places.answersN); else helix's search of the register. .search_step => |step| if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) @@ -939,12 +944,13 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void return searchStep(p, t, text, step.direction, step.count), .search_selection => |boundary| { searchSelection(p, t, text, boundary); - // The pattern's places: the selection is already on one of them. - if (t.what == .body and pane.file != null) { + // The pattern is line 1 of this text's query pane, made or + // reused, the keyboard staying here: n and N step its places. + if (t.what == .body and pane.file != null and !pane.hasPdf() and pane.query == null) { const name = if (p.register != 0) p.register else '/'; const pat = p.registers.value(name, 0) orelse return; - const r = pane.body.primaryRange(text, 0); - pane.places.search(p, pane, .search, 0, pat, false, @min(r.anchor, r.head), false); + panes.Query.open(p, p.active, .text, pat, false); + pane.places.provenance = .search; } }, .node => |walk| return nodeSelect(p, pane, t, walk), diff --git a/src/panes.zig b/src/panes.zig index 73794b91..e0eb3fec 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -108,6 +108,9 @@ pub const Pane = struct { /// gone, or a pane no longer right under its owner's group, leaves it /// an ordinary pane (layout.keepGroups). attached_to: ?u32 = null, + /// This pane is a query pane: its line 1 the query, its rows made live + /// from a source (Query.zig, gpa-owned). + query: ?*Query = null, cols: u16, rows: u16, greet: bool = false, @@ -463,6 +466,8 @@ pub const Pane = struct { if (f.mini != null) return .source; if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; if (f.output != null) { + // A +Preview is a file's text: coloured as the file. + if (f.output.?.from == .preview) return .source; const tr = Output.fileTraits(f.output); if (tr.locations) return .locations; if (!tr.saves) return .none; @@ -655,6 +660,8 @@ pub const Output = @import("Output.zig"); pub const Places = @import("Places.zig"); +pub const Query = @import("Query.zig"); + pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c4011f7d..1b4e9920 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -486,6 +486,8 @@ test { _ = @import("animation.zig"); _ = @import("pager.zig"); _ = @import("Places.zig"); + _ = @import("Query.zig"); + _ = @import("Names.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4402,6 +4404,9 @@ pub const Pardes = struct { jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, + /// The next place tracked is an entry of its own however near the last + /// (a query answered: Ctrl-o goes back to where it was asked). + jump_force: bool = false, look_src: [MAX_PANES]u32 = undefined, n_look_src: usize = 0, look_walk_owner: ?u32 = null, @@ -5049,6 +5054,8 @@ pub const Pardes = struct { // to it reopen it there. p.noteClosed(pane); panes.Output.dropUnsaved(p, pane); + // A query pane's places, in whatever panes it fed, go with it. + if (pane.query != null) panes.Query.release(p, pane); if (pane.file) |*file| panes.File.leaveTwins(p, file); const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { @@ -5084,6 +5091,11 @@ pub const Pardes = struct { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + if (pane.query) |q| { + q.deinit(p.gpa); + p.gpa.destroy(q); + pane.query = null; + } panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); @@ -6121,6 +6133,8 @@ pub const Pardes = struct { // Each pane's places find a frame's more on a tick, and on any other // step the ones an edit or a scroll left unfound in the view. for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); + // Each live query pane's rows, made from what changed this step. + panes.Query.produceAll(p, ev == .tick); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); @@ -6450,6 +6464,9 @@ pub const Pardes = struct { return; } if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); + // A query pane's line 1 answers Enter, Esc and the stepping keys + // itself (Query.zig). + if (t == &pane.body and header == null and pane.query != null and panes.Query.key(p, p.active, key)) return; if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) { // A header's words are the workspace's and column's commands, so // Enter runs them there, as the execute key does. @@ -6564,6 +6581,12 @@ pub const Pardes = struct { p.leader_keys[p.leader_n] = c; p.leader_n += 1; const pfx = p.leader_keys[0..p.leader_n]; + // A path that runs a builtin with its argument (the query pane's + // sources with no word of their own). + for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, p.active, "", la.arg); + for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) { + p.leader_on = true; + }; // a path-less builtin is a row here too (it is the same index Help // reads), and SPC cannot reach one — so both scans skip it for (builtin_rows) |row| { @@ -7017,6 +7040,21 @@ pub const Pardes = struct { return; } + // The lists of places: into the asking text's query pane (made or + // reused), line 1 their word, the places in that text its places. + const listed: ?panes.Query.Source = switch (w.kind) { + .references => .refs, + .definition => .defs, + .implementation => .impls, + .diagnostics => .diagnostics, + else => null, + }; + if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) { + p.fs.refilled = null; + panes.Query.fillList(p, w.pane, source, rows); + p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null; + return; + }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // A Callstack page that stops short ends in its marker: said as a // row naming the word that shows the next page, and kept. @@ -7285,6 +7323,11 @@ pub const Pardes = struct { p.jcur = @min(cur, w -| 1); const pane = p.panes[p.active] orelse return; + // A query being typed moves the owner's selection to show, never a + // jump; its pane is no place to come back to either. + if (pane.query) |q| if (!q.frozen) return; + const force = p.jump_force; + p.jump_force = false; const now: Loc = .{ .pane = @intCast(p.active), .serial = pane.serial, @@ -7292,14 +7335,14 @@ pub const Pardes = struct { .col = if (pane.pdfPage() != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0, .path_hash = if (recentDot(pane)) |d| std.hash.Wyhash.hash(0, d.path) else 0, }; - if (p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { + if (!force and p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { p.jumps[p.jcur] = now; // same visit; the entry IS where you are return; } // a new jump made from the middle of the list drops everything ahead of // it, the way vim's does: the future you did not take is not history. if (p.njumps > 0) p.njumps = p.jcur + 1; - if (p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { + if (!force and p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { p.jumps[p.njumps - 2] = p.jumps[p.njumps - 1]; p.jumps[p.njumps - 1] = now; p.jcur = p.njumps - 1; @@ -7588,6 +7631,7 @@ pub const Pardes = struct { if (p.chrome_animation.isActive() or p.presentation.animating()) return next; // Places still to find resume on the next frame. for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; + if (panes.Query.busy(p)) return next; var frames: ?u64 = null; if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames orelse return next; @@ -8003,11 +8047,13 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); defer std.testing.allocator.free(tag_before); - p.update(.{ .key = .{ .cp = '/' } }); + // `s` keeps a prompt on the band (a text's `/` is its query pane's + // line 1 now, Query.zig). + p.update(.{ .key = .{ .cp = 's' } }); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); try std.testing.expect(pane.prompt == .search and pane.focus == .body); - try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); + try std.testing.expectEqualStrings(config.select_marker ++ "tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); // The tagline is exactly what it was: nothing of the prompt is in it. diff --git a/src/tagline.zig b/src/tagline.zig index e668419d..89152a3a 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -35,6 +35,10 @@ pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str 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; Unattach leaves it where it stands. +pub const query_live_tail = " Del"; +pub const query_frozen_tail = " Save Unattach Del"; /// A file with changes it has not saved. pub fn dirty(pane: *const panes.Pane) bool { const f = pane.file orelse return false; @@ -135,6 +139,9 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co 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. if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; @@ -174,6 +181,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; + if (pane.query) |q| return if (q.frozen) query_frozen_tail else 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; diff --git a/test/output.zig b/test/output.zig index 523e8129..8ba2f357 100644 --- a/test/output.zig +++ b/test/output.zig @@ -185,7 +185,7 @@ test "ranked choices and prose retain their supplied order" { } } -test "reference Look selects the next sorted row from the captured request and keeps navigation there" { +test "references fill the asking text's query pane: sorted under their files, the next after where it was asked current, the owner's places the refs in it" { if (!pardes.lsp.supports.contains(.references)) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -194,53 +194,38 @@ test "reference Look selects the next sorted row from the captured request and k try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "z.zig", .data = "z\n" }); var path_buf: [256]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/m.zig", .{tmp.sub_path}); - const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 24 }); + const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 40 }); defer p.deinit(); - p.locations_config.layout = .@"inline"; const source = p.panes[0].?; const response = "m.zig:5:5-8 later\nz.zig:1:1 last-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\na.zig:1:1 first-file\nm.zig:4:5-8 next\n"; - const sorted = "a.zig:1:1 first-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\nm.zig:4:5-8 next\nm.zig:5:5-8 later\nz.zig:1:1 last-file\n"; source.body.cur_row = 2; source.body.cur_col = 4; p.lspRequest(0, .references, ""); const request = p.lsp_wait.?.id; + // the cursor moves before the answer: it is placed by where it was asked source.body.cur_row = 4; p.lspResponse(request, response); - const rid = source.search_pane orelse return error.MissingResults; - const results = p.panes[rid].?; - try expectResultRows(sorted, &results.file.?); - try std.testing.expectEqual(@as(usize, 0), p.active); + const qid = panes.Query.ofOwner(p, source.serial) orelse return error.MissingResults; + const results = p.panes[qid].?; + const content = results.file.?.content; + try std.testing.expect(std.mem.startsWith(u8, content, "Refs \n")); + // under their files, in order + const a_at = std.mem.indexOf(u8, content, "\na.zig\n").?; + const m_at = std.mem.indexOf(u8, content, "\nm.zig\n").?; + const z_at = std.mem.indexOf(u8, content, "\nz.zig\n").?; + try std.testing.expect(a_at < m_at and m_at < z_at); + // the owner's places are its four refs; the current the one after line 3 + try std.testing.expectEqual(@as(usize, 4), source.places.hits.items.len); + try std.testing.expectEqual(@as(?usize, 2), source.places.current); try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); - try std.testing.expect(source.body.vsel.active); - try std.testing.expectEqual(@as(i32, 4), @min(source.body.cur_col, source.body.vsel.col)); - try std.testing.expectEqual(@as(i32, 7), @max(source.body.cur_col, source.body.vsel.col)); - try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); - try std.testing.expectEqual(@as(usize, 3), source.search_row.?); - try std.testing.expectEqual(results.serial, p.look_walk_owner.?); - try std.testing.expectEqual(@as(i32, 3), results.look_at.?.row); - const available = p.freeSlot(); - lookKey(p, 'n'); - try std.testing.expectEqual(rid, p.active); - try std.testing.expectEqual(@as(i32, 4), results.body.cur_row); - try std.testing.expectEqual(available, p.freeSlot()); - lookKey(p, 'N'); - try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); - + try std.testing.expectEqual(@as(usize, 6), results.query.?.total); + // n in the owner steps them, round the end without a word p.active = 0; - source.body.cur_row = 4; - source.body.cur_col = 4; - p.lspRequest(0, .references, ""); - p.lspResponse(p.lsp_wait.?.id, response); - try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/z.zig")); - try std.testing.expectEqual(@as(i32, 5), results.body.cur_row); - try std.testing.expectEqual(@as(usize, 5), source.search_row.?); - const last = p.active; - p.lspRequest(last, .references, ""); - p.lspResponse(p.lsp_wait.?.id, response); - try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/a.zig")); - const wrapped = p.panes[p.panes[last].?.search_pane.?].?; - try std.testing.expectEqual(@as(i32, 0), wrapped.body.cur_row); - try std.testing.expectEqual(wrapped.serial, p.look_walk_owner.?); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(?usize, 3), source.places.current); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(?usize, 0), source.places.current); + try std.testing.expectEqual(@as(usize, 0), p.active); } test "location sorting leaves mixed prose alone and preserves newline shape" { -- cgit v1.3 From ce6ba3d8a9e1f5c1e31892639049317f6a27b1bc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:59:21 -0300 Subject: Tables 1/3: a markdown file's pipe tables laid out in their rows, cells padded with virtual width before a byte (a tab's extra cells, not a parallel map): File.rowPads under displayOffset/displayEndOffset/byteAtRowDisplay, fillBody, recolorSyntax, the pointer sweep, j/k; tree-sitter-markdown as the detector's oracle --- src/File.zig | 55 ++++- src/Tables.zig | 641 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/Text.zig | 26 ++- src/body_layer.zig | 22 +- src/edit.zig | 11 +- src/syntax.zig | 69 ++++++ 6 files changed, 813 insertions(+), 11 deletions(-) create mode 100644 src/Tables.zig (limited to 'src/Text.zig') diff --git a/src/File.zig b/src/File.zig index 24dc9318..ddf91af3 100644 --- a/src/File.zig +++ b/src/File.zig @@ -17,6 +17,7 @@ const dump = @import("dump.zig"); const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Colors = @import("colors.zig"); +const Tables = @import("Tables.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; @@ -201,6 +202,9 @@ pub const State = struct { /// helix's object_selections: what Alt-o grew from, for Alt-i to go back /// to; gpa-owned ranges and the primary's index. node_history: std.ArrayList(NodeStep) = .empty, + /// A markdown text's pipe tables, laid out in their rows (Tables.zig): + /// found again on the first body drawn after an edit. + tables: Tables = .{}, history: *History, /// Zerox's group: the panes on one buffer share `content`, `history` /// and (while it is the one index) `line_starts`, each with its own @@ -577,20 +581,41 @@ test "indexed source rows match uncached scans across content changes" { } } +/// The pads `row` is laid out with in this pane: a row of a markdown +/// table (Tables.zig) of its text as it is now, when the table fits the +/// width a wrapping body has (a wider one is shown as its source, wrapped); +/// else none. Every mapping between a file row's bytes and its cells goes +/// through here, so the drawn row, the caret and a click cannot disagree. +pub fn rowPads(pane: *const Pane, row: i32, out: *[Tables.max_pads]Tables.Pad) []const Tables.Pad { + const f = if (pane.file) |*file| file else return &.{}; + if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return &.{}; + const table = f.tables.find(@intCast(row)) orelse return &.{}; + const width = wrapWidth(pane, pane.body_wrapped); + if (width > 0 and table.width > width) return &.{}; + return f.tables.padsOf(table, sourceLine(pane, row), out); +} + pub fn displayOffset(pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 { const line_text = sourceLine(pane, row); const from: usize = @intCast(@max(0, from_raw)); const to: usize = @intCast(@max(0, to_raw)); - return lineDisplayOffset(line_text, from, to); + var buf: [Tables.max_pads]Tables.Pad = undefined; + return lineDisplayOffset(line_text, from, to) + Tables.between(rowPads(pane, row, &buf), from, to); } pub fn displayEndOffset(pane: *const Pane, row: i32, from_raw: i32, at_raw: i32) i32 { const line_text = sourceLine(pane, row); - return lineDisplayEndOffset(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, at_raw))); + const from: usize = @intCast(@max(0, from_raw)); + const at: usize = @intCast(@max(0, at_raw)); + var buf: [Tables.max_pads]Tables.Pad = undefined; + return lineDisplayEndOffset(line_text, from, at) + Tables.between(rowPads(pane, row, &buf), from, at); } pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: i32) i32 { const line_text = sourceLine(pane, row); + var buf: [Tables.max_pads]Tables.Pad = undefined; + const pads = rowPads(pane, row, &buf); + if (pads.len > 0) return @intCast(Tables.byteAt(line_text, pads, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); return @intCast(byteAtDisplayFrom(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); } @@ -1130,6 +1155,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); file.node_history.deinit(p.gpa); + file.tables.deinit(p.gpa); if (ntwins > 0) return; file.history.destroy(p.gpa); } @@ -1768,6 +1794,7 @@ pub fn visualRow(line: []const u8, col: usize, width: usize) VisualRow { pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State, wrap: bool) ![]const u8 { const width = wrapWidth(pane, wrap); pane.body_wrapped = width > 0; + f.tables.ensure(pane.gpa, f); prepareContextRows(pane, f); pane.wrap_n = 0; @@ -1834,7 +1861,20 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) written += prefix.len; if (dst) |out| @memcpy(out[written..][0..guide.len], guide); written += guide.len; - const shown = text[cut..end]; + // A table row's pads are blanks before their bytes: the row + // drawn as the column functions above measure it. + var pad_buf: [Tables.max_pads]Tables.Pad = undefined; + var from = cut; + for (rowPads(pane, @intCast(row), &pad_buf)) |table_pad| { + if (table_pad.at <= cut) continue; + if (table_pad.at > end) break; + if (dst) |out| @memcpy(out[written..][0 .. table_pad.at - from], text[from..table_pad.at]); + written += table_pad.at - from; + if (dst) |out| @memset(out[written..][0..table_pad.cells], ' '); + written += table_pad.cells; + from = table_pad.at; + } + const shown = text[from..end]; if (dst) |out| @memcpy(out[written..][0..shown.len], shown); written += shown.len; } @@ -2029,7 +2069,16 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. s.at(tx + @as(u16, @intCast(prefix_width + col)), body_y + vr).style.fg = .{ .rgb = p.bodyChrome().diagnostic_info }; } var screen_c: usize = pad; + var table_buf: [Tables.max_pads]Tables.Pad = undefined; + const table_pads = rowPads(pane, @intCast(row_index), &table_buf); + var table_at: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { + while (table_at < table_pads.len and table_pads[table_at].at < hs + c) table_at += 1; + if (table_at < table_pads.len and table_pads[table_at].at == hs + c and hs + c > hs) { + screen_c += table_pads[table_at].cells; + table_at += 1; + if (prefix_width + screen_c >= tw) break; + } const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c)); const cells = graphemeDisplayWidth(line[hs + c .. grapheme_end]); const idx = base + hs + c; diff --git a/src/Tables.zig b/src/Tables.zig new file mode 100644 index 00000000..ca4a4b57 --- /dev/null +++ b/src/Tables.zig @@ -0,0 +1,641 @@ +//! A markdown file's pipe tables (GFM), laid out in their own rows. Every +//! byte of a table stays in its row as the text it is: B1, B2, B3 and the +//! chords work on it as on any text, and nothing is drawn over it. What +//! changes is the width some bytes take. A cell narrower than its column +//! is given the cells it lacks as virtual width, a *pad*, before one of its +//! bytes (the `|` that ends it, or for a right-aligned column the first +//! byte after the `|` that starts it), so every row's `|` of a column falls +//! on the same screen column whatever the source spacing. A pad is to the +//! byte it stands before what a tab's extra cells are to the tab: drawn as +//! blanks, every one of them maps back to that byte (a click there puts +//! the caret before it), and the caret before that byte is drawn after the +//! pad, against its glyph. +//! +//! The pads are the only mapping. File.zig's pane-aware column functions +//! (`displayOffset`, `displayEndOffset`, `byteAtRowDisplay`) and the row +//! walks that draw a body (`fillBody`, `recolorSyntax`) add them, so the +//! caret, every selection, a click and a Look map between a cell's x and +//! its byte as they map a tab's. The look itself (`paint`: the `|` as rules, +//! the delimiter row as one, the header bold) restyles cells that are +//! there; it moves nothing. +//! +//! Which lines are tables is found by lines, as tree-sitter-markdown's +//! scanner finds a `pipe_table` (its PIPE_TABLE_START: a header row's cells +//! counted by its pipes, a delimiter row of `:?-+:?` cells, the same count), +//! once per revision of the text, over the whole text: the highlighter +//! parses only the lines around the view, which start mid-table as soon as +//! a long one is scrolled, and fenced code is known only from the top. The +//! grammar is the oracle in a test ("tables are the pipe_tables tree-sitter +//! finds"). +const std = @import("std"); +const panes = @import("panes.zig"); +const pardes = @import("pardes.zig"); +const colors = @import("colors.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; + +const Tables = @This(); + +pub const Align = enum(u2) { left, right, center }; + +pub const Table = struct { + /// The header row's line; the delimiter row is the next. + first: u32, + /// One past the last row's line. + end: u32, + /// Where its columns' widths and alignments start in `widths`/`aligns`. + col0: u32, + /// Columns: the most cells any row ends with a `|`. + cols: u16, + /// The widest indentation before a leading `|`, in cells. + lead: u16, + /// The widest row laid out, in cells: a table wider than a wrapping + /// pane is shown as its source (`File.rowPads`). + width: u32, +}; + +/// `cells` of virtual width before the byte at `at` of its line. +pub const Pad = struct { at: u32, cells: u16 }; + +/// Columns past this many are not aligned (their pipes take no pad). +pub const max_cols = 64; +/// A centred column pads both sides of a cell, and a leading `|` its indent. +pub const max_pads = 2 * max_cols + 1; + +/// The text these tables are of: its revision, where it is and how long. +revision: ?u32 = null, +content: usize = 0, +len: usize = 0, +list: std.ArrayList(Table) = .empty, +widths: std.ArrayList(u16) = .empty, +aligns: std.ArrayList(Align) = .empty, + +pub fn deinit(t: *Tables, gpa: std.mem.Allocator) void { + t.list.deinit(gpa); + t.widths.deinit(gpa); + t.aligns.deinit(gpa); + t.* = .{}; +} + +/// Whether these tables are of `f`'s text as it is now. +pub fn current(t: *const Tables, f: *const File.State) bool { + return t.revision == f.revision and t.content == @intFromPtr(f.content.ptr) and t.len == f.content.len; +} + +/// The table `line` is a row of, if any. +pub fn find(t: *const Tables, line: usize) ?*const Table { + const items = t.list.items; + var lo: usize = 0; + var hi: usize = items.len; + while (lo < hi) { + const mid = (lo + hi) / 2; + if (items[mid].end <= line) lo = mid + 1 else hi = mid; + } + if (lo < items.len and items[lo].first <= line) return &items[lo]; + return null; +} + +/// Find the tables of `f`'s text again unless they are of it already. Only +/// a markdown file has any; on no memory there are none (the text is shown +/// as it is). +pub fn ensure(t: *Tables, gpa: std.mem.Allocator, f: *const File.State) void { + if (t.current(f)) return; + t.revision = f.revision; + t.content = @intFromPtr(f.content.ptr); + t.len = f.content.len; + t.list.clearRetainingCapacity(); + if (f.output != null or f.mini != null or !isMarkdown(f.path)) return; + scan(t, gpa, f.content) catch { + t.list.clearRetainingCapacity(); + t.widths.clearRetainingCapacity(); + t.aligns.clearRetainingCapacity(); + }; +} + +pub fn isMarkdown(path: []const u8) bool { + return std.ascii.endsWithIgnoreCase(path, ".md") or std.ascii.endsWithIgnoreCase(path, ".markdown"); +} + +/// One line of the text: its bytes and its number. +const Line = struct { text: []const u8, start: usize, n: u32 }; + +fn lineAt(content: []const u8, start: usize, n: u32) ?Line { + if (start > content.len) return null; + const end = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len; + const text = content[start..end]; + return .{ .text = if (text.len > 0 and text[text.len - 1] == '\r') text[0 .. text.len - 1] else text, .start = start, .n = n }; +} + +fn nextLine(content: []const u8, l: Line) ?Line { + const nl = std.mem.indexOfScalarPos(u8, content, l.start, '\n') orelse return null; + return lineAt(content, nl + 1, l.n + 1); +} + +fn indentOf(text: []const u8) usize { + var i: usize = 0; + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + return i; +} + +fn blank(text: []const u8) bool { + return indentOf(text) == text.len; +} + +/// A fence's opener (```` ``` ```` or `~~~`, three or more, up to three +/// spaces in): its character and length. +const Fence = struct { ch: u8, len: usize }; + +fn fenceOf(text: []const u8) ?Fence { + const in = indentOf(text); + if (in > 3 or in >= text.len) return null; + const ch = text[in]; + if (ch != '`' and ch != '~') return null; + var n: usize = 0; + while (in + n < text.len and text[in + n] == ch) n += 1; + if (n < 3) return null; + // A backtick fence's info string has no backtick (CommonMark 4.5). + if (ch == '`' and std.mem.indexOfScalar(u8, text[in + n ..], '`') != null) return null; + return .{ .ch = ch, .len = n }; +} + +fn closes(text: []const u8, open: Fence) bool { + const f = fenceOf(text) orelse return false; + return f.ch == open.ch and f.len >= open.len and blank(text[indentOf(text) + f.len ..]); +} + +/// A line that ends a table's rows by starting a block of its own (what +/// the grammar's paragraph_interrupt_symbols are): a heading, a fence, a +/// quote, a list item, a thematic break, HTML. +fn interrupts(text: []const u8) bool { + const in = indentOf(text); + if (in > 3 or in >= text.len) return false; + const rest = text[in..]; + if (fenceOf(text) != null) return true; + switch (rest[0]) { + '#', '>', '<' => return true, + '-', '*', '+' => { + if (rest.len == 1 or rest[1] == ' ' or rest[1] == '\t') return true; + // A thematic break: three or more of one of -*_ and spaces. + var n: usize = 0; + for (rest) |b| { + if (b == rest[0]) n += 1 else if (b != ' ' and b != '\t') return false; + } + return n >= 3; + }, + '0'...'9' => { + var i: usize = 0; + while (i < rest.len and i < 9 and std.ascii.isDigit(rest[i])) i += 1; + return i < rest.len and (rest[i] == '.' or rest[i] == ')') and (i + 1 == rest.len or rest[i + 1] == ' '); + }, + else => return false, + } +} + +/// A row's unescaped pipes, in order, and whether the row starts with one +/// (after its indentation) and ends with one (before trailing blanks). +const Pipes = struct { + at: [max_cols + 2]u32 = undefined, + n: usize = 0, + /// Pipes past `at`'s room: counted, not kept. + more: usize = 0, + leading: bool = false, + trailing: bool = false, + + fn of(text: []const u8) Pipes { + var p: Pipes = .{}; + const in = indentOf(text); + p.leading = in < text.len and text[in] == '|'; + var last_ink: usize = text.len; + var i: usize = 0; + while (i < text.len) : (i += 1) { + const b = text[i]; + if (b == '\\' and i + 1 < text.len and std.ascii.isPrint(text[i + 1]) and !std.ascii.isAlphanumeric(text[i + 1]) and text[i + 1] != ' ') { + last_ink = i + 1; + i += 1; + continue; + } + if (b == '|') { + if (p.n < p.at.len) { + p.at[p.n] = @intCast(i); + p.n += 1; + } else p.more += 1; + } + if (b != ' ' and b != '\t') last_ink = i; + } + p.trailing = p.n > 0 and last_ink == p.at[p.n - 1] and p.more == 0; + return p; + } + + /// The cells the grammar counts: the pipes after a leading one, plus + /// the last cell when no pipe ends the row. + fn cells(p: *const Pipes) usize { + const pipes = p.n + p.more - @intFromBool(p.leading); + return pipes + @intFromBool(!p.trailing); + } + + /// The pipe that ends cell `k` (the pipes after a leading one). + fn end(p: *const Pipes, k: usize) ?usize { + const i = k + @intFromBool(p.leading); + return if (i < p.n) p.at[i] else null; + } + + /// Where cell `k` starts: after the pipe before it, or after the + /// indentation when it is the first and no pipe leads. + fn start(p: *const Pipes, k: usize) usize { + if (k == 0 and !p.leading) return 0; + return p.at[k - @intFromBool(!p.leading)] + 1; + } +}; + +/// A delimiter row's cells (`:?-+:?` between pipes), or null if `text` is +/// none: as the scanner reads one after a header. +fn delimiterCells(text: []const u8, out: *[max_cols]Align) ?usize { + var i = indentOf(text); + if (i > 3) return null; + var cells: usize = 0; + var pipes: usize = 0; + if (i < text.len and text[i] == '|') { + i += 1; + pipes += 1; + } + while (true) { + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + if (i >= text.len) break; + if (text[i] == '|') { + cells += 1; + pipes += 1; + i += 1; + continue; + } + var left = false; + if (text[i] == ':') { + left = true; + i += 1; + if (i >= text.len or text[i] != '-') return null; + } + var dashes: usize = 0; + while (i < text.len and text[i] == '-') : (i += 1) dashes += 1; + if (dashes == 0) return null; + var right = false; + if (i < text.len and text[i] == ':') { + right = true; + i += 1; + } + if (cells < max_cols) out[cells] = if (left and right) .center else if (right) .right else .left; + cells += 1; + while (i < text.len and (text[i] == ' ' or text[i] == '\t')) i += 1; + if (i >= text.len) break; + if (text[i] != '|') return null; + pipes += 1; + i += 1; + } + if (pipes == 0) return null; + return cells; +} + +/// The display width of a cell's bytes; ASCII is a cell a byte. +fn widthOf(text: []const u8) usize { + for (text) |b| if (b < 0x20 or b >= 0x7f) return File.displayWidth(text); + return text.len; +} + +/// Find the tables of `content`, in place of the ones there were. +pub fn scan(t: *Tables, gpa: std.mem.Allocator, content: []const u8) !void { + t.list.clearRetainingCapacity(); + t.widths.clearRetainingCapacity(); + t.aligns.clearRetainingCapacity(); + var fence: ?Fence = null; + var prev_blank = true; + var line = lineAt(content, 0, 0); + while (line) |l| { + const following = nextLine(content, l); + if (fence) |open| { + if (closes(l.text, open)) fence = null; + prev_blank = fence == null; + line = following; + continue; + } + if (fenceOf(l.text)) |open| { + fence = open; + prev_blank = false; + line = following; + continue; + } + const is_blank = blank(l.text); + var aligns: [max_cols]Align = undefined; + // A header starts a block: after a blank line, a heading or a fence + // (the grammar tries PIPE_TABLE_START where a paragraph could start). + if (!is_blank and prev_blank and indentOf(l.text) <= 3 and std.mem.indexOfScalar(u8, l.text, '|') != null) { + if (following) |delimiter| if (delimiterCells(delimiter.text, &aligns)) |count| { + const header = Pipes.of(l.text); + // A header's one pipe may not be its leading one alone, + // unless one ends it too (`| a |`, not `| a`). + const lone = header.n + header.more == @intFromBool(header.leading) and !(header.leading and header.trailing); + if (!lone and header.cells() == count) { + const last = try t.add(gpa, content, l, delimiter, aligns[0..@min(count, max_cols)]); + line = nextLine(content, last); + prev_blank = false; + continue; + } + }; + } + // A heading line ends a block too: a header may follow it. + prev_blank = is_blank or std.mem.startsWith(u8, l.text[@min(indentOf(l.text), l.text.len)..], "#"); + line = following; + } +} + +/// Take the table whose header is `header`: its rows, its columns' widths +/// and its width. Returns its last row's line. +fn add(t: *Tables, gpa: std.mem.Allocator, content: []const u8, header: Line, delimiter: Line, aligns: []const Align) !Line { + var last = delimiter; + while (nextLine(content, last)) |row| { + if (blank(row.text) or interrupts(row.text)) break; + last = row; + } + const col0: u32 = @intCast(t.widths.items.len); + var table: Table = .{ .first = header.n, .end = last.n + 1, .col0 = col0, .cols = 0, .lead = 0, .width = 0 }; + // Widths: each column's widest cell, the cell's bytes up to the pipe + // that ends it; a row's last cell with no pipe after it aligns nothing. + var row: ?Line = header; + while (row) |r| : (row = if (r.n == last.n) null else nextLine(content, r)) { + const pipes = Pipes.of(r.text); + if (pipes.leading) table.lead = @max(table.lead, @as(u16, @intCast(@min(widthOf(r.text[0..pipes.at[0]]), std.math.maxInt(u16))))); + var k: usize = 0; + while (k < max_cols) : (k += 1) { + const stop = pipes.end(k) orelse break; + const w: u16 = @intCast(@min(widthOf(r.text[pipes.start(k)..stop]), std.math.maxInt(u16))); + if (k >= table.cols) { + try t.widths.append(gpa, w); + try t.aligns.append(gpa, if (k < aligns.len) aligns[k] else .left); + table.cols += 1; + } else t.widths.items[col0 + k] = @max(t.widths.items[col0 + k], w); + } + } + // The width: each row laid out, its source width and its pads. + row = header; + var buf: [max_pads]Pad = undefined; + while (row) |r| : (row = if (r.n == last.n) null else nextLine(content, r)) { + var width = widthOf(r.text); + for (t.padsOf(&table, r.text, &buf)) |pad| width += pad.cells; + table.width = @max(table.width, @as(u32, @intCast(@min(width, std.math.maxInt(u32))))); + } + try t.list.append(gpa, table); + return last; +} + +/// The pads of one of `table`'s rows, by byte, in order. No pad is ever at +/// byte 0: a row is drawn from its first byte, so there is no cell before +/// it to give. +pub fn padsOf(t: *const Tables, table: *const Table, text: []const u8, out: *[max_pads]Pad) []Pad { + const pipes = Pipes.of(text); + var n: usize = 0; + if (pipes.leading and pipes.at[0] > 0) { + const w = widthOf(text[0..pipes.at[0]]); + if (w < table.lead) { + out[n] = .{ .at = pipes.at[0], .cells = @intCast(table.lead - w) }; + n += 1; + } + } + var k: usize = 0; + while (k < table.cols) : (k += 1) { + const stop = pipes.end(k) orelse break; + const from = pipes.start(k); + const w = widthOf(text[from..stop]); + const want = t.widths.items[table.col0 + k]; + if (w >= want) continue; + const missing: u16 = @intCast(want - w); + // The first cell with no leading pipe starts at byte 0: it pads at + // its end, whatever its alignment. + const how: Align = if (from == 0) .left else t.aligns.items[table.col0 + k]; + const before: u16 = switch (how) { + .left => 0, + .right => missing, + .center => missing / 2, + }; + // An empty cell's start is its pipe: one pad there. + if (before > 0 and from < stop) { + out[n] = .{ .at = @intCast(from), .cells = before }; + n += 1; + } + const after = if (from < stop) missing - before else missing; + if (after > 0) { + out[n] = .{ .at = @intCast(stop), .cells = after }; + n += 1; + } + } + return out[0..n]; +} + +/// The cells of virtual width between byte `from` (excluded: its pad is +/// before the row's first shown byte) and byte `to` (included: its pad is +/// before its glyph), negative when `to` is before `from`. +pub fn between(pads: []const Pad, from: usize, to: usize) i32 { + const lo = @min(from, to); + const hi = @max(from, to); + var sum: i32 = 0; + for (pads) |pad| { + if (pad.at > hi) break; + if (pad.at > lo) sum += pad.cells; + } + return if (to >= from) sum else -sum; +} + +/// The byte at display column `col` of a row shown from byte `from`, its +/// pads counted: a pad's cells are its byte's, as a tab's are the tab's. +/// Past the end, a virtual column a cell (File.rawAtDisplay). +pub fn byteAt(text: []const u8, pads: []const Pad, from_raw: usize, col: usize) usize { + if (from_raw >= text.len) return from_raw +| col; + var at = @import("modal.zig").graphemeStart(text, from_raw); + var k: usize = 0; + while (k < pads.len and pads[k].at <= at) k += 1; + var used: usize = 0; + while (at < text.len) { + if (k < pads.len and pads[k].at == at) { + used += pads[k].cells; + k += 1; + if (col < used) return at; + } + const end = @import("modal.zig").nextGrapheme(text, at); + used += File.graphemeDisplayWidth(text[at..end]); + if (col < used) return at; + at = end; + } + return text.len + (col - used); +} + +// ---- tests ---- + +const testing = std.testing; +const config = @import("config.zig"); +const Key = pardes.Key; + +const sample = + "# Fruit\n" ++ + "\n" ++ + "| name | qty | note |\n" ++ + "|:-----|----:|:----:|\n" ++ + "| apple | 3 | red |\n" ++ + "| kiwi | 12 | small and fuzzy |\n" ++ + "| fig || |\n" ++ + "\n" ++ + "after\n"; + +/// A pane on `content` as a markdown file, drawn once. +fn testPane(p: *Pardes, content: []const u8, frame: std.mem.Allocator) !*Pane { + const pane = try p.setTestFile(content); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/notes.md"); + _ = try p.render(frame); + return pane; +} + +test "tables: a pipe table's columns, alignments and pads, by line" { + var t: Tables = .{}; + defer t.deinit(testing.allocator); + try t.scan(testing.allocator, sample); + try testing.expectEqual(@as(usize, 1), t.list.items.len); + const table = t.list.items[0]; + try testing.expectEqual(@as(u32, 2), table.first); + try testing.expectEqual(@as(u32, 7), table.end); + try testing.expectEqualSlices(u16, &.{ 7, 5, 17 }, t.widths.items); + try testing.expectEqualSlices(Align, &.{ .left, .right, .center }, t.aligns.items); + // `| fig || |`: the first cell short by 2 (left: before its `|`), the + // empty second by 5 (one pad at its pipe), the third by 16 (centred). + var buf: [max_pads]Pad = undefined; + const fig = "| fig || |"; + try testing.expectEqualSlices(Pad, &.{ + .{ .at = 6, .cells = 2 }, .{ .at = 7, .cells = 5 }, .{ .at = 8, .cells = 8 }, .{ .at = 9, .cells = 8 }, + }, t.padsOf(&table, fig, &buf)); + // `| apple | 3 | red |`: right-aligned 3 pads before its first byte. + try testing.expectEqualSlices(Pad, &.{ + .{ .at = 9, .cells = 2 }, .{ .at = 13, .cells = 6 }, .{ .at = 18, .cells = 6 }, + }, t.padsOf(&table, "| apple | 3 | red |", &buf)); + // Every row laid out is one width: the table's. + try testing.expectEqual(@as(u32, 1 + 7 + 1 + 5 + 1 + 17 + 1), table.width); + // Not tables: a fence's rows, counts that differ, a delimiter alone. + for ([_][]const u8{ + "```\n| a | b |\n|---|---|\n```\n", + "| a | b |\n|---|\n", + "|---|---|\n", + "| a\n|---\n", + }) |text| { + try t.scan(testing.allocator, text); + try testing.expectEqual(@as(usize, 0), t.list.items.len); + } +} + +test "tables: every byte's cell maps back to it, and every pad cell to the byte after it" { + var t: Tables = .{}; + defer t.deinit(testing.allocator); + try t.scan(testing.allocator, sample); + const table = &t.list.items[0]; + var lines = std.mem.splitScalar(u8, sample, '\n'); + var n: usize = 0; + while (lines.next()) |text| : (n += 1) { + if (n < table.first or n >= table.end) continue; + var buf: [max_pads]Pad = undefined; + const pads = t.padsOf(table, text, &buf); + var col: usize = 0; + for (text, 0..) |_, b| { + // The pad before b: each of its cells is b's. + const start = File.displayWidth(text[0..b]) + @as(usize, @intCast(between(pads, 0, b))); + while (col < start) : (col += 1) try testing.expectEqual(b, byteAt(text, pads, 0, col)); + try testing.expectEqual(b, byteAt(text, pads, 0, col)); + col += 1; + } + // Past the end, a virtual column a cell. + try testing.expectEqual(text.len + 2, byteAt(text, pads, 0, col + 2)); + // From a scrolled start, the pads before it are not counted. + try testing.expectEqual(@as(usize, 2), byteAt(text, pads, 2, 0)); + } +} + +test "tables: a markdown table is drawn aligned, its bytes in order, the caret and a click on each byte's cell" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const pane = try testPane(p, sample, frame.allocator()); + const r = p.rects[0]; + const text_x = r.x + config.GUTTER + File.gutterWidth(pane); + const body_y = p.bodyTop(pane, r); + // The k-th pipe of every row on one screen column. + var pipe_x: [4]?u16 = @splat(null); + for (2..7) |line| { + const text = File.sourceLine(pane, @intCast(line)); + var k: usize = 0; + for (text, 0..) |b, i| { + const x = text_x + @as(u16, @intCast(File.displayOffset(pane, @intCast(line), 0, @intCast(i)))); + const cell = p.surface.at(x, body_y + @as(u16, @intCast(line))); + if (b == '|') { + if (pipe_x[k]) |want| try testing.expectEqual(want, x) else pipe_x[k] = x; + try testing.expect(!std.mem.eql(u8, cell.grapheme(), " ")); + k += 1; + } else if (line != 3) try testing.expectEqualStrings(text[i .. i + 1], cell.grapheme()); + } + } + try testing.expectEqual(@as(u16, 1 + 7 + 1 + 5 + 1 + 17), pipe_x[3].? - text_x); + // B1 on any cell of `| fig || |`: the caret on the byte the cell is + // (a pad's cells are the byte after them), drawn where that byte is. + const fig: i32 = 6; + const text = File.sourceLine(pane, fig); + const y = body_y + 6; + var col: u16 = 0; + while (col < pipe_x[3].? - text_x + 1) : (col += 1) { + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + col, .row = y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + col, .row = y } }); + const want = File.byteAtRowDisplay(pane, fig, 0, col); + try testing.expectEqual(fig, pane.body.cur_row); + try testing.expectEqual(want, pane.body.cur_col); + try testing.expect(want < text.len); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const caret = p.surface.cursor orelse return error.NoCaret; + try testing.expectEqual(text_x + @as(u16, @intCast(File.displayOffset(pane, fig, 0, want))), caret.x); + // The caret is on the cell clicked, or on the glyph after its pad. + try testing.expect(caret.x >= text_x + col); + } + // A pad cell: the empty second cell's five, all the `|` after them. + const empty_x = pipe_x[1].? - text_x + 1; + for (0..5) |i| try testing.expectEqual(@as(i32, 7), File.byteAtRowDisplay(pane, fig, 0, @intCast(empty_x + i))); +} + +test "tables: typing in a cell re-aligns the table live, and j/k keep the column shown" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const pane = try testPane(p, sample, frame.allocator()); + // On `3` in the apple row: insert before it. + pane.body.cur_row = 4; + pane.body.cur_col = 10; + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + for ("123456789") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try testing.expectEqualStrings("| apple | 1234567893 | red |", File.sourceLine(pane, 4)); + // The qty column is now 12 wide in every row. + for (2..7) |line| { + const text = File.sourceLine(pane, @intCast(line)); + var k: usize = 0; + for (text, 0..) |b, i| { + if (b != '|') continue; + k += 1; + if (k == 3) try testing.expectEqual(@as(i32, 1 + 7 + 1 + 12), File.displayOffset(pane, @intCast(line), 0, @intCast(i))); + } + } + // k from the kiwi row's `and` keeps its screen column: the apple + // row's centred `red` under it. + p.update(.{ .key = .{ .cp = Key.escape } }); + pane.body.cur_row = 5; + pane.body.cur_col = @intCast(std.mem.indexOf(u8, File.sourceLine(pane, 5), "and").?); + pane.body.vsel.active = false; + pane.body.sticky_col = -1; + const shown = File.displayOffset(pane, 5, 0, pane.body.cur_col); + p.update(.{ .key = .{ .cp = 'k', .text = "k" } }); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + try testing.expectEqual(shown, File.displayOffset(pane, 4, 0, pane.body.cur_col)); +} diff --git a/src/Text.zig b/src/Text.zig index 88630f83..b57c953a 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -514,17 +514,33 @@ pub fn findMove(t: *Text, text: []const u8, range: modal.Selection, ch: u21, fwd setRange(t, text, 0, res, false); } +/// The file pane whose text `text` is, when `t` is its body: its rows are +/// measured through their table pads (File.rowPads), so j and k keep the +/// column a table shows, not the one its source has. +fn filePane(t: *Text, text: []const u8) ?*const Pane { + if (t.what != .body) return null; + const fp = t.pane() orelse return null; + const f = if (fp.file) |*file| file else return null; + return if (f.content.ptr == text.ptr and f.content.len == text.len) fp else null; +} + /// j/k and friends: sticky goal column, clamped onto short lines' newline pub fn verticalMove(t: *Text, text: []const u8, range: modal.Selection, down: bool, cnt: usize) void { const cur = modal.selectionCursor(text, range); const pos = File.textPosition(t, text, cur); + const shown = filePane(t, text); const goal: usize = if (t.sticky_col >= 0) @intCast(t.sticky_col) + else if (shown) |fp| + @intCast(@max(0, File.displayOffset(fp, @intCast(pos.row), 0, @intCast(pos.col)))) else File.rawDisplayCol(File.textLine(t, text, pos.row), pos.col); const last_row = File.textLineCount(t, text) - 1; const nline = if (down) @min(pos.row + @max(1, cnt), last_row) else pos.row -| @max(1, cnt); - const target_col = File.rawAtDisplay(File.textLine(t, text, nline), goal); + const target_col: usize = if (shown) |fp| + @intCast(File.byteAtRowDisplay(fp, @intCast(nline), 0, @intCast(@min(goal, std.math.maxInt(i32))))) + else + File.rawAtDisplay(File.textLine(t, text, nline), goal); const target = File.textOffset(t, text, .{ .row = nline, .col = target_col }); // extend mode never walks onto the empty trailing line (helix) if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return; @@ -546,8 +562,11 @@ pub fn visualMove( var row = pos.row; var line = modal.lineSlice(text, row); var vrow = File.visualRow(line, pos.col, width); + const shown = filePane(t, text); const goal: usize = if (t.sticky_col >= 0) @intCast(t.sticky_col) + else if (shown) |fp| + @intCast(@max(0, File.displayOffset(fp, @intCast(row), @intCast(vrow.start), @intCast(pos.col)))) else File.rawDisplayCol(line[vrow.start..vrow.end], pos.col -| vrow.start); var steps = @max(1, cnt); @@ -574,7 +593,10 @@ pub fn visualMove( } // The newline slot is a real cursor position, but the first byte of the // NEXT visual row is not: landing there would read as two rows moved. - var target_col = vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); + var target_col: usize = if (shown) |fp| + @intCast(File.byteAtRowDisplay(fp, @intCast(row), @intCast(vrow.start), @intCast(@min(goal, std.math.maxInt(i32))))) + else + vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); if (vrow.end < line.len and target_col >= vrow.end) target_col = modal.graphemeStart(line, vrow.end - 1); const target = File.textOffset(t, text, .{ .row = row, .col = target_col }); diff --git a/src/body_layer.zig b/src/body_layer.zig index e50b7e3e..90622e52 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -73,7 +73,9 @@ fn pastView(pane: *Pane, body: []const u8, line: i32, row: i32, at: i32, col: i3 const from: usize = @intCast(@max(0, at)); const to: usize = @intCast(@max(0, col)); if (from >= text.len) return to >= from +| tw; - return to >= from + panes.File.byteAtDisplay(text[from..], tw) and to < text.len; + // A file row's last shown byte counts its table pads (File.rowPads). + const shown: usize = if (pane.file != null) @intCast(panes.File.byteAtRowDisplay(pane, line, at, tw)) else from + panes.File.byteAtDisplay(text[from..], tw); + return to >= shown and to < text.len; } fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { @@ -95,8 +97,15 @@ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []c const lo = @max(start, row.lo); const hi = @min(end, row.hi); if (lo >= hi) continue; - const col = prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); - const last = @min(width, if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start)))); + // A file row through its pads (File.rowPads), as it is drawn. + const col = prefix + source.pad + if (pane.file != null) + panes.File.displayOffset(pane, source.line, @intCast(start), @intCast(lo)) + else + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); + const last = @min(width, if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + if (pane.file != null) + panes.File.displayOffset(pane, source.line, @intCast(start), @intCast(hi)) + else + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start)))); if (col < last) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible)), @intCast(last - col), bg, fg); } } @@ -361,7 +370,12 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // The byte past the row's last column, walked from its first: // bounded by the view, not the line. // A line that ends inside the view has no column past it. - const shown_to = if (row_at >= row_text.len) row_text.len else row_at + panes.File.byteAtDisplay(row_text[row_at..], tw); + const shown_to = if (row_at >= row_text.len) + row_text.len + else if (pane.file != null) + @as(usize, @intCast(panes.File.byteAtRowDisplay(pane, w.line, w.at, tw))) + else + row_at + panes.File.byteAtDisplay(row_text[row_at..], tw); const past_view = if (shown_to >= row_text.len) std.math.maxInt(usize) else shown_to; // A row that ends before the selection starts has none of it. if (w.line == bnd.lo_row and @as(usize, @intCast(@max(0, bnd.lo_col))) >= past_view) continue; diff --git a/src/edit.zig b/src/edit.zig index a06f5f2d..74dd0d1d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -250,8 +250,15 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { if (raw) next = .{ .line = source.line + 1, .at = 0 }; const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; const start: usize = @intCast(@max(0, source.at)); - const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix - source.pad)))); - const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix - source.pad)))); + // A file row through its table pads (File.rowPads), as it is drawn. + const lo: usize = @min(end, if (pane.file != null and !raw) + @as(usize, @intCast(panes.File.byteAtRowDisplay(pane, source.line, source.at, @max(0, left - prefix - source.pad)))) + else + panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix - source.pad)))); + const at: usize = @min(end, if (pane.file != null and !raw) + @as(usize, @intCast(panes.File.byteAtRowDisplay(pane, source.line, source.at, @max(0, right - prefix - source.pad)))) + else + panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix - source.pad)))); row.* = .{ .row = source.line, .lo = lo, diff --git a/src/syntax.zig b/src/syntax.zig index 81722ce5..aca2c3ff 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -2003,3 +2003,72 @@ test "syntax source analysis preserves declarations and injected colors" { try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len); try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len); } + +test "tables are the pipe_tables tree-sitter finds" { + if (!enabled or !full_grammars) return; + start(std.testing.allocator); + defer stop(); + const Tables = @import("Tables.zig"); + const source = + "# Tables\n" ++ + "\n" ++ + "| a | b |\n" ++ + "|---|:-:|\n" ++ + "| 1 | 2 |\n" ++ + "no pipe row\n" ++ + "\n" ++ + "a | b\n" ++ + "--|--\n" ++ + "c | d\n" ++ + "# heading ends it\n" ++ + "| x |\n" ++ + "|---|\n" ++ + "\n" ++ + "```\n" ++ + "| in | fence |\n" ++ + "|----|-------|\n" ++ + "```\n" ++ + "\n" ++ + "| one | two |\n" ++ + "|-----|\n" ++ + "\n" ++ + " | indented | table |\n" ++ + " | -------- | ----- |\n" ++ + " | row | here |\n" ++ + "> quote ends\n" ++ + "\n" ++ + "| esc \\| aped | two |\n" ++ + "| --- | --- |\n" ++ + "- list ends\n"; + const selected = (try forLang("markdown")).?; + const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; + defer tree.destroy(); + // Every pipe_table node's lines, wherever it is in the tree. + var found: std.ArrayList([2]u32) = .empty; + defer found.deinit(std.testing.allocator); + var stack: std.ArrayList(ts.Node) = .empty; + defer stack.deinit(std.testing.allocator); + try stack.append(std.testing.allocator, tree.rootNode()); + while (stack.pop()) |node| { + if (std.mem.eql(u8, node.kind(), "pipe_table")) { + const end = node.endPoint(); + try found.append(std.testing.allocator, .{ node.startPoint().row, end.row + @intFromBool(end.column > 0) }); + continue; + } + var i = node.childCount(); + while (i > 0) : (i -= 1) if (node.child(i - 1)) |child| try stack.append(std.testing.allocator, child); + } + // The tables, the indented one and the escaped pipe's; not the fence's + // or the one whose delimiter has a cell too few. + try std.testing.expectEqual(@as(usize, 5), found.items.len); + var t: Tables = .{}; + defer t.deinit(std.testing.allocator); + try t.scan(std.testing.allocator, source); + var mine: std.ArrayList([2]u32) = .empty; + defer mine.deinit(std.testing.allocator); + for (t.list.items) |table| try mine.append(std.testing.allocator, .{ table.first, table.end }); + std.testing.expectEqualSlices([2]u32, found.items, mine.items) catch |e| { + std.debug.print("tree-sitter {any}\nTables {any}\n", .{ found.items, mine.items }); + return e; + }; +} -- cgit v1.3