diff options
Diffstat (limited to 'core/Pick.zig')
| -rw-r--r-- | core/Pick.zig | 1078 |
1 files changed, 982 insertions, 96 deletions
diff --git a/core/Pick.zig b/core/Pick.zig index 8669314f..c05ed084 100644 --- a/core/Pick.zig +++ b/core/Pick.zig @@ -54,8 +54,9 @@ const Key = pardes.Key; /// answer, SPC e's places), titled by their word, the messages' history /// (SPC h m), the themes (SPC t t, the window wearing the one under /// the cursor), and a language server's code actions for the caret's place -/// (SPC l a, the body showing the one under the cursor as its edit). -pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, messages, themes, actions }; +/// (SPC l a, the body showing the one under the cursor as its edit), and +/// the kept pickers (Lists, UX L'3). +pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, messages, themes, actions, lists }; /// Each source's word in the tag and its key cells (`␣ f Find`); a /// source whose Backspace leaves it (`back`) goes back to the SPC level of @@ -72,9 +73,11 @@ const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 .messages = .{ .word = "Messages", .keys = "h" }, .themes = .{ .word = "Themes", .keys = "t" }, .actions = .{ .word = "Actions", .keys = "la" }, + .lists = .{ .word = "Lists", .keys = "f" }, }); -/// The pickers kept after they roll up, for their list words and Resume. +/// The pickers kept after they roll up, for their list words, Resume and +/// Lists (Lists itself never one of them: Pardes.picks has one more). pub const max_lists = 8; /// Refinements a picker stacks (C-SPC). pub const max_refine = 3; @@ -137,9 +140,12 @@ marks: std.ArrayList(u32) = .empty, refined: [max_refine]Refined = undefined, nrefined: u8 = 0, /// The band's second step: the sources to switch to (M-h), the acts on -/// the picked rows (M-l, M-Enter); `edit`: the field is the act Edit's -/// command, the query kept in `query`. -spine: enum(u8) { rows, sources, acts, edit } = .rows, +/// the picked rows (M-l, M-Enter), its source's earlier queries (C-r); +/// `edit`: the field is the act Edit's command, the query kept in `query`. +spine: enum(u8) { rows, sources, acts, edit, history } = .rows, +/// The line of its source's history the cursor of it unrolled is on +/// (Prompt.historyAt: 0 the newest holding the field). +recall: u8 = 0, /// The act step's cursor, among the acts offered. act_at: u8 = 0, /// The places Walk queued (C-i steps them in the landing pane): each a @@ -147,6 +153,15 @@ act_at: u8 = 0, queue: std.ArrayList(Queued) = .empty, queue_bytes: std.ArrayList(u8) = .empty, queue_at: u32 = 0, +/// Where it last landed, `@p2 › words.zig:16` (Lists' meta, UX L'3). +landed: Kind.Buf(80) = .{}, +/// Where it stands among the kept pickers, the newest the highest +/// (`touch`): Resume's order (`nth`), and the oldest goes for a new one. +used: u32 = 0, +/// The step of its landing pane's trail a walk reopened it at (Ctrl-o, +/// UX L'1): its Ctrl-o and Ctrl-i walk on from that word, and its Enter +/// lands as that word's, the steps after it dropped. +walking: ?u8 = null, pub const Queued = struct { path: u32, len: u16, line: u32, col: u32 }; @@ -167,11 +182,11 @@ pub fn deinit(pk: *Pick, gpa: std.mem.Allocator) void { /// Whether a search a builtin asks for from pane `id` is a picker in the /// tag (SPEC §14.3 phase 4): in a session whose jumps walk, from the -/// keyboard or a click (kbdin's and mousein's too), never a script's word -/// (a 9P exec's: the query pane, whose rows it reads back, and whose `not -/// found` it hears). +/// keyboard or a click (kbdin's and mousein's too, which run as theirs: +/// ninep/ctl.zig writeKbdin), never a script's word (a 9P exec's: the query +/// pane, whose rows it reads back, and whose `not found` it hears). pub fn asked(p: *const Pardes) bool { - return p.settings.jumps == .walk and (!p.fs.serving or p.fs.typed); + return p.settings.jumps == .walk and !p.fs.serving; } /// Picker `id`, kept or live. @@ -207,10 +222,12 @@ pub fn previewing(p: *const Pardes, id: usize) bool { pub fn open(p: *Pardes, from: usize, source: Source, word: []const u8, query: []const u8, rows: []const u8) void { const asker = p.panes[from] orelse return; TagState.toRest(p); + p.resume_at = 0; const pk = make(p, source) catch |err| return p.reportError(.at(from), "pick", err); pk.word.set(if (word.len > 0) word else words.get(source).word); pk.keys.set(words.get(source).keys); - pk.dir.set(Pardes.paneDir(asker)); + // Find and Grep from the work tree's root (W8), as other finders search. + pk.dir.set(if (source == .find or source == .grep) workTree(p, Pardes.paneDir(asker)) else Pardes.paneDir(asker)); pk.rows = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(from), "pick", err); hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "pick", err); if (p.paneBySerial(pk.landing)) |host| pk.cap = p.view().rects[host].h * 2 / 5; @@ -221,17 +238,55 @@ pub fn open(p: *Pardes, from: usize, source: Source, word: []const u8, query: [] if (source == .themes and query.len == 0 and p.custom_theme == null) p.view().tag_state.rows.at = @intCast(p.settings.theme); } +/// The work tree `dir` is in: the nearest directory at or above it that +/// holds a `.jj` or a `.git` (a git worktree's is a file); `dir` itself +/// when none does. Find and Grep search from it, their rows' paths +/// relative to it, wherever in the tree the asking pane is. +fn workTree(p: *Pardes, dir: []const u8) []const u8 { + var d = dir; + while (true) { + var buf: [4096]u8 = undefined; + for ([_][]const u8{ ".jj", ".git" }) |name| { + const marker = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, d, "/"), name }) catch return dir; + if (exec.kindOf(p.tape, marker) != null) return d; + } + d = std.Io.Dir.path.dirname(d) orelse return dir; + } +} + +/// Where a Grep's query `q` searches and for what (SPEC §5.1): a leading +/// directory, the root's or absolute, then a blank, narrows it to that +/// directory (`src/torque Macro`), the rest the pattern; else all of it +/// from the root. The directory joined in `buf`. +fn grepScope(p: *Pardes, pk: *const Pick, q: []const u8, buf: *[4096]u8) struct { dir: []const u8, pat: []const u8 } { + const root = pk.dir.slice(); + const sp = std.mem.indexOfScalar(u8, q, ' ') orelse return .{ .dir = root, .pat = q }; + const lead = q[0..sp]; + const dir = if (lead[0] == '/') lead else std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.trimEnd(u8, root, "/"), lead }) catch return .{ .dir = root, .pat = q }; + if (exec.kindOf(p.tape, dir) != .directory) return .{ .dir = root, .pat = q }; + return .{ .dir = dir, .pat = std.mem.trimStart(u8, q[sp + 1 ..], " ") }; +} + /// A new picker in the ring, the oldest kept one dropped for it. fn make(p: *Pardes, source: Source) !*Pick { var slot: ?usize = null; - for (p.picks, 0..) |s, i| if (s == null) { + // Lists is never kept (UX L'3): the one it had goes, and it drops none + // of the kept for its room. + for (p.picks, 0..) |s, i| if (s) |pk| if (source == .lists and pk.source == .lists) { + pk.deinit(p.gpa); + p.gpa.destroy(pk); + p.picks[i] = null; + slot = i; + break; + }; + if (slot == null and (source == .lists or nkept(p) < max_lists)) for (p.picks, 0..) |s, i| if (s == null) { slot = i; break; }; if (slot == null) { // The oldest not live. var oldest: ?usize = null; - for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and (oldest == null or pk.id < p.picks[oldest.?].?.id)) { + for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and pk.source != .lists and (oldest == null or rank(pk) < rank(p.picks[oldest.?].?))) { oldest = i; }; const i = oldest orelse return error.NoPickerSlots; @@ -244,9 +299,48 @@ fn make(p: *Pardes, source: Source) !*Pick { p.next_serial += 1; pk.* = .{ .id = p.next_serial, .source = source }; p.picks[slot.?] = pk; + touch(p, pk); return pk; } +/// Picker `pk` the newest kept (UX L': made, landed, reopened by a walk). +fn touch(p: *Pardes, pk: *Pick) void { + var top: u32 = 0; + for (p.picks) |slot| if (slot) |o| { + top = @max(top, o.used); + }; + pk.used = top +| 1; +} + +/// Where picker `pk` stands among the kept ones, newer higher: its `used`, +/// then its serial (pickers a dump made before `used` was kept). +fn rank(pk: *const Pick) u64 { + return @as(u64, pk.used) << 32 | pk.id; +} + +/// The `k`th newest kept picker, the newest 1. +fn nth(p: *const Pardes, k: usize) ?*Pick { + var below: u64 = std.math.maxInt(u64); + var found: ?*Pick = null; + for (0..k) |_| { + found = null; + for (p.picks) |slot| if (slot) |pk| if (pk.source != .lists and rank(pk) < below and (found == null or rank(pk) > rank(found.?))) { + found = pk; + }; + below = rank(found orelse return null); + } + return found; +} + +/// The pickers kept: not Lists. +fn nkept(p: *const Pardes) usize { + var n: usize = 0; + for (p.picks) |slot| if (slot) |pk| { + n += @intFromBool(pk.source != .lists); + }; + return n; +} + /// Picker `pk` asked from pane `from`: the pane it lands in is `from` when /// it reads; its reader when it is held and has one; else an untouched /// pane, `from` itself first (UX J1), which previews as a reading pane does @@ -331,6 +425,13 @@ fn start(p: *Pardes, pk: *Pick) void { addRows(p, pk, out.written()); }, .list => addRows(p, pk, pk.rows), + // The kept pickers, newest first, each by its list word. + .lists => for (1..max_lists + 1) |k| { + const kp = nth(p, k) orelse break; + var word: Kind.Buf(Trail.max_text) = .{}; + const text = wordOf(p, kp, &word); + pk.names.add(p.gpa, text, 0, text.len, 0, kp.id) catch return; + }, .messages => { var out: std.Io.Writer.Allocating = .init(p.gpa); defer out.deinit(); @@ -381,12 +482,17 @@ pub fn filter(p: *Pardes, pk: *Pick) void { const q = std.mem.trim(u8, p.view().tag_state.field.text(), " "); p.view().tag_state.rows.at = 0; pk.shown = no_row; - if (fuzzy(pk)) return pk.names.typed(p.gpa, q); + if (fuzzy(pk)) { + pk.names.typed(p.gpa, q); + return toBest(p, pk); + } if (pk.source == .grep) { pk.found.clearRetainingCapacity(); pk.found_bytes.clearRetainingCapacity(); - if (q.len > 0) { - Stream.query(p, pk.id, .grep, q, pk.dir.slice(), if (p.fs.serving) .now else .typed) catch |err| return p.reportError(.at(p.view().active), "pick", err); + var buf: [4096]u8 = undefined; + const at = grepScope(p, pk, q, &buf); + if (at.pat.len > 0) { + Stream.query(p, pk.id, .grep, at.pat, at.dir, if (p.fs.serving) .now else .typed) catch |err| return p.reportError(.at(p.view().active), "pick", err); if (p.fs.serving) Stream.step(p); } else if (p.stream.target == pk.id) _ = p.stream.stop(); return; @@ -430,7 +536,12 @@ fn allPanes(p: *const Pardes, pk: *const Pick, out: *[pardes.MAX_PANES]usize) [] /// The disk engine's rows for picker `target` (Stream.receive). pub fn take(p: *Pardes, target: u32, kind: Stream.Kind, rows: []const u8) bool { const pk = byId(p, target) orelse return false; - Query.take(p, pk, kind, rows); + // A Grep narrowed to a directory (grepScope): its rows' paths from the + // root, as an unnarrowed one's are. + var buf: [4096]u8 = undefined; + const searched = p.stream.dir.items; + const under = if (kind == .grep and !std.mem.eql(u8, searched, pk.dir.slice())) std.fmt.bufPrint(&buf, "{s}/", .{relative(searched, pk.dir.slice())}) catch "" else ""; + Query.take(p, pk, kind, rows, under); // A listing's names, scored as they come. if (kind == .files) pk.names.rescore(p.gpa); return true; @@ -443,15 +554,31 @@ pub fn declsArrived(p: *Pardes, serial: u32) void { Query.gather(p, &pk.names, .symbols, pk.dir.slice(), null, p.paneBySerial(serial)); pk.names.typed(p.gpa, pk.names.queryText()); pk.names.rescore(p.gpa); + if (live(p) == pk) toBest(p, pk); }; } +/// The live picker's cursor on its best match, wherever its group puts it +/// (UX DESIGN N3: a Symbols list stays grouped while typed), its rows +/// sorted as far as the band shows past it. +fn toBest(p: *Pardes, pk: *Pick) void { + const at = pk.names.bestRow(); + pk.names.reachTo(at + Band.Cursor.shown); + p.view().tag_state.rows.at = @intCast(@min(at, std.math.maxInt(u16))); +} + /// After every step: each live picker's names scored on (a frame's count), /// and on a frame of its own after the cursor stood, the preview of the /// current row. pub fn produceAll(p: *Pardes, tick: bool) void { for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { - if (pk.names.busy()) pk.names.rescore(p.gpa); + if (pk.names.busy()) { + // A cursor on the best match follows it while the rest are + // scored. + const on_best = live(p) == pk and p.view().tag_state.rows.at == pk.names.bestRow(); + pk.names.rescore(p.gpa); + if (on_best) toBest(p, pk); + } // A theme's preview in the step of the key that moved to it. if (pk.source == .themes) pardes.colors.previewTheme(p, refAt(p, pk)); if (tick) preview(p, pk); @@ -513,9 +640,9 @@ const Target = union(enum) { none, place: struct { path: []const u8, at: look.Sp /// Row `i` as the band shows it and what it points at, its text in /// `arena`. -const Row = struct { text: []const u8, key: u8 = 0, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" }; +const Row = struct { text: []const u8, key: u8 = 0, kind: u8 = 0, pre: u16 = 0, faint: u16 = 0, quiet: [2]u16 = .{ 0, 0 }, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" }; -fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { +fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) std.mem.Allocator.Error!Row { const dir = pk.dir.slice(); if (!fuzzy(pk) and pk.source == .all) { var order: [pardes.MAX_PANES]usize = undefined; @@ -555,7 +682,8 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { var marks: std.ArrayList(u16) = .empty; var c = fd.col; while (c < fd.end and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead)); - const path = try std.Io.Dir.path.join(arena, &.{ dir, name }); + // (Under an absolute leading directory, grepScope's, an absolute path.) + const path = if (name.len > 0 and name[0] == '/') name else try std.Io.Dir.path.join(arena, &.{ dir, name }); return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = .{ .place = .{ .path = path, .at = .{ .line = fd.line, .col = fd.col + 1 } } } }; } var marks: [Names.max_query * 4]u16 = undefined; @@ -568,19 +696,44 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { var namebuf: [4096]u8 = undefined; const name = if (text.len > 1 and text[0] == '"' and text[text.len - 1] == '"') look.unquoted(&namebuf, text[1 .. text.len - 1]) else text; row.faint = @intCast(if (std.mem.lastIndexOfScalar(u8, text, '/')) |k| k + 1 else 0); - row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = .{ .line = 1, .col = 1 } } }; + // A text at its first line; a kind's file whole, as a Look of + // its name opens it (a place in it is its kind's address). + const at: look.Spot = if (p.kinds.forPath(name) != null) .{} else .{ .line = 1, .col = 1 }; + row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = at } }; }, .panes => { row.pre = cand.key -| 1; row.dim = p.paneBySerial(cand.ref) == null; row.target = .{ .pane = cand.ref }; }, + // ` 12 m Counts.lines : usize = 0` (Query.gather): the line its + // meta, the mark in the keyword's ink, the qualifier and what + // follows the name dim (UX DESIGN N4). .symbols => { - row.pre = 6; + const line = 8; + if (text.len <= line or cand.key < line) return row; + row.text = text[line..]; + row.meta = std.mem.trimStart(u8, text[0..6], " "); + const marks_in = try arena.alloc(u16, row.marks.len); + for (marks_in, row.marks) |*m, at| m.* = at -| line; + row.marks = marks_in; + const name_at = cand.key - line; + row.kind = @intCast(name_at - 1); + row.pre = @intCast(name_at); + row.faint = cand.base; + if (name_at + cand.key_len < row.text.len) row.quiet = .{ @intCast(name_at + cand.key_len), @intCast(row.text.len) }; const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row; const f = owner.file orelse return row; row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } }; }, + // A kept picker: where it last landed, its current row's place the + // preview (UX L'3). + .lists => { + const kp = byId(p, cand.ref) orelse return row; + row.meta = kp.landed.slice(); + const n = count(p, kp); + if (n > 0) row.target = (try rowAt(p, kp, arena, @min(kp.at, n - 1))).target; + }, // The theme in use says so, whichever the window wears (POLISH 12). .themes => if (p.custom_theme == null and cand.ref == p.settings.theme) { row.meta = "in use"; @@ -647,6 +800,8 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { const text = &b.text; // SPC's cell, then its keys': `␣ f`. if (pk.keys.len > 0) try b.keyCells(.leader, pk.keys.slice()); + // One Resume opened: where it stands among the kept (UX L'2). + if (p.resume_at != 0) try text.print(arena, "Resume {d}/{d} ", .{ p.resume_at, nkept(p) }); try text.appendSlice(arena, pk.word.slice()); try text.append(arena, ' '); for (pk.refined[0..pk.nrefined]) |r| try text.print(arena, "{s} | ", .{r.query.slice()}); @@ -660,10 +815,15 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { if (n == 0) try text.append(arena, '0') else try text.print(arena, "{d}/{d}", .{ s.rows.at + 1, n }); if (pk.marks.items.len > 0) try text.print(arena, " •{d}", .{pk.marks.items.len}); if (pk.names.busy() or p.stream.busyFor(pk.id)) try text.appendSlice(arena, " ⋯"); - // Themes and actions have no acts and no other sources: no second row. - if (pk.source == .themes or pk.source == .actions) { + // Themes, actions and Lists have no acts and no other sources: no + // second row. + if (pk.source == .themes or pk.source == .actions or pk.source == .lists) { const hints = text.items.len; - try b.styled(if (pk.source == .themes) "⏎ wear it · esc" else "⏎ or 1-9 apply it · esc", .dim); + try b.styled(switch (pk.source) { + .themes => "⏎ wear it · esc", + .lists => "⏎ reopen it · esc", + else => "⏎ or 1-9 apply it · esc", + }, .dim); try b.right(counted, hints); var h = b.done(); h.caret = caret; @@ -685,7 +845,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { const nacts = nw; offer[nw] = "|"; nw += 1; - inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .messages and src != .themes and src != .actions and src != pk.source) { + inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .messages and src != .themes and src != .actions and src != .lists and src != pk.source) { offer[nw] = words.get(src).word; nw += 1; }; @@ -722,6 +882,7 @@ pub fn bandRows(p: *const Pardes) u16 { for (acts) |act| n += @intFromBool(offered(pk, act)); break :acts @max(rows, n); }, + .history => @max(rows, pardes.Prompt.historyRows(p.prompt_history.pick.getPtrConst(pk.source), p.view().tag_state.field.text())), .rows, .edit => rows, }); } @@ -731,8 +892,10 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { const pk = live(p) orelse return &.{}; const s = &p.view().tag_state; const n = count(p, pk); - const out = try arena.alloc(Band.Step, if (pk.spine == .sources or pk.spine == .acts) 2 else 1); + const out = try arena.alloc(Band.Step, if (pk.spine == .sources or pk.spine == .acts or pk.spine == .history or pk.source == .lists) 2 else 1); + if (pk.spine == .history) _ = try pardes.Prompt.historyStep(arena, p.prompt_history.pick.getPtrConst(pk.source), s.field.text(), pk.recall, &out[1]); if (pk.spine == .acts) out[1] = try actStep(p, pk, arena); + if (pk.source == .lists) out[1] = try listedStep(p, pk, arena); if (pk.spine == .sources) { const rows = try arena.alloc(Band.Row, spine_rows.len); for (spine_rows, rows, 0..) |src, *row, i| row.* = .{ .text = try std.fmt.allocPrint(arena, "{c} {s}", .{ src.key, src.word }), .key = 1, .index = @intCast(i), .dim = src.source == pk.source }; @@ -748,7 +911,7 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { const rows = try arena.alloc(Band.Row, w.hi - w.lo); for (rows, w.lo..) |*row, i| { const r = try rowAt(p, pk, arena, i); - row.* = .{ .text = r.text, .key = r.key, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i), .meta = r.meta }; + row.* = .{ .text = r.text, .key = r.key, .kind = r.kind, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .quiet = r.quiet, .marks = r.marks, .index = @intCast(i), .meta = r.meta }; } // A place's text (a Grep's line, a list's): its `path:line` in the dim // ink and the text after it in one column, the widest place shown @@ -778,6 +941,18 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { return out; } +/// Lists' second step (UX L'3): the kept picker under its cursor, its +/// rows around its own cursor, which is marked `▶`; read, never a list. +fn listedStep(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator) !Band.Step { + const kp = byId(p, @intCast(refAt(p, pk) orelse return .{ .doc = true })) orelse return .{ .doc = true }; + const n = count(p, kp); + const lo = if (kp.at < Band.Cursor.shown) 0 else kp.at + 1 - Band.Cursor.shown; + const hi = @min(n, lo + Band.Cursor.shown); + const rows = try arena.alloc(Band.Row, hi -| lo); + for (rows, lo..) |*row, i| row.* = .{ .text = try std.fmt.allocPrint(arena, "{s}{s}", .{ if (i == kp.at) "▶ " else " ", (try rowAt(p, kp, arena, i)).text }) }; + return .{ .rows = rows, .doc = true }; +} + // ---- the preview ---- /// The line (from 0) pane `pane`'s body lands the live picker's cursor row @@ -807,7 +982,7 @@ pub fn landingLine(p: *Pardes, arena: std.mem.Allocator, pane: *const Pane) ?usi /// previewing. pub fn sentence(p: *const Pardes, w: *std.Io.Writer) ?[2]usize { const pk = live(p) orelse return null; - if (!pk.previews or pk.source == .themes or pk.source == .actions) return null; + if (!pk.previews or pk.source == .themes or pk.source == .actions or pk.source == .lists) return null; if (pk.landing == pk.owner) { w.writeAll("⏎ lands here") catch return null; } else { @@ -824,7 +999,11 @@ pub fn sentence(p: *const Pardes, w: *std.Io.Writer) ?[2]usize { /// The landing pane's body showing the current row's place (SPEC §5.3): /// a file at its line, the query's matches lit for a Grep. Its own text is /// set aside the first time, put back when the picker rolls up. A file an -/// open pane shows is taken from it; any other is read. +/// open pane shows is taken from it; any other is read. A file a kind +/// takes (an addon's: a picture, a PDF), as a Look would open it +/// (look.resolve), shows through that kind (showKind); any other that is +/// not text (a NUL in its first 8000 bytes) as one line naming it, +/// `blob.bin · binary · 3.0 kB`, never its bytes. fn preview(p: *Pardes, pk: *Pick) void { const s = &p.view().tag_state; // No row yet: none shown, so the first to come is (a Find's listing @@ -843,45 +1022,27 @@ fn preview(p: *Pardes, pk: *Pick) void { const pane = p.panes[id].?; const f = if (pane.file) |*file| file else return; if (f.twin != 0) return; - if (!std.mem.eql(u8, f.path, place.path)) { + const showing = if (pane.addon) |k| k.path else f.path; + if (!std.mem.eql(u8, showing, place.path)) { if (exec.kindOf(p.tape, place.path)) |kind| if (kind != .file) return; - const bytes = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return); - if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { - p.gpa.free(bytes); - return; + const read = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return); + if (pane.addon != null) Kind.close(p, pane); + if (p.kinds.forPath(place.path)) |k| { + defer p.gpa.free(read); + return showKind(p, pk, id, k, place.path, read); } - const path = p.gpa.dupe(u8, place.path) catch { - p.gpa.free(bytes); - return; + const bytes = if (std.mem.indexOfScalar(u8, read[0..@min(read.len, 8000)], 0) == null) read else named: { + defer p.gpa.free(read); + break :named nameLine(p.gpa, place.path, "binary", read.len, "") catch return; }; - if (pk.aside == null and !pk.made) { - const history = File.History.create(p.gpa) catch { - p.gpa.free(bytes); - p.gpa.free(path); - return; - }; - pk.aside = pane.file; - pane.file = .{ .path = path, .content = bytes, .output = .{ .from = .preview }, .history = history }; - } else { - const pf = &pane.file.?; - p.gpa.free(pf.path); - pf.path = path; - File.setContent(p, pf, bytes); - pf.saved_revision = pf.revision; - pf.scroll = 0; - pf.scroll_row = 0; - pf.syntax_dirty = true; - pane.places.clear(p.gpa); - } - pane.hscroll = 0; - pk.previewed = true; - p.sync(); + showText(p, pk, id, place.path, bytes); } + if (pane.addon != null) return; // The body under the band from the first place it shows (previewing): // laid out again before the place is put in its rows. if (!pk.previewed) { pk.previewed = true; - p.sync(); + p.layOut(); } const keyboard = p.view().active; defer p.view().active = keyboard; @@ -897,7 +1058,85 @@ fn preview(p: *Pardes, pk: *Pick) void { } look.focusPaneLine(p, id, at, .third); // A Grep's matches in the file lit, as its own pane would have them. - if (pk.source == .grep) pane.places.search(p, pane, .list, pk.id, std.mem.trim(u8, s.field.text(), " "), true, null, false); + if (pk.source == .grep) { + var buf: [4096]u8 = undefined; + pane.places.search(p, pane, .list, pk.id, grepScope(p, pk, std.mem.trim(u8, s.field.text(), " "), &buf).pat, true, null, false); + } +} + +/// Landing pane `id`'s text `bytes` (taken) as `path`: its own text set +/// aside the first time, a preview's text after that changed in place. +fn showText(p: *Pardes, pk: *Pick, id: usize, path_: []const u8, bytes: []u8) void { + const pane = p.panes[id].?; + const path = p.gpa.dupe(u8, path_) catch { + p.gpa.free(bytes); + return; + }; + if (pk.aside == null and !pk.made) { + const history = File.History.create(p.gpa) catch { + p.gpa.free(bytes); + p.gpa.free(path); + return; + }; + pk.aside = pane.file; + pane.file = .{ .path = path, .content = bytes, .output = .{ .from = .preview }, .history = history }; + } else { + const pf = &pane.file.?; + p.gpa.free(pf.path); + pf.path = path; + File.setContent(p, pf, bytes); + pf.saved_revision = pf.revision; + pf.scroll = 0; + pf.scroll_row = 0; + pf.syntax_dirty = true; + pane.places.clear(p.gpa); + } + pane.hscroll = 0; + pk.previewed = true; + p.layOut(); +} + +/// Landing pane `id` showing the file at `path` through kind `k`, as a +/// Look would open it in a pane of its own: a slot of that kind over the +/// pane's text, which stays under it, unseen, until the next row or the +/// roll-up takes the slot away (Kind.close). Its kind does the work it +/// does for its own pane (an image decoded on a worker; a draw of a row +/// passed by dropped, Kind.Slot.drawn_from), and nothing more: what it +/// says, looks at or runs is not done while it previews (Kind.Call.end). +/// Until its picture is drawn, the line naming it (draw.zig); one its kind +/// refuses is that line as text, saying why. +fn showKind(p: *Pardes, pk: *Pick, id: usize, k: u8, path: []const u8, bytes: []const u8) void { + const pane = p.panes[id].?; + const slot = Kind.newSlot(p, k, path) catch |err| return p.reportError(.at(id), "pick", err); + slot.size = bytes.len; + pane.addon = slot; + pk.previewed = true; + if (!Kind.reopen(p, id, slot, bytes) and slot.refused.len > 0) { + const line = nameLine(p.gpa, path, slot.nameOf(), bytes.len, slot.refused.slice()) catch return Kind.close(p, pane); + Kind.close(p, pane); + return showText(p, pk, id, path, line); + } + p.layOut(); +} + +/// The one line a file shows while a picker previews it and none of its +/// text is shown: its name, what it is (`binary`, a kind's name), its size +/// and why when it says why: `photo.png · image · 1.2 MB`. +pub fn nameLine(gpa: std.mem.Allocator, path: []const u8, what: []const u8, size: u64, why: []const u8) ![]u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + try w.print("{s} · {s} · ", .{ std.Io.Dir.path.basename(path), what }); + if (size < 1000) try w.print("{d} B", .{size}) else { + const units = [_][]const u8{ "kB", "MB", "GB", "TB", "PB", "EB" }; + var unit: u64 = 1000; + var u: usize = 0; + while (size / unit >= 1000 and u + 1 < units.len) : (u += 1) unit *= 1000; + const tenths = size / (unit / 10); + try w.print("{d}.{d} {s}", .{ tenths / 10, tenths % 10, units[u] }); + } + if (why.len > 0) try w.print(" · {s}", .{why}); + return out.toOwnedSlice(); } /// The text of `path` as an open pane has it, copied: no read for it. @@ -918,6 +1157,9 @@ fn restore(p: *Pardes, pk: *Pick) void { const id = p.paneBySerial(pk.landing) orelse return; for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa); if (pk.made) { + // A kind's file shown: its slot closed first, as a pane's text + // closing is no file closed (no Recent row). + if (p.panes[id].?.addon != null) Kind.close(p, p.panes[id].?); pk.made = false; p.removePane(id, p.paneBySerial(pk.owner)) catch |err| p.reportError(.at(id), "pick", err); return; @@ -929,6 +1171,7 @@ fn restore(p: *Pardes, pk: *Pick) void { fn putBack(p: *Pardes, pk: *Pick) void { const id = p.paneBySerial(pk.landing) orelse return; const pane = p.panes[id].?; + if (pane.addon != null) Kind.close(p, pane); if (pk.made) return; const own = pk.aside orelse { // Its own file previewed: its caret and top as they were. @@ -944,7 +1187,7 @@ fn putBack(p: *Pardes, pk: *Pick) void { pane.body.cur_row = pk.aside_row; pane.body.cur_col = pk.aside_col; pane.body.vsel.active = false; - p.sync(); + p.layOut(); } /// The live picker rolled up (Esc, or the tag put to rest by anything): @@ -954,9 +1197,13 @@ pub fn rollUp(p: *Pardes) void { const pk = live(p) orelse return; const s = &p.view().tag_state; if (pk.spine != .edit) pk.query.set(s.field.text()); + // Its query its source's history's (UX L2's C-r): Lists keeps none. + if (pk.source != .lists) p.prompt_history.pick.getPtr(pk.source).add(pk.query.slice()); pk.spine = .rows; + pk.recall = 0; pk.at = s.rows.at; pk.unrolled = false; + pk.walking = null; if (p.stream.target == pk.id) _ = p.stream.stop(); restore(p, pk); } @@ -1071,8 +1318,8 @@ pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: if (rows <= first) return; const w: usize = s.cols; const old = try arena.dupe(Cell, s.cells[(y0 + first) * w .. (y0 + rows) * w]); - const grounds = colors.Grounds.of(p.theme()); - const ink = p.theme().fg orelse p.theme().tag_fg; + const chrome = p.chrome(); + const ink = chrome.page.text; const x0 = r.x + config.GUTTER + File.gutterWidth(pane); const width = r.w -| (x0 - r.x); var out: usize = first; @@ -1089,15 +1336,15 @@ pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: if (out >= rows) break; const y: u16 = @intCast(y0 + out); s.fill(0, y, @intCast(s.cols), 1, .{}); - s.fill(x0, y, width, 1, .{ .bg = .{ .rgb = grounds.add.row } }); - _ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = grounds.add.row } }); + s.fill(x0, y, width, 1, .{ .bg = .{ .rgb = chrome.add.row } }); + _ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = chrome.add.row } }); out += 1; }; } } if (out >= rows) break; @memcpy(s.cells[(y0 + out) * w ..][0..w], old[(vr - first) * w ..][0..w]); - if (g < groups.items.len and line >= groups.items[g].lo and line < groups.items[g].hi) s.tint(x0, @intCast(y0 + out), width, grounds.del.row, null); + if (g < groups.items.len and line >= groups.items[g].lo and line < groups.items[g].hi) s.tint(x0, @intCast(y0 + out), width, chrome.del.row, null); out += 1; } } @@ -1119,10 +1366,34 @@ pub fn key(p: *Pardes, k: Key) void { return; } if (pk.spine == .acts) return actKey(p, pk, k); + // Its source's earlier queries unrolled (C-r, UX L2): Down and Up + // move their cursor, Enter puts the one under it in the field, C-r + // and Esc (closeHistory) roll them up; anything else is the field's, + // which filters both. + if (pk.spine == .history) { + const r = p.prompt_history.pick.getPtr(pk.source); + if (pardes.Prompt.historyKey(r, s.field.text(), &pk.recall, k)) return; + if (plain and k.cp == Key.enter) { + const at = pardes.Prompt.historyAt(r, s.field.text(), pk.recall); + pk.spine = .rows; + pk.recall = 0; + if (at == 0) return; + s.field.set(r.get(at).?); + return filter(p, pk); + } + if (ctrl and k.cp == 'r') { + pk.spine = .rows; + return; + } + pk.recall = 0; + if (s.field.key(k)) filter(p, pk); + return; + } // Themes: Enter wears the one under the cursor; actions: Enter, or an // action's digit with the field empty, applies it; the rows and the // field. - if (pk.source == .themes or pk.source == .actions) { + if (pk.source == .themes or pk.source == .actions or pk.source == .lists) { + if (plain and k.cp == Key.enter and pk.source == .lists) return reopenListed(p, pk); if (plain and k.cp == Key.enter and pk.source == .themes) { const at = refAt(p, pk) orelse return; TagState.toRest(p); @@ -1148,6 +1419,12 @@ pub fn key(p: *Pardes, k: Key) void { _ = s.field.key(k); return; } + // A list a walk reopened (UX L'1): Ctrl-o and Ctrl-i walk on from its + // word, the list rolled up unlanded. Ctrl-i is Tab where the terminal + // cannot tell them apart: a mark, as Tab. + if (pk.walking) |at| if (ctrl and (k.cp == 'o' or k.cp == 'i')) return walkOn(p, pk, at, if (k.cp == 'o') -1 else 1); + // One Resume opened: the next older or newer kept one (UX L'2). + if (p.resume_at != 0 and ctrl and (k.cp == 'o' or k.cp == 'i')) return resumeAt(p, p.paneBySerial(pk.owner) orelse p.view().active, if (k.cp == 'o') p.resume_at + 1 else p.resume_at - 1); if (alt and (k.cp == Key.enter or k.cp == 'l')) { pk.spine = .acts; pk.act_at = 0; @@ -1169,6 +1446,11 @@ pub fn key(p: *Pardes, k: Key) void { } if (ctrl and (k.cp == ' ' or k.cp == '@')) return refine(p, pk, false); if (ctrl and k.cp == 'q') return keep(p, pk); + if (ctrl and k.cp == 'r') { + pk.spine = .history; + pk.recall = 0; + return; + } if (alt and k.cp == 'p') { pk.previews = !pk.previews; pk.shown = no_row; @@ -1184,6 +1466,16 @@ pub fn key(p: *Pardes, k: Key) void { if (s.field.key(k)) filter(p, pk); } +/// Esc with the live picker's history unrolled (keys.tagStateKey): that +/// rolled up alone, the picker as it was; false with none. +pub fn closeHistory(p: *Pardes) bool { + const pk = live(p) orelse return false; + if (pk.spine != .history) return false; + pk.spine = .rows; + pk.recall = 0; + return true; +} + /// The source spine (M-h): a key a source, the query kept. const spine_rows = [_]struct { key: u8, word: []const u8, source: ?Source }{ .{ .key = 'f', .word = "Find", .source = .find }, @@ -1192,6 +1484,7 @@ const spine_rows = [_]struct { key: u8, word: []const u8, source: ?Source }{ .{ .key = 'b', .word = "Panes", .source = .panes }, .{ .key = 's', .word = "Symbols", .source = .symbols }, .{ .key = '/', .word = "All", .source = .all }, + .{ .key = '\'', .word = "Lists", .source = .lists }, .{ .key = '?', .word = "Help", .source = null }, }; @@ -1207,6 +1500,13 @@ fn switchTo(p: *Pardes, pk: *Pick, source: ?Source) void { p.view().tag_state.field.set(query.slice()); return TagState.filter(p); }; + // Lists is a picker of the kept ones, this one among them: one of its + // own, from where this one was asked (UX L'3). + if (to == .lists) { + const from = p.paneBySerial(pk.owner) orelse p.view().active; + TagState.toRest(p); + return open(p, from, to, "", "", ""); + } if (p.stream.target == pk.id) _ = p.stream.stop(); for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pk.id) tp.places.clear(p.gpa); for (pk.refined[0..pk.nrefined]) |*r| r.names.deinit(p.gpa); @@ -1257,6 +1557,7 @@ fn refine(p: *Pardes, pk: *Pick, drop: bool) void { if (drop and (if (pk.marks.items.len > 0) marked(pk, h.cand) != null else h.cand == current)) continue; const c = pk.names.cands.items[h.cand]; next.add(p.gpa, pk.names.bytes.items[c.start..][0..c.len], c.key, c.key_len, c.base, c.ref) catch break; + next.cands.items[next.cands.items.len - 1].group = c.group; } } else { var arena = std.heap.ArenaAllocator.init(p.gpa); @@ -1308,6 +1609,7 @@ fn back(p: *Pardes, pk: *Pick) void { if (!fuzzy(pk) and pk.source == .all) filter(p, pk); return; } + if (pk.walking) |at| return walkOn(p, pk, at, -1); const keys = pk.keys; TagState.toRest(p); if (keys.len == 0) return; @@ -1318,6 +1620,16 @@ fn back(p: *Pardes, pk: *Pick) void { s.unrolled = true; } +/// Ctrl-o (`delta` < 0) or Ctrl-i in a list a walk reopened at step `at` +/// of its landing pane's trail (UX L'1): the list rolled up unlanded, the +/// pane as it was, and the walk on from the list's word; past the last +/// word, the jump list's step. +fn walkOn(p: *Pardes, pk: *Pick, at: u8, delta: i32) void { + const id = p.paneBySerial(pk.landing) orelse return TagState.toRest(p); + TagState.toRest(p); + if (!Trail.walkFrom(p, id, at, delta)) pardes.Jump.listBy(p, delta); +} + /// C-q: the rows (the marked, else all, `Query.max_rows` at most) kept as /// text in a +Search under the asking pane, the source's word and query /// its first line, each row an address a Look opens. @@ -1345,7 +1657,7 @@ fn keep(p: *Pardes, pk: *Pick) void { const row = rowAt(p, pk, arena.allocator(), i) catch break; switch (row.target) { .place => |t| if (pk.source == .symbols) - out.writer.print("{s}:{d} {s}\n", .{ std.Io.Dir.path.basename(t.path), t.at.line, std.mem.trimStart(u8, row.text, " 0123456789") }) catch break + out.writer.print("{s}:{d} {s}\n", .{ std.Io.Dir.path.basename(t.path), t.at.line, row.text }) catch break else out.writer.print("{s}\n", .{row.text}) catch break, else => out.writer.print("{s}\n", .{row.text}) catch break, @@ -1379,6 +1691,9 @@ fn land(p: *Pardes, wanted: How) void { const a = arena.allocator(); const picked = pickedRows(p, pk, a) catch return; if (picked.len == 0) return; + const walking = pk.walking; + touch(p, pk); + p.resume_at = 0; // Walk: the first now, the others queued for C-i. pk.queue.clearRetainingCapacity(); pk.queue_bytes.clearRetainingCapacity(); @@ -1412,9 +1727,17 @@ fn land(p: *Pardes, wanted: How) void { _ = p.store.reopen(p, serial, from); }, .place => |at| if (k == 0 and (how == .walk or how == .queue)) { + // A list a walk reopened lands as its word's (UX L'1): a step + // from that word, the steps after it dropped. + const word: ?u8 = if (walking) |i| (if (from == landing and isWord(p.panes[from].?, i, pk.id)) i else null) else null; + if (word) |i| { + const trail = &p.panes[from].?.trail; + trail.n = i + 1; + trail.cur = i; + } switch (look.open(p, from, at.path, at.at, .replace)) { .none => {}, - else => listed(p, pk), + else => listed(p, pk, word), } } else if (k == 0 and how == .column) { // A column made only where there is no free space (UX J1). @@ -1429,6 +1752,9 @@ fn land(p: *Pardes, wanted: How) void { _ = look.open(p, from, at.path, at.at, .below); }, }; + if (picked[0] == .place) if (p.panes[v.active]) |at| if (at.file) |f| { + _ = pk.landed.print(config.pane_addr ++ "{d} › {s}:{d}", .{ at.serial, std.Io.Dir.path.basename(f.path), at.body.cur_row + 1 }); + }; if (how == .queue and pk.queue.items.len > 0) { var said: Kind.Buf(64) = .{}; p.setMessage(.at(v.active), said.print("Walk: {d} more places here, C-i for the next", .{pk.queue.items.len})); @@ -1452,11 +1778,25 @@ fn wordOf(p: *const Pardes, pk: *const Pick, buf: *Kind.Buf(Trail.max_text)) []c return buf.slice(); } +/// Whether step `i` of pane `pane`'s trail is picker `id`'s word. +fn isWord(pane: *const Pane, i: u8, id: u32) bool { + const t = &pane.trail; + return i < t.n and t.steps[i] == .list and t.steps[i].list.index == id; +} + /// The list rolled into the trail of the reading pane it landed in, its -/// word before the place: the list `n` and `N` walk there. -fn listed(p: *Pardes, pk: *const Pick) void { - const pane = p.panes[p.view().active] orelse return; +/// word before the place: the list `n` and `N` walk there; a list a walk +/// reopened at step `at` says where it is now in that word. The notice row +/// says what Ctrl-o goes back to (UX L'1). +fn listed(p: *Pardes, pk: *const Pick, at: ?u8) void { + const id = p.view().active; + const pane = p.panes[id] orelse return; if (!Trail.reading(p, pane)) return; + defer Trail.sayBack(p, id); + if (at) |i| if (isWord(pane, i, pk.id)) { + _ = wordOf(p, pk, &pane.trail.steps[i].list.text); + return; + }; var w: Trail.Word = .{ .index = pk.id }; _ = wordOf(p, pk, &w.text); Trail.through(&pane.trail, .{ .list = w }); @@ -1502,16 +1842,20 @@ pub fn walkList(p: *Pardes, id: usize, forward: bool) bool { return true; } -/// Look on a list word in pane `id`'s trail (SPEC §6.3): the list unrolled -/// again in that pane's tag, its rows, marks, cursor and query as they were. -pub fn reopen(p: *Pardes, id: usize, index: u32) void { +/// Look on a list word in pane `id`'s trail (SPEC §6.3), or a walk onto +/// it at step `walking` (UX L'1): the list unrolled again in that pane's +/// tag, its rows, marks, cursor and query as they were. +pub fn reopen(p: *Pardes, id: usize, index: u32, walking: ?u8) void { const pk = byId(p, index) orelse return p.setMessage(.at(id), "walk: that list is gone: the last 8 are kept"); const pane = p.panes[id] orelse return; TagState.toRest(p); + p.resume_at = 0; + touch(p, pk); pk.landing = pane.serial; pk.made = false; unroll(p, pk, pk.query.slice()); unrollRows(p, pk); + pk.walking = walking; } /// A list unrolled again: All's places found again, the cursor where it was. @@ -1530,27 +1874,57 @@ pub fn rerun(p: *Pardes, id: usize, index: u32) void { open(p, id, pk.source, pk.word.slice(), query.slice(), pk.rows); } -/// Resume (`SPC '`): the last picker reopened as it was, from pane `from`, -/// in the tag of the pane its Enter lands in. +/// Resume (`SPC '`): the newest kept picker reopened as it was, from pane +/// `from`, in the tag of the pane its Enter lands in; again after an Esc +/// from it, nothing typed between, the one before it (UX L'2). pub fn resumeFrom(p: *Pardes, from: usize) void { - var newest: ?*Pick = null; - for (p.picks) |slot| if (slot) |pk| if (newest == null or pk.id > newest.?.id) { - newest = pk; - }; - const pk = newest orelse return p.setMessage(.at(from), "Resume: no picker yet"); - TagState.toRest(p); + if (p.resume_at == 0 and nkept(p) == 0) return p.setMessage(.at(from), "Resume: no picker yet"); if (p.panes[from] == null) return; + resumeAt(p, from, p.resume_at + 1); +} + +/// The `k`th newest kept picker reopened as it was, asked from pane +/// `from`, in the tag of the pane its Enter lands in. +fn resumeAt(p: *Pardes, from: usize, k: usize) void { + const pk = (if (k > 0) nth(p, k) else null) orelse + return p.setMessage(.at(from), if (k == 0) "Resume: the newest picker" else "Resume: no picker before it: the last 8 are kept"); + TagState.toRest(p); hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "Resume", err); unroll(p, pk, pk.query.slice()); unrollRows(p, pk); + p.resume_at = @intCast(k); +} + +/// A key the tag at rest takes (keys.handleKey): any but the leader and +/// Resume's after it ends a Resume walk, so that `SPC '` opens the newest +/// again (UX L'2). +pub fn keyAtRest(p: *Pardes, k: Key) void { + const v = p.view(); + if (p.resume_at == 0) return; + if (v.prefix == .none and pardes.hit(k, config.leader)) return; + if (v.prefix == .leader and v.leader_n == 0 and !k.ctrl and !k.alt and k.cp == config.leader_path.get(.Resume).?[0]) return; + p.resume_at = 0; } /// B3 on a picker's row (mouse.zig bandPress): Enter on it. pub fn landHere(p: *Pardes) void { const pk = live(p) orelse return; + if (pk.source == .lists) return reopenListed(p, pk); if (pk.spine == .rows) land(p, .walk); } +/// Enter in Lists (UX L'3): the kept picker under its cursor unrolled again +/// as it was left, where Lists was asked from, and the newest now. +fn reopenListed(p: *Pardes, pk: *Pick) void { + const kp = byId(p, @intCast(refAt(p, pk) orelse return)) orelse return; + const from = p.paneBySerial(pk.owner) orelse p.view().active; + TagState.toRest(p); + touch(p, kp); + hostIn(p, kp, from) catch |err| return p.reportError(.at(from), "Lists", err); + unroll(p, kp, kp.query.slice()); + unrollRows(p, kp); +} + /// The rows an act or Enter takes: the marked, else the current. fn pickedRows(p: *Pardes, pk: *const Pick, a: std.mem.Allocator) ![]Target { const s = &p.view().tag_state; @@ -1749,6 +2123,8 @@ fn editRows(p: *Pardes, pk: *Pick) void { /// picker's. pub fn execWord(p: *Pardes, txt: []const u8) bool { const pk = live(p) orelse return false; + // Lists offers no acts and no sources (UX L'3). + if (pk.source == .lists) return false; const word = std.mem.trim(u8, txt, " \t\n"); for (spine_rows) |src| if (std.mem.eql(u8, word, src.word)) { switchTo(p, pk, src.source); @@ -1766,6 +2142,9 @@ pub fn execWord(p: *Pardes, txt: []const u8) bool { } fn testFile(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) ![]u8 { + // The directory a work tree of its own, as a project is: Find and Grep + // search it, not the tree the test runs in. + tmp.dir.createDir(std.testing.io, ".git", .default_dir) catch |err| if (err != error.PathAlreadyExists) return err; try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; @@ -2352,15 +2731,15 @@ test "code actions: a picker in the asking pane's tag, the one under the cursor const r = p.view().rects[id]; const x = r.x + config.GUTTER + File.gutterWidth(pane); const y = p.bodyTop(pane, r); - const grounds = colors.Grounds.of(p.theme()); + const chrome = p.chrome(); for ([_][]const u8{ "o", "t", "t", "t" }, [_][]const u8{ "n", "w", "w", "h" }, 0..) |c0, c1, row| { try std.testing.expectEqualStrings(c0, shot.at(x, y + @as(u16, @intCast(row))).grapheme()); try std.testing.expectEqualStrings(c1, shot.at(x + 1, y + @as(u16, @intCast(row))).grapheme()); } try std.testing.expectEqualStrings("a", shot.at(x + 4, y + 1).grapheme()); try std.testing.expectEqualStrings("s", shot.at(x + 4, y + 2).grapheme()); - try std.testing.expectEqual(pardes.Color{ .rgb = grounds.del.row }, shot.at(x, y + 1).style.bg); - try std.testing.expectEqual(pardes.Color{ .rgb = grounds.add.row }, shot.at(x, y + 2).style.bg); + try std.testing.expectEqual(pardes.Color{ .rgb = chrome.del.row }, shot.at(x, y + 1).style.bg); + try std.testing.expectEqual(pardes.Color{ .rgb = chrome.add.row }, shot.at(x, y + 2).style.bg); try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content); // An action lands nowhere: no landing line, no `▸` before the line it // changes, no sentence of where Enter lands (UX D7's are a jump's; an @@ -2377,10 +2756,10 @@ test "code actions: a picker in the asking pane's tag, the one under the cursor frame = std.heap.ArenaAllocator.init(std.testing.allocator); shot = try p.render(frame.allocator()); try std.testing.expectEqualStrings("/", shot.at(x, y).grapheme()); - try std.testing.expectEqual(pardes.Color{ .rgb = grounds.add.row }, shot.at(x, y).style.bg); + try std.testing.expectEqual(pardes.Color{ .rgb = chrome.add.row }, shot.at(x, y).style.bg); try std.testing.expectEqualStrings("o", shot.at(x, y + 1).grapheme()); - try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = grounds.del.row }, shot.at(x, y + 1).style.bg)); - try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.chromeTheme().roles.hit }, shot.at(x, y + 1).style.bg)); + try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = chrome.del.row }, shot.at(x, y + 1).style.bg)); + try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.chrome().hit }, shot.at(x, y + 1).style.bg)); // `3`: the rename applied, the tag at rest; one undo takes it back. p.update(.{ .key = .{ .cp = '3', .text = "3" } }); try std.testing.expectEqual(TagState.Kind.rest, s.kind); @@ -2487,16 +2866,16 @@ test "a picker's preview is legible as one (UX D7): its landing line on the hit }; try std.testing.expectEqual(@as(?u16, @intCast((pane.rows + 2) / 3)), at); const y = body_y + at.?; - const roles = &p.chromeTheme().roles; + const c = p.chrome(); const tx = r.x + pardes.config.GUTTER; const gutter = File.gutterWidth(pane); // Its text on the hit ground across the row; the row above as it was. - for (gutter..r.w - pardes.config.GUTTER) |x| try std.testing.expectEqual(pardes.Color{ .rgb = roles.hit }, s.at(tx + @as(u16, @intCast(x)), y).style.bg); - try std.testing.expect(!std.meta.eql(s.at(tx + gutter + 2, y - 1).style.bg, pardes.Color{ .rgb = roles.hit })); + for (gutter..r.w - pardes.config.GUTTER) |x| try std.testing.expectEqual(pardes.Color{ .rgb = c.hit }, s.at(tx + @as(u16, @intCast(x)), y).style.bg); + try std.testing.expect(!std.meta.eql(s.at(tx + gutter + 2, y - 1).style.bg, pardes.Color{ .rgb = c.hit })); // `▸` in the key ink in the gutter's cell after the number. const mark = s.at(tx + gutter - 1, y); try std.testing.expectEqualStrings("▸", mark.grapheme()); - try std.testing.expectEqual(pardes.Color{ .rgb = roles.key }, mark.style.fg); + try std.testing.expectEqual(pardes.Color{ .rgb = c.page.key }, mark.style.fg); // The notice row: where Enter lands, the owner's address a word in it. var buf: [pardes.Messages.notice_row_cap]u8 = undefined; const said = pardes.Messages.noticeRow(p, 120, &buf); @@ -2815,3 +3194,510 @@ test "a picker's preview starts under its band: its landing line ⌈visible/3⌉ try std.testing.expectEqual(rest, .{ pane.tag_rows, pane.rows, pane.file.?.scroll, p.bodyTop(pane, r) }); try std.testing.expect(std.mem.startsWith(u8, pane.file.?.content, "own 1\n")); } + +test "SPC ' steps back through the kept pickers (UX L'2): again after an Esc, nothing typed between, the one before; Ctrl-o and Ctrl-i in it the next older and newer, its head `Resume 2/3`; a key between, the newest again; a list word naming a picker no longer kept says so and the walk passes it by" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "base.zig", "text\n"); + const base = try p.setTestFile("text\n"); + p.gpa.free(base.file.?.path); + base.file.?.path = b_path; + const id = p.view().active; + const row = try std.fmt.allocPrint(p.gpa, "{s}:2:1 two\n", .{a_path}); + defer p.gpa.free(row); + // Three lists kept, C the newest. + for ([_][]const u8{ "A", "B", "C" }) |word| { + open(p, id, .list, word, "", row); + p.update(.{ .key = .{ .cp = Key.escape } }); + } + try std.testing.expect(live(p) == null); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const Shown = struct { + /// The live picker's word and its head's `Resume k/N`, as `2/3 B`. + fn of(pp: *Pardes, a: std.mem.Allocator) ![]const u8 { + const pk = live(pp) orelse return "none"; + const h = (try head(pp, a, pp.panes[pp.paneBySerial(pk.landing).?].?)).?; + const at = std.mem.indexOf(u8, h.text, "Resume ") orelse return pk.word.slice(); + const end = std.mem.indexOfScalarPos(u8, h.text, at + "Resume ".len, ' ').?; + return std.fmt.allocPrint(a, "{s} {s}", .{ h.text[at + "Resume ".len .. end], pk.word.slice() }); + } + }; + const Step = struct { keys: []const u8, want: []const u8 }; + for ([_]Step{ + .{ .keys = " '", .want = "1/3 C" }, + .{ .keys = "\x1b '", .want = "2/3 B" }, + .{ .keys = "o", .want = "3/3 A" }, + .{ .keys = "o", .want = "3/3 A" }, + .{ .keys = "i", .want = "2/3 B" }, + .{ .keys = "i", .want = "1/3 C" }, + .{ .keys = "\x1bj '", .want = "1/3 C" }, + .{ .keys = "\x1b '", .want = "2/3 B" }, + }, 0..) |step, n| { + for (step.keys) |c| switch (c) { + 0x1b => p.update(.{ .key = .{ .cp = Key.escape } }), + // Ctrl-o and Ctrl-i alone in a step: in the picker. + 'o', 'i' => p.update(.{ .key = .{ .cp = c, .ctrl = true } }), + else => p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }), + }; + errdefer std.debug.print("step {d}\n", .{n}); + try std.testing.expectEqualStrings(step.want, try Shown.of(p, frame.allocator())); + if (n == 3) try std.testing.expect(std.mem.indexOf(u8, p.messages.headline().?.words(), "no picker before it") != null); + } + // Its Enter lands as any list's: the walk over, it the newest. + p.update(.{ .key = .{ .cp = Key.enter } }); + p.sync(); + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + p.update(.{ .key = .{ .cp = '\'', .text = "'" } }); + try std.testing.expectEqualStrings("1/3 B", try Shown.of(p, frame.allocator())); + p.update(.{ .key = .{ .cp = Key.escape } }); + // A list word naming a picker no longer kept: said, and passed by. + const reader = p.view().active; + const t = &p.panes[reader].?.trail; + try std.testing.expect(t.n == 3 and t.cur == 2 and t.steps[1] == .list); + t.steps[1].list.index = 999_999; + p.update(.{ .key = .{ .cp = 'o', .ctrl = true } }); + p.sync(); + try std.testing.expect(std.mem.indexOf(u8, p.messages.headline().?.words(), "that list is gone: the last 8 are kept") != null); + try std.testing.expect(live(p) == null); + try std.testing.expectEqualStrings("base.zig", std.Io.Dir.path.basename(p.panes[p.view().active].?.file.?.path)); + try std.testing.expectEqual(@as(u8, 0), p.panes[p.view().active].?.trail.cur); +} + +test "Lists (UX L'3): a picker of the kept pickers, newest first, each its list word and where it last landed; the body previews the one under the cursor at its current row, its rows beside, its cursor's marked; Enter reopens it as it was left, the newest now; Lists is never kept and drops none of the eight for its room" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const a_path = try testFile(p, &tmp, "alpha.zig", "one\ntwo\n"); + defer p.gpa.free(a_path); + const b_path = try testFile(p, &tmp, "beta.zig", "b1\nb2\n"); + defer p.gpa.free(b_path); + const base = try p.setTestFile("text\n"); + p.gpa.free(base.file.?.path); + base.file.?.path = try testFile(p, &tmp, "base.zig", "text\n"); + const rows = try std.fmt.allocPrint(p.gpa, "{s}:2:1 two\n{s}:2:1 b2\n", .{ a_path, b_path }); + defer p.gpa.free(rows); + // Eight kept: A to F, G left on its second row, H landed, the newest. + for ("ABCDEFG") |c| { + open(p, p.view().active, .list, &[_]u8{c}, "", rows); + if (c == 'G') p.update(.{ .key = .{ .cp = Key.down } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + } + open(p, p.view().active, .list, "H", "", rows); + p.update(.{ .key = .{ .cp = Key.enter } }); + p.sync(); + const at = p.view().active; + var ids: [max_lists]u32 = undefined; + for (&ids, 1..) |*id, k| id.* = nth(p, max_lists + 1 - k).?.id; + exec.runBuiltin(p, .Lists, at, "", null); + const lists = live(p).?; + try std.testing.expectEqual(Source.lists, lists.source); + // None dropped for it, and it is none of the kept. + try std.testing.expectEqual(@as(usize, max_lists), nkept(p)); + for (ids) |id| try std.testing.expect(byId(p, id) != null); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + try std.testing.expectEqual(@as(usize, max_lists), count(p, lists)); + var buf: [64]u8 = undefined; + for ("HGFEDCBA", 0..) |c, i| { + const row = try rowAt(p, lists, a, i); + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{c} {d}/2", .{ c, @as(u8, if (c == 'G') 2 else 1) }), row.text); + if (c == 'H') try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "@p{d} › alpha.zig:2", .{p.panes[at].?.serial}), row.meta); + } + // On G: the body previews its current row, beta.zig's line 2; its rows + // beside, its cursor's marked. + p.update(.{ .key = .{ .cp = Key.down } }); + settle(p); + const host = p.panes[p.paneBySerial(lists.landing).?].?; + try std.testing.expectEqualStrings(b_path, host.file.?.path); + try std.testing.expectEqual(@as(i32, 1), host.body.cur_row); + const band = try steps(p, a); + try std.testing.expect(band.len == 2 and band[1].doc and band[1].rows.len == 2); + try std.testing.expect(std.mem.startsWith(u8, band[1].rows[1].text, "▶ ") and std.mem.startsWith(u8, band[1].rows[0].text, " ")); + // Enter: G as it was left, the newest now; Lists rolled up. + p.update(.{ .key = .{ .cp = Key.enter } }); + const g = live(p).?; + try std.testing.expectEqualStrings("G", g.word.slice()); + try std.testing.expectEqual(@as(u16, 1), p.view().tag_state.rows.at); + try std.testing.expect(nth(p, 1).? == g); + p.update(.{ .key = .{ .cp = Key.escape } }); + // A ninth picker drops the oldest kept, never for Lists' room. + open(p, p.view().active, .list, "I", "", rows); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(usize, max_lists), nkept(p)); + try std.testing.expect(byId(p, ids[0]) == null and byId(p, ids[1]) != null); + // `'` among a picker's sources (M-h): Lists, from where it was asked. + open(p, p.view().active, .list, "J", "", rows); + p.update(.{ .key = .{ .cp = 'h', .alt = true } }); + p.update(.{ .key = .{ .cp = '\'', .text = "'" } }); + try std.testing.expectEqual(Source.lists, live(p).?.source); + try std.testing.expectEqualStrings("J 1/2", (try rowAt(p, live(p).?, a, 0)).text); + p.update(.{ .key = .{ .cp = Key.escape } }); +} + +test "Ctrl-r in a picker unrolls its source's earlier queries (UX L2's last line): recorded as a picker lands and as it is left with its field typed; the band's rows filtered by the field, Enter puts one in the field, Esc closes the band; each source its own; Lists none; as many as a prompt's history keeps" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + p.stream.engine = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const w_path = try testFile(p, &tmp, "words.zig", "in_word\n"); + defer p.gpa.free(w_path); + const base = try p.setTestFile("text\n"); + p.gpa.free(base.file.?.path); + base.file.?.path = try testFile(p, &tmp, "main.zig", "text\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const History = struct { + /// The history band's rows, joined by `|`; "" with none shown. + fn rows(pp: *Pardes, a: std.mem.Allocator) ![]const u8 { + const band = try steps(pp, a); + if (band.len < 2) return ""; + var out: std.ArrayList(u8) = .empty; + for (band[1].rows, 0..) |row, i| try out.print(a, "{s}{s}", .{ if (i > 0) "|" else "", row.text }); + return out.items; + } + }; + const ctrl_r: Key = .{ .cp = 'r', .ctrl = true }; + const Type = struct { + fn keys(pp: *Pardes, text: []const u8) void { + for (text) |c| pp.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + } + }; + // SPC f f words, Enter: `words` is Find's. + Type.keys(p, " ffwords"); + settle(p); + p.update(.{ .key = .{ .cp = Key.enter } }); + p.sync(); + try std.testing.expect(live(p) == null); + // A Grep left with its field typed: `in_w` is Grep's. + Type.keys(p, " fgin_w"); + p.update(.{ .key = .{ .cp = Key.escape } }); + // SPC f f, Ctrl-r: Find's alone. + Type.keys(p, " ff"); + p.update(.{ .key = ctrl_r }); + try std.testing.expectEqualStrings("words", try History.rows(p, frame.allocator())); + // Esc closes the band, back to the picker; Ctrl-r again, Enter: the + // line in the field, the rows filtered by it. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(live(p) != null); + try std.testing.expectEqualStrings("", try History.rows(p, frame.allocator())); + p.update(.{ .key = ctrl_r }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(live(p) != null); + try std.testing.expectEqualStrings("words", p.view().tag_state.field.text()); + try std.testing.expectEqualStrings("", try History.rows(p, frame.allocator())); + settle(p); + try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?)); + p.update(.{ .key = .{ .cp = Key.escape } }); + // Grep's: its own line. + Type.keys(p, " fg"); + p.update(.{ .key = ctrl_r }); + try std.testing.expectEqualStrings("in_w", try History.rows(p, frame.allocator())); + p.update(.{ .key = .{ .cp = Key.escape } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + // Lists keeps none: left with its field typed, nothing recorded. + Type.keys(p, " flzz"); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(@as(u8, 0), p.prompt_history.pick.get(.lists).n); + // The bound: a prompt's history's, the oldest gone, newest first; the + // rows filtered by the field. + for (0..pardes.Prompt.Ring.max + 1) |i| { + Type.keys(p, " ff"); + var q: [8]u8 = undefined; + Type.keys(p, try std.fmt.bufPrint(&q, "q{d}", .{i})); + p.update(.{ .key = .{ .cp = Key.escape } }); + } + const find = p.prompt_history.pick.get(.find); + try std.testing.expectEqual(@as(u8, pardes.Prompt.Ring.max), find.n); + try std.testing.expectEqualStrings("q16", find.get(1).?); + try std.testing.expectEqualStrings("q1", find.get(pardes.Prompt.Ring.max).?); + Type.keys(p, " ffq1"); + p.update(.{ .key = ctrl_r }); + const shown = try History.rows(p, frame.allocator()); + try std.testing.expect(std.mem.startsWith(u8, shown, "q16|q15|q14|q13|q12|q11|q10|q1")); + try std.testing.expect(std.mem.indexOf(u8, shown, "words") == null); + p.update(.{ .key = .{ .cp = Key.escape } }); + p.update(.{ .key = .{ .cp = Key.escape } }); +} + +/// A Symbols picker opened from a file pane whose path is `name` and text +/// `text`, its symbols parsed (small: here and now), and the pane. +fn openSymbols(p: *Pardes, name: []const u8, text: []const u8) !*Pane { + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, name); + open(p, p.view().active, .symbols, "", "", ""); + settle(p); + return pane; +} + +/// The live picker's rows, `meta text` a line each. +fn rowLines(p: *Pardes, a: std.mem.Allocator) ![]const u8 { + const pk = live(p).?; + var out: std.ArrayList(u8) = .empty; + for (0..count(p, pk)) |i| { + const r = try rowAt(p, pk, a, i); + try out.print(a, "{s: >2} {s}\n", .{ r.meta, r.text }); + } + return out.items; +} + +const counts_zig = + \\const std = @import("std"); + \\pub const Counts = struct { + \\ lines: usize = 0, + \\ words: usize = 0, + \\ pub const zero: Counts = .{}; + \\ pub fn add(c: *Counts, text: []const u8) void { + \\ const local = text.len; + \\ c.lines += local; + \\ } + \\}; + \\const Mode = enum { fast, slow }; + \\var hits: u32 = 0; + \\pub fn count(text: []const u8) Counts { + \\ return .{ .lines = text.len }; + \\} + \\test "count.add" {} + \\ +; + +test "Symbols (UX DESIGN N): a Zig file's rows types, functions, fields, then the rest, each in the text's order with the field empty; a row its kind's mark, its name qualified, what its first line says after it, its line the meta; the mark in the keyword's ink, the qualifier and the rest dim" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + _ = try openSymbols(p, "/w6/counts.zig", counts_zig); + try std.testing.expectEqualStrings( + \\ 2 t Counts = struct + \\11 t Mode = enum { fast, slow } + \\ 6 f Counts.add (c: *Counts, text: []const u8) void + \\13 f count (text: []const u8) Counts + \\ 3 m Counts.lines : usize = 0 + \\ 4 m Counts.words : usize = 0 + \\11 m Mode.fast + \\11 m Mode.slow + \\ 1 n std = @import("std") + \\ 5 c Counts.zero : Counts = .{} + \\12 v hits : u32 = 0 + \\16 · "count.add" + \\ + , try rowLines(p, a)); + // The qualifier dim, `Counts.`; a name holding a `.` none of it. + try std.testing.expectEqual(@as(u16, "Counts.".len), (try rowAt(p, live(p).?, a, 4)).faint); + try std.testing.expectEqual(@as(u16, 0), (try rowAt(p, live(p).?, a, 11)).faint); + // Drawn: `m Counts.lines : usize = 0` (not the cursor's row). + const pane = p.panes[p.paneBySerial(live(p).?.landing).?].?; + _ = try p.render(a); + const layer = &p.surface.tag_layers[pardes.BAND_LAYER]; + const roles = &p.chromeTheme().roles; + const inks = roles.on(if (Trail.reading(p, pane)) .reading_focused else .focused); + var found = false; + for (0..layer.rows) |y| { + const cells = layer.cells[y * layer.cols ..][0..layer.cols]; + var text: std.ArrayList(u8) = .empty; + var at: std.ArrayList(usize) = .empty; + for (cells, 0..) |c, x| { + try at.append(a, text.items.len); + try text.appendSlice(a, c.grapheme()); + _ = x; + } + const from = std.mem.indexOf(u8, text.items, "m Counts.lines") orelse continue; + var x: usize = 0; + while (at.items[x] < from) x += 1; + try std.testing.expectEqual(pardes.Color{ .rgb = p.chrome().on(.focus).kind }, cells[x].style.fg); + try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[x + 2].style.fg); + try std.testing.expectEqual(pardes.Color{ .rgb = inks.text }, cells[x + 9].style.fg); + try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[x + 16].style.fg); + // Its line at the row's right end, dim. + const three = std.mem.lastIndexOfScalar(u8, text.items, '3').?; + var m: usize = 0; + while (at.items[m] < three) m += 1; + try std.testing.expect(m > x + 30); + try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cells[m].style.fg); + found = true; + } + try std.testing.expect(found); +} + +test "Symbols (UX DESIGN N3): typed, the rows stay grouped, scored within each group, and the cursor starts on the best match wherever its group puts it; the name alone is matched, never the signature" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + const pane = try openSymbols(p, "/w6/counts.zig", counts_zig); + for ("count") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + const rows = try rowLines(p, a); + try std.testing.expect(std.mem.startsWith(u8, rows, + \\ 2 t Counts = struct + \\13 f count (text: []const u8) Counts + \\ 6 f Counts.add (c: *Counts, text: []const u8) void + \\ 3 m Counts.lines : usize = 0 + \\ 4 m Counts.words : usize = 0 + \\ + )); + // `count` matched best: the cursor on it, not on the first row, and + // the count says where it is. + const s = &p.view().tag_state; + try std.testing.expectEqual(@as(u16, 1), s.rows.at); + const h = (try head(p, a, p.panes[p.paneBySerial(live(p).?.landing).?].?)).?; + try std.testing.expect(std.mem.indexOf(u8, h.text, "2/7") != null); + // Enter lands on its line. + _ = pane; + // `u8` is in signatures only: nothing matches. + for (0..5) |_| p.update(.{ .key = .{ .cp = pardes.Key.backspace } }); + for ("u8") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?)); +} + +test "Symbols (UX DESIGN N): a C++ file's rows by its kind table, members named in their class and namespace, a function's locals none" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try openSymbols(p, "/w6/parser.cc", + \\#define LIMIT 4 + \\namespace torque { + \\class Parser : public Base { + \\ public: + \\ Parser(); + \\ int Parse(int depth) const { return depth; } + \\ int depth_; + \\}; + \\enum class Kind { kA, kB }; + \\int Parser::Run(int n) { int local = n; return local; } + \\static int counter = 0; + \\const int limit = 4; + \\using Alias = int; + \\} + \\ + ); + try std.testing.expectEqualStrings( + \\ 3 t torque.Parser : public Base + \\ 9 t torque.Kind + \\13 t torque.Alias = int + \\ 5 f torque.Parser.Parser () + \\ 6 f torque.Parser.Parse (int depth) const + \\10 f torque.Parser::Run (int n) + \\ 7 m torque.Parser.depth_ + \\ 9 m torque.Kind.kA + \\ 9 m torque.Kind.kB + \\ 1 · LIMIT 4 + \\ 2 n torque + \\11 v torque.counter = 0 + \\12 c torque.limit = 4 + \\ + , try rowLines(p, frame.allocator())); +} + +test "Symbols: every row is ordinary text: no header rows, the cursor steps onto each in turn, the band shows each row's text, and C-q keeps them in a +Search with the mark a word" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); + defer p.deinit(); + p.settings.jumps = .walk; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + _ = try openSymbols(p, "/w6/counts.zig", counts_zig); + const pk = live(p).?; + const n = count(p, pk); + try std.testing.expectEqual(@as(usize, 12), n); + const s = &p.view().tag_state; + for (0..n) |i| { + try std.testing.expectEqual(@as(u16, @intCast(i)), s.rows.at); + const r = try rowAt(p, pk, a, i); + const host = p.paneBySerial(pk.landing).?; + const band = (try Band.of(p, a, p.panes[host].?, host)).?; + var shown = false; + for (0..band.height) |y| { + const ln = try band.line(a, p.settings.tab, @intCast(y)); + shown = shown or std.mem.indexOf(u8, ln.text, r.text) != null; + } + try std.testing.expect(shown); + p.update(.{ .key = .{ .cp = pardes.Key.down } }); + } + p.update(.{ .key = .{ .cp = 'q', .ctrl = true } }); + var kept: ?[]const u8 = null; + for (p.panes) |slot| if (slot) |tp| if (tp.file) |f| if (std.mem.startsWith(u8, f.content, "Symbols ")) { + kept = f.content; + }; + try std.testing.expect(std.mem.indexOf(u8, kept.?, "\ncounts.zig:3 m Counts.lines : usize = 0\n") != null); + try std.testing.expect(std.mem.indexOf(u8, kept.?, "\ncounts.zig:2 t Counts = struct\n") != null); +} + +test "Find and Grep search the work tree (W8): from a pane deep in a repo Find lists the files from its root and `sub/name` narrows it, a leading directory narrows Grep, and outside a repo they search the pane's directory" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + p.settings.jumps = .walk; + p.stream.engine = .walk; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + for ([_][]const u8{ "src/deep", "sub", "other" }) |d| try tmp.dir.createDirPath(std.testing.io, d); + const deep = try testFile(p, &tmp, "src/deep/x.txt", "deep\n"); + defer p.gpa.free(deep); + for ([_][2][]const u8{ .{ "sub/name.txt", "needle one\n" }, .{ "other/name.txt", "needle two\n" } }) |f| p.gpa.free(try testFile(p, &tmp, f[0], f[1])); + const root = std.Io.Dir.path.dirname(std.Io.Dir.path.dirname(std.Io.Dir.path.dirname(deep).?).?).?; + _ = try p.setTestFile("held\n"); + const asker = p.view().active; + Trail.keep(p.panes[asker].?); + p.gpa.free(p.panes[asker].?.file.?.path); + p.panes[asker].?.file.?.path = try p.gpa.dupe(u8, deep); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + // Find from src/deep: the root's files, by their paths from it. + open(p, asker, .find, "", "", ""); + var pk = live(p).?; + try std.testing.expectEqualStrings(root, pk.dir.slice()); + settle(p); + try std.testing.expectEqual(@as(usize, 3), count(p, pk)); + for ("sub/name") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + settle(p); + try std.testing.expectEqual(@as(usize, 1), count(p, pk)); + try std.testing.expectEqualStrings("sub/name.txt", (try rowAt(p, pk, a, 0)).text); + p.update(.{ .key = .{ .cp = Key.escape } }); + // Grep: the whole tree, then `sub needle` in sub/ alone, its row's + // path from the root, landing on the file there. + open(p, asker, .grep, "", "", ""); + pk = live(p).?; + for ("needle") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + // (Its typing paused: the search starts.) + p.clock.now_ns = p.stream.due_ns.?; + settle(p); + try std.testing.expectEqual(@as(usize, 2), count(p, pk)); + p.update(.{ .key = .{ .cp = Key.escape } }); + open(p, asker, .grep, "", "", ""); + pk = live(p).?; + for ("sub needle") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + // (Its typing paused: the search starts.) + p.clock.now_ns = p.stream.due_ns.?; + settle(p); + try std.testing.expectEqual(@as(usize, 1), count(p, pk)); + const row = try rowAt(p, pk, a, 0); + try std.testing.expect(std.mem.startsWith(u8, row.text, "sub/name.txt:1 needle one")); + try std.testing.expectEqualStrings(try std.Io.Dir.path.join(a, &.{ root, "sub/name.txt" }), row.target.place.path); + p.update(.{ .key = .{ .cp = Key.escape } }); + // Outside a repo (`/`, the test text's directory, holds no .jj nor + // .git): the pane's directory, as before. + p.gpa.free(p.panes[asker].?.file.?.path); + p.panes[asker].?.file.?.path = try p.gpa.dupe(u8, "/held.txt"); + open(p, asker, .find, "", "", ""); + try std.testing.expectEqualStrings("/", live(p).?.dir.slice()); + p.update(.{ .key = .{ .cp = Key.escape } }); +} |
