//! A picker (pick-ui SPEC.md §5, direction E): a list of places, panes or //! names hung under the tag of the pane that asked, which keeps the //! keyboard (UX DESIGN O1). Its query is typed in the head's field //! (TagState.field), its rows hang in the band under it (Band.zig) eleven //! at a time around the cursor, and the body of the pane its Enter lands in //! is the preview: the current row's file at its line, its own text set //! aside meanwhile and put back when the picker rolls up. That pane is the //! asking one when it reads or is untouched, else its reader, else free //! space, else one made under it for the picker and taken away by Esc. //! //! The rows are Query.zig's producers', re-presented: names scored by //! Names.zig a frame's count at a time (Find's listing from the disk //! engine's worker, Recent, Panes, the asking text's declarations, the //! rows a language server answered, the jump list), Grep's lines from the //! disk engine's worker (Stream.zig: its pause, its cap). A frame makes //! only the rows it shows, in its arena. //! //! A picker is the session's, named by a serial drawn from the panes' //! counter (`id`), so the disk engine's `target` names it as it names a //! pane; one is live in a view's tag (TagState.pick), and the last //! `max_lists` are kept after they roll up. const Pick = @This(); const std = @import("std"); const pardes = @import("root.zig"); const config = @import("config.zig"); const layout = @import("layout.zig"); const look = @import("look.zig"); const panes = @import("panes.zig"); const filesystem = @import("fs.zig"); const exec = @import("exec.zig"); const bindings = @import("bindings.zig"); const Kind = @import("Kind.zig"); const Names = @import("Names.zig"); const Stream = @import("Stream.zig"); const Trail = @import("Trail.zig"); const TagState = @import("TagState.zig"); const Band = @import("Band.zig"); const Places = @import("Places.zig"); const colors = @import("colors.zig"); const Surface = @import("surface.zig").Surface; const Cell = @import("surface.zig").Cell; const Query = panes.Query; const File = panes.File; const Output = panes.Output; const Pardes = pardes.Pardes; const Pane = panes.Pane; const Key = pardes.Key; /// What a picker lists (SPEC §5.1, the sources pardes has): the files /// under the asking pane's directory, the lines of them holding the /// query, the files opened lately, the panes, the asking text's /// declarations, the lines holding the query in every open pane (All, its /// places in each), the jump list, rows handed over (a language server's /// 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), 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 /// those keys: a group's. const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 }).init(.{ .find = .{ .word = "Find", .keys = "f" }, .grep = .{ .word = "Grep", .keys = "f" }, .recent = .{ .word = "Recent", .keys = "f" }, .panes = .{ .word = "Panes", .keys = "b" }, .symbols = .{ .word = "Symbols", .keys = "s" }, .all = .{ .word = "All", .keys = "" }, .jumplist = .{ .word = "Jumplist", .keys = "j" }, .list = .{ .word = "List", .keys = "l" }, .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, 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; pub const replica = .{ .len = .{.{ "refined", "nrefined" }} }; /// Its serial: the disk engine's target, a list word's index. id: u32, source: Source, /// Its word, `Find`, or a list's own (`Refs`). word: Kind.Buf(24) = .{}, /// The leader keys under which its builtin is, drawn as key cells. keys: Kind.Buf(4) = .{}, /// Where Find and Grep look; what the rows' paths are relative to. dir: Kind.Buf(4096) = .{}, /// Asked by Root (`SPC f F`, `SPC f G`): `dir` is the project's root above /// the asking pane's, and its head and list word say `root`. root: bool = false, /// The pane that asked, under whose tag it hangs, and the one its Enter /// lands in, whose body previews, by serial. owner: u32 = 0, landing: u32 = 0, /// The landing pane was made for it: Esc takes it away. made: bool = false, /// Its band's rows at most: 40 % of its asking pane's rows at open (UX D6), /// fixed: the layout that borrows the host's body from its column reads /// it, and a pane laid out again changes it no more than typing does. cap: u16 = 0, /// Unrolled in a view's tag now. unrolled: bool = false, /// The most rows its list has had since it unrolled, eleven at most: its /// band grows with a list whose rows come later and never shrinks while it /// is up (bandRows, UX D6). tall: u8 = 0, names: Names = .{}, /// A Grep's lines, as the disk engine sends them (Query.take). found: std.ArrayList(Query.Found) = .empty, found_bytes: std.ArrayList(u8) = .empty, /// A list's rows, as they were handed over (`path:line:col text`); code /// actions' each followed by its edit's records (lsp_client actionEdits). rows: []u8 = &.{}, /// The revision of the asking text its actions' edits are of. revision: u32 = 0, /// The query and the cursor as it rolled up (live, they are its view's /// field and cursor). query: Kind.Buf(256) = .{}, at: u32 = 0, /// The landing pane's own text while its body previews (a reading pane: /// put back when the picker rolls up), and its caret and top then (put /// back too when it previewed its own file, with nothing set aside). aside: ?File.State = null, aside_row: i32 = 0, aside_col: i32 = 0, aside_top: usize = 0, /// What the row the preview shows is (`idOf`; `no_row`: none yet): asked /// again on the frame after the cursor moves to another, never on the key /// that moved it, and on the frame a row first comes under it. shown: u32 = no_row, /// A place shown in its landing pane's body since it unrolled: the band /// takes its rows from that body (`previewing`). previewed: bool = false, /// The preview on (M-p). previews: bool = true, /// Marked rows (Tab), by what each is (`idOf`), in order. marks: std.ArrayList(u32) = .empty, /// The queries refined from (C-SPC), each with the names it listed then: /// Backspace on an empty field goes back to them. 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), 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 /// path in `queue_bytes`, its line and column. 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 }; const Refined = struct { query: Kind.Buf(64) = .{}, names: Names = .{} }; const no_row = std.math.maxInt(u32); pub fn deinit(pk: *Pick, gpa: std.mem.Allocator) void { for (pk.refined[0..pk.nrefined]) |*r| r.names.deinit(gpa); pk.marks.deinit(gpa); pk.queue.deinit(gpa); pk.queue_bytes.deinit(gpa); pk.names.deinit(gpa); pk.found.deinit(gpa); pk.found_bytes.deinit(gpa); gpa.free(pk.rows); } /// 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, 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; } /// Picker `id`, kept or live. pub fn byId(p: *const Pardes, id: u32) ?*Pick { if (id == 0) return null; for (p.picks) |slot| if (slot) |pk| if (pk.id == id) return pk; return null; } /// The picker live in the live view's tag. pub fn live(p: *const Pardes) ?*Pick { const s = &p.view().tag_state; if (s.kind != .pick) return null; const pk = byId(p, s.pick) orelse return null; return if (pk.unrolled) pk else null; } /// Whether pane `id`'s body is the live picker's preview: a place shown in /// it. Its band then takes its rows from the body, which starts under the /// band (Pardes.sync), as a file's first lines could not be put under it /// otherwise (UX DESIGN I1's "a picker's landing line at a third below /// the band" for Find's line 1: W1's reading); before that, and at rest /// again, the pane's own text stays where it was under the band. Code /// actions' body is their preview from the first, their edit's ghost lines /// in it (UX DESIGN I1: "a picker and code actions (whose body is the /// preview) keep D6"): under the head and the band, never under them. pub fn previewing(p: *const Pardes, id: usize) bool { const pk = live(p) orelse return false; const pane = p.panes[id] orelse return false; return (pk.previewed or pk.source == .actions) and pane.serial == pk.landing; } /// Whether pane `id` shows the live picker's preview, being its landing /// pane, for the layout: a body of 60 % kept under what is above it (UX /// D6, DESIGN O1), the head and the band among that when it asked too. /// Panes and Themes preview in no pane. pub fn previewPane(p: *const Pardes, id: usize) bool { const pk = live(p) orelse return false; const pane = p.panes[id] orelse return false; return pane.serial == pk.landing and pk.source != .panes and pk.source != .themes; } /// The live picker whose rows pane `pane`'s body previews, it being its /// landing pane: what its tag names in place of the preview /// (tagline.named, UX DESIGN M3); none for a themes or actions picker, /// whose landing is the asking pane's own text. pub fn landingOf(p: *const Pardes, pane: *const Pane) ?*const Pick { const pk = live(p) orelse return null; if (pk.landing != pane.serial or pk.source == .themes or pk.source == .actions) return null; return pk; } /// A picker of `source` asked from pane `from`, hung under its tag (UX /// DESIGN O1), its field `query`. `rows` are a list's (`source` `list`, /// titled `word`). 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); // Root's (`SPC f F`): from the project's root above the asking pane's. pk.root = p.exec_root; pk.dir.set(if (pk.root) 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); pk.cap = p.view().rects[from].h * 2 / 5; hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "pick", err); unroll(p, pk, query); start(p, pk); filter(p, pk); // The themes: the cursor on the one worn (their order, the field empty). 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. Root's words run there (Pardes.execDir, `open`). pub 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 picker's or absolute, then a blank, narrows it to that /// directory (`src/torque Macro`), the rest the pattern; else all of it /// from the picker's. 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; // 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 pk.source != .lists and (oldest == null or rank(pk) < rank(p.picks[oldest.?].?))) { oldest = i; }; const i = oldest orelse return error.NoPickerSlots; p.picks[i].?.deinit(p.gpa); p.gpa.destroy(p.picks[i].?); p.picks[i] = null; slot = i; } const pk = try p.gpa.create(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`, which keeps the keyboard and hangs /// its head and band under its tag (UX DESIGN O1). The pane it lands in, /// whose body previews: `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 and is given back as it was on Esc; /// else a pane made where its reader would go, empty until the preview /// fills it. A source with nothing to preview makes no pane and sets /// nothing aside: Panes (a row is a pane on the screen), Themes (the whole /// window wears the row) and code actions (their edit in the asking text). fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void { defer p.view().active = from; const asker = p.panes[from].?; pk.owner = asker.serial; pk.landing = asker.serial; pk.made = false; if (pk.source == .panes or pk.source == .themes or pk.source == .actions) return; var reader = if (Trail.reading(p, asker)) from else Trail.readerOf(p, asker); if (reader == null) if (layout.freeSpace(p, from, .reader)) |free| if (free == .pane) { reader = free.pane; }; pk.landing = p.panes[reader orelse try landingFor(p, from)].?.serial; pk.made = reader == null; } /// A pane made for a picker where pane `from`'s reader goes: under it, or /// an empty column (layout.freeSpace). fn landingFor(p: *Pardes, from: usize) !usize { const asker = p.panes[from].?; const free = p.freeSlot() orelse return error.NoPaneSlots; const content = try p.gpa.dupe(u8, ""); errdefer p.gpa.free(content); _ = try Output.open(p, free, Pardes.paneDir(asker), .preview, "", content); layout.placeNew(p, from, from, free, .reader); layout.compute(p); return free; } /// Picker `pk` live in the live view's tag: hung under its asking pane's /// tag (UX DESIGN O1), its field `query`, the cursor where it was. fn unroll(p: *Pardes, pk: *Pick, query: []const u8) void { const v = p.view(); const s = &v.tag_state; s.kind = .pick; s.pick = pk.id; s.host = pk.owner; s.field.set(query); s.rows = .{ .at = @intCast(@min(pk.at, std.math.maxInt(u16))) }; pk.unrolled = true; pk.tall = 0; pk.shown = no_row; pk.previewed = false; // The whole window previews a theme. if (pk.source == .themes) s.previewing = .full; if (p.paneBySerial(pk.landing)) |id| { const pane = p.panes[id].?; pk.aside_row = pane.body.cur_row; pk.aside_col = pane.body.cur_col; pk.aside_top = if (pane.file) |f| f.scroll else 0; } } /// Its source begun: the names gathered, a listing started. fn start(p: *Pardes, pk: *Pick) void { pk.names.reset(); pk.found.clearRetainingCapacity(); pk.found_bytes.clearRetainingCapacity(); const dir = pk.dir.slice(); switch (pk.source) { .find => { Stream.query(p, pk.id, .files, "", dir, .now) catch |err| return p.reportError(.at(p.view().active), "pick", err); if (p.fs.serving) Stream.step(p); }, .grep, .all => {}, .recent => Query.gather(p, &pk.names, .recent, dir, null, null), .panes => Query.gather(p, &pk.names, .panes, dir, null, null), .symbols => Query.gather(p, &pk.names, .symbols, dir, null, p.paneBySerial(pk.owner)), .jumplist => { var out: std.Io.Writer.Allocating = .init(p.gpa); defer out.deinit(); Output.jumpsText(p, &out.writer) catch return; 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(); Output.messagesText(p, &out.writer) catch return; addRows(p, pk, out.written()); }, .themes => for (pardes.colors.themes, 0..) |t, i| { pk.names.add(p.gpa, t.name, 0, t.name.len, 0, @intCast(i)) catch return; }, // Each action by its title, its digit before it (the first nine, // which `1`-`9` apply), the title what the query matches. .actions => { var lines = std.mem.splitScalar(u8, pk.rows, '\n'); var i: u32 = 0; while (lines.next()) |ln| { if (ln.len == 0 or ln[0] == '@') continue; const title = std.mem.trimStart(u8, ln[Output.location(ln).end..], " "); var buf: [2 + 512]u8 = undefined; const cut = title[0..@min(title.len, 512)]; const text = if (i < 9) std.fmt.bufPrint(&buf, "{d} {s}", .{ i + 1, cut }) catch unreachable else cut; // 2 + 512 fit pk.names.add(p.gpa, text, text.len - cut.len, cut.len, 0, i) catch return; i += 1; } }, } } /// Rows of text as names, a row each, matched whole. fn addRows(p: *Pardes, pk: *Pick, text: []const u8) void { var lines = std.mem.splitScalar(u8, text, '\n'); var i: u32 = 0; while (lines.next()) |ln| : (i += 1) { if (ln.len == 0) continue; pk.names.add(p.gpa, ln, 0, ln.len, 0, i) catch return; } } /// Its rows are names scored by the query: any source's but a live Grep's /// or All's, and theirs once refined. fn fuzzy(pk: *const Pick) bool { return pk.nrefined > 0 or (pk.source != .grep and pk.source != .all); } /// The field typed: the rows again for it. A Grep's lines are the disk /// engine's, once the typing pauses; the names are scored a frame's count /// at a time from here. 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)) { pk.names.typed(p.gpa, q); return toBest(p, pk); } if (pk.source == .grep) { pk.found.clearRetainingCapacity(); pk.found_bytes.clearRetainingCapacity(); 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; } { // All: each open text's places, found a frame's more at a time. for (p.panes) |slot| { const tp = slot orelse continue; if (!searchable(tp)) continue; if (q.len == 0) { if (tp.places.from == pk.id) tp.places.clear(p.gpa); } else tp.places.search(p, tp, .list, pk.id, q, false, null, false); } } } /// A pane whose text 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; } /// The panes All's places are in, in the order of their serials. fn allPanes(p: *const Pardes, pk: *const Pick, out: *[pardes.MAX_PANES]usize) []usize { var n: usize = 0; for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == pk.id and tp.places.shows(tp) and tp.places.hits.items.len > 0) { out[n] = i; n += 1; }; std.mem.sort(usize, out[0..n], p, struct { fn lt(pp: *const Pardes, a: usize, b: usize) bool { return pp.panes[a].?.serial < pp.panes[b].?.serial; } }.lt); return out[0..n]; } /// 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; // A Grep narrowed to a directory (grepScope): its rows' paths from the // picker's directory, 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; } /// Pane `serial`'s declarations came (Stream.receiveParse): a Symbols /// picker asked from it gathers them. pub fn declsArrived(p: *Pardes, serial: u32) void { for (p.picks) |slot| if (slot) |pk| if (pk.unrolled and pk.source == .symbols and pk.owner == serial and pk.names.cands.items.len == 0) { 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) { pk.tall = @intCast(@max(pk.tall, @min(have(p, pk), Band.Cursor.shown))); 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); }; } /// The rows a picker's source has: every name it scores (not what the /// query keeps), a Grep's lines and All's places for this query. fn have(p: *const Pardes, pk: *const Pick) usize { return if (fuzzy(pk)) pk.names.cands.items.len else count(p, pk); } /// The frames a live picker still owes: scoring, a preview (nextWake's). pub fn busy(p: *const Pardes) bool { for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { const at = p.view().tag_state.rows.at; if (pk.names.busy() or (pk.previews and at < count(p, pk) and pk.shown != idOf(pk, at))) return true; }; return false; } // ---- the rows ---- /// What the row under the cursor is of: a themes picker's theme, an /// actions picker's action. fn refAt(p: *const Pardes, pk: *const Pick) ?usize { const n = pk.names.hits.items.len; if (n == 0) return null; const at = @min(p.view().tag_state.rows.at, n - 1); return pk.names.cands.items[pk.names.hits.items[at].cand].ref; } /// The rows the list has now. pub fn count(p: *const Pardes, pk: *const Pick) usize { if (fuzzy(pk)) return pk.names.hits.items.len; switch (pk.source) { .grep => return pk.found.items.len, .all => { var order: [pardes.MAX_PANES]usize = undefined; var n: usize = 0; for (allPanes(p, pk, &order)) |i| n += p.panes[i].?.places.hits.items.len; return n; }, else => return pk.names.hits.items.len, } } /// What row `i` is, kept by a mark across a new query: a name's candidate, /// a line's place in its source. fn idOf(pk: *const Pick, i: usize) u32 { return if (fuzzy(pk)) pk.names.hits.items[i].cand else @intCast(i); } fn marked(pk: *const Pick, id: u32) ?usize { const at = std.sort.lowerBound(u32, pk.marks.items, id, struct { fn order(a: u32, b: u32) std.math.Order { return std.math.order(a, b); } }.order); return if (at < pk.marks.items.len and pk.marks.items[at] == id) at else null; } /// Where a row points: a place in a file, or a pane by its serial. const Target = union(enum) { none, place: struct { path: []const u8, at: look.Spot }, pane: u32 }; /// 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, 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) std.mem.Allocator.Error!Row { const dir = pk.dir.slice(); if (!fuzzy(pk) and pk.source == .all) { var order: [pardes.MAX_PANES]usize = undefined; var k = i; for (allPanes(p, pk, &order)) |id| { const tp = p.panes[id].?; const hits = tp.places.hits.items; if (k >= hits.len) { k -= hits.len; continue; } const f = &tp.file.?; const h = hits[k]; const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), h.start); const ls = File.lineStart(p.gpa, f, line); const le = std.mem.indexOfScalarPos(u8, f.content, h.start, '\n') orelse f.content.len; const whole = f.content[ls..le]; const lead = whole.len - std.mem.trimStart(u8, whole, " \t").len; const name = if (f.output == null) std.Io.Dir.path.basename(f.path) else ""; const pre = try std.fmt.allocPrint(arena, config.pane_addr ++ "{d} {s}:{d}", .{ tp.serial, name, line + 1 }); const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, whole[lead..@min(whole.len, lead + 240)] }); var marks: std.ArrayList(u16) = .empty; var c = h.start - ls; while (c < h.end - ls and c >= lead and pre.len + 1 + c - lead < text.len) : (c += 1) try marks.append(arena, @intCast(pre.len + 1 + c - lead)); const target: Target = if (f.output == null) .{ .place = .{ .path = f.path, .at = .{ .line = line + 1, .col = h.start - ls + 1 } } } else .{ .pane = tp.serial }; return .{ .text = text, .pre = @intCast(pre.len), .marks = marks.items, .target = target }; } return .{ .text = "" }; } if (!fuzzy(pk)) { const fd = pk.found.items[i]; const name = pk.found_bytes.items[fd.path..][0..fd.path_len]; const code = pk.found_bytes.items[fd.code..][0..fd.code_len]; const lead = code.len - std.mem.trimStart(u8, code, " \t").len; const pre = try std.fmt.allocPrint(arena, "{f}:{d}", .{ look.quoted(name), fd.line }); const text = try std.fmt.allocPrint(arena, "{s} {s}", .{ pre, code[lead..] }); 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)); // (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; var nmarks: usize = 0; const text = pk.names.row(i, &marks, &nmarks); const cand = pk.names.cands.items[pk.names.hits.items[i].cand]; var row: Row = .{ .text = text, .marks = try arena.dupe(u16, marks[0..nmarks]) }; switch (pk.source) { .find => { 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); // 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 => { 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"; }, // An action: its digit a key; its place the first line its edit // changes, which the body is moved to while it is previewed. .actions => { row.key = @intFromBool(cand.ref < 9); const act = action(pk, cand.ref) orelse return row; // One Enter cannot apply (apply's refusals): dim, saying why // (UX E5 12). if (act.records.len == 0 or std.mem.eql(u8, act.records, "@elsewhere\n")) { row.dim = true; row.meta = if (act.records.len == 0) "command" else "other files"; return row; } const owner = p.panes[p.paneBySerial(pk.landing) orelse return row].?; // With the `Changes` layer's lines shown the body stays where it is. const f = if (owner.file) |*file| file else return row; if (f.layer.lines.len > 0 or f.revision != pk.revision) return row; const edits = pardes.lsp.Ask.parseLspEdits(arena, act.records, null) orelse return row; if (edits[0].start > f.content.len) return row; const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), edits[0].start); row.target = .{ .place = .{ .path = f.path, .at = .{ .line = line + 1 } } }; }, .recent, .jumplist, .list, .grep, .all => { const t = look.parsePathLine(text); row.pre = @intCast(t.end); if (t.path.len == 0) return row; const path = if (t.path[0] == '/' or t.path[0] == '@') t.path else try std.Io.Dir.path.join(arena, &.{ dir, t.path }); row.target = .{ .place = .{ .path = path, .at = t.at } }; }, // A message (`✗ 3: words`, Output.messagesText): its cause's pane // while it is open; a place under it (indented): that place. .messages => { const lead = text.len - std.mem.trimStart(u8, text, " ").len; if (lead == 0) { const sp = std.mem.indexOfScalar(u8, text, ' ') orelse return row; const digits = text[sp + 1 ..]; const n = std.mem.indexOfNone(u8, digits, "0123456789") orelse return row; if (n == 0 or digits[n] != ':') return row; const serial = std.fmt.parseInt(u32, digits[0..n], 10) catch return row; if (p.paneBySerial(serial) != null) row.target = .{ .pane = serial }; return row; } const t = look.parsePathLine(text[lead..]); row.pre = @intCast(lead + t.end); if (t.path.len == 0) return row; row.target = .{ .place = .{ .path = t.path, .at = t.at } }; }, } return row; } // ---- the tag ---- /// The head under the asking pane's tag (SPEC §5.3, UX DESIGN M2, O1): the /// key cells, the source's word, the query, the count `cursor/total` and /// `•marked`, and one hint, `M-l acts`, the key to the acts (UX DESIGN O4: /// no row of acts and sources; each source has its own key, M-h switches /// keeping the query). pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { const pk = live(p) orelse return null; const s = &p.view().tag_state; var b = try TagState.Builder.of(p, arena, pane); 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()); if (pk.root) try text.appendSlice(arena, " root"); try text.append(arena, ' '); for (pk.refined[0..pk.nrefined]) |r| try text.print(arena, "{s} | ", .{r.query.slice()}); if (pk.spine == .edit) try text.print(arena, "{s} | Edit ", .{pk.query.slice()}); const caret: u32 = @intCast(text.items.len + s.field.caret); try text.appendSlice(arena, s.field.text()); // The count at the row's right end (UX D3): `cursor/matches`, `0` with // none, ` •M` marked. const counted = text.items.len; const n = count(p, pk); 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, code actions and Lists have no acts: no hint. const hints = text.items.len; if (pk.source != .themes and pk.source != .actions and pk.source != .lists) try b.styled("M-l acts", .dim); try b.right(counted, hints); var h = b.done(); h.caret = caret; return h; } /// The band's rows (UX D6, DESIGN O4): as many as the list will show, from /// what the source has (not what the query keeps: typing never moves the /// body) and the most it has had (`tall`): a list known at open exactly its /// rows, one whose rows come later (Find, Grep, All, Symbols) three at /// least, growing as they come; eleven at most, and its `cap` at most (the /// asking pane's 40 % at open: the layout asks this while it lays the /// column out, when no pane has its rows yet). pub fn bandRows(p: *const Pardes) u16 { const pk = live(p) orelse return 0; const later: usize = switch (pk.source) { .find, .grep, .all, .symbols => 3, else => 1, }; const rows: usize = @max(1, @min(Band.Cursor.shown, @max(later, pk.tall, have(p, pk)), pk.cap)); // Its second step's rows too: the sources, the acts and what they act on. return @intCast(switch (pk.spine) { .sources => @max(rows, spine_rows.len), .acts => acts: { var n: usize = 1; 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, }); } /// The band's steps: the rows around the cursor. 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 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 }; out[1] = .{ .rows = rows }; } if (n == 0) { const none = try arena.alloc(Band.Row, 1); none[0] = .{ .text = if (pk.names.busy() or p.stream.busyFor(pk.id)) "⋯" else if (s.field.len == 0 and pk.source == .grep) "type to search" else "nothing matches", .dim = true }; out[0] = .{ .rows = none }; return out; } const w = s.rows.window(@intCast(@min(n, std.math.maxInt(u16)))); 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, .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 // before it (UX E7 2b: the old +Search's column). Bounded by the rows // shown. if (pk.source == .grep or pk.source == .all or pk.source == .list) { var widest: usize = 0; for (rows) |row| if (row.pre > 0 and row.pre < row.text.len) { widest = @max(widest, File.displayWidth(p.settings.tab, row.text[0 .. std.mem.indexOfScalarPos(u8, row.text, row.pre, ' ') orelse row.text.len])); }; for (rows) |*row| if (row.pre > 0 and row.pre < row.text.len) { // The place up to its blank: a column (`:3:1`) and the `:` a // compiler's `path:line:col: words` puts after it are its. const end = std.mem.indexOfScalarPos(u8, row.text, row.pre, ' ') orelse row.text.len; row.quiet = .{ 0, @intCast(end) }; const pad = widest - File.displayWidth(p.settings.tab, row.text[0..end]); if (pad == 0) continue; const blanks = try arena.alloc(u8, pad); @memset(blanks, ' '); row.text = try std.mem.concat(arena, u8, &.{ row.text[0..end], blanks, row.text[end..] }); const marks = try arena.alloc(u16, row.marks.len); for (marks, row.marks) |*m, at| m.* = if (at >= end) at + @as(u16, @intCast(pad)) else at; row.marks = marks; }; } out[0] = .{ .rows = rows }; 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) and the byte in it that pane `pane`'s body lands the /// live picker's cursor row on, while it is that picker's landing pane /// previewing that row's file (UX D7: drawn on the hit ground, /// body_layer.zig); null else. The row's own place, where Enter lands /// (`land`) and `preview` put the caret: never the caret, which a click in /// the preview moves while the picker waits (UX DESIGN O2). pub fn landingLine(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ?struct { line: usize, col: usize } { const pk = live(p) orelse return null; // A theme or an action lands nowhere: the window wearing it, its // edit on the Changes grounds are their previews. if (!pk.previews or pk.landing != pane.serial or pk.source == .themes or pk.source == .actions) return null; const s = &p.view().tag_state; if (s.rows.at >= count(p, pk) or pk.shown != idOf(pk, s.rows.at)) return null; const row = rowAt(p, pk, arena, s.rows.at) catch return null; const place = switch (row.target) { .place => |t| t, else => return null, }; const f = if (pane.file) |*file| file else return null; if (!std.mem.eql(u8, f.path, place.path)) return null; // As `preview` and look.focusPaneLine put the caret: a place past the // file's end on its first line; past the `Changes` layer's lines. if (place.at.line == 0 or place.at.line > File.nlines(p.gpa, f)) return .{ .line = 0, .col = 0 }; const line = File.bufferRow(f, place.at.line - 1); return .{ .line = line, .col = @min(place.at.col -| 1, File.sourceLine(pane, @intCast(line)).len) }; } /// The notice row's sentence while a picker previews (UX D7), written to /// `w`: where Enter lands (`here`, or the owner's reader by its address, /// a word to Look at), that the body is the preview, and Shift-Enter's new /// pane; the address's bytes in what was written, or null with no picker /// 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 or pk.source == .lists or pk.source == .panes) return null; if (pk.landing == pk.owner) { w.writeAll("⏎ lands here") catch return null; } else { w.writeAll("⏎ lands in ") catch return null; } const lo = w.end; if (pk.landing != pk.owner) w.print("@p{d}", .{pk.owner}) catch return null; const hi = w.end; if (pk.landing != pk.owner) w.writeAll("'s reader") catch return null; w.writeAll(" · its text is the preview · S-⏎ a new pane") catch return null; return .{ lo, hi }; } /// 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. 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 // and a Grep's lines come frames after the field asked). if (!pk.previews or s.rows.at >= count(p, pk)) return; if (pk.shown == idOf(pk, s.rows.at)) return; pk.shown = idOf(pk, s.rows.at); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); const row = rowAt(p, pk, frame.allocator(), s.rows.at) catch return; const place = switch (row.target) { .place => |t| t, else => return, }; const id = p.paneBySerial(pk.landing) orelse return; const pane = p.panes[id].?; const f = if (pane.file) |*file| file else return; if (f.twin != 0) return; 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 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 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; }; 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.layOut(); } const keyboard = p.view().active; defer p.view().active = keyboard; look.clearNavigationSelection(p, pane); const pf = &pane.file.?; const at = place.at; if (at.line == 0 or at.line > File.nlines(p.gpa, pf)) { pf.scroll = 0; pf.scroll_row = 0; pane.body.cur_row = 0; pane.body.cur_col = 0; return; } 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) { 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. fn openText(p: *Pardes, path: []const u8) ?[]u8 { for (p.panes) |slot| { const tp = slot orelse continue; const tf = tp.file orelse continue; if (tf.output != null or !std.mem.eql(u8, tf.path, path)) continue; return p.gpa.dupe(u8, tf.content) catch null; } return null; } /// The landing pane as the picker found it: its own text back, or the /// pane made for the picker taken away; the places it lit put out. fn restore(p: *Pardes, pk: *Pick) void { if (pk.source == .themes) return pardes.colors.previewTheme(p, null); 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; } putBack(p, pk); } /// The landing pane's own text back in it, the preview's freed. 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. look.clearNavigationSelection(p, pane); pane.body.cur_row = pk.aside_row; pane.body.cur_col = pk.aside_col; if (pane.file != null) File.setTop(pane, .{ .line = pk.aside_top }); return; }; pk.aside = null; File.deinit(p, pane, &pane.file.?); pane.file = own; pane.body.cur_row = pk.aside_row; pane.body.cur_col = pk.aside_col; pane.body.vsel.active = false; p.layOut(); } /// The live picker rolled up (Esc, or the tag put to rest by anything): /// its query and cursor kept for its list word and Resume, every body as /// it was (TagState.toRest). 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); } /// Every picker freed, a live one's landing pane put back first (the /// session's end). pub fn deinitAll(p: *Pardes) void { for (&p.picks) |*slot| if (slot.*) |pk| { if (pk.unrolled) { pk.unrolled = false; if (pk.aside) |own| if (p.paneBySerial(pk.landing)) |id| { const pane = p.panes[id].?; File.deinit(p, pane, &pane.file.?); pane.file = own; pk.aside = null; }; } pk.deinit(p.gpa); p.gpa.destroy(pk); slot.* = null; }; } // ---- code actions ---- /// Action `index` of a code actions picker's rows: its title and its edit's /// records (the `@put` lines after its row, `@elsewhere` for an edit that /// reaches other files, none for a command's); null past the last. fn action(pk: *const Pick, index: usize) ?struct { title: []const u8, records: []const u8 } { var lines = std.mem.splitScalar(u8, pk.rows, '\n'); var n: usize = 0; while (lines.next()) |ln| { if (ln.len == 0 or ln[0] == '@') continue; if (n < index) { n += 1; continue; } const from = lines.index orelse pk.rows.len; var to = from; while (lines.peek()) |next| { if (next.len == 0 or next[0] != '@') break; _ = lines.next(); to = lines.index orelse pk.rows.len; } return .{ .title = std.mem.trimStart(u8, ln[Output.location(ln).end..], " "), .records = pk.rows[from..to] }; } return null; } /// Action `index` of the live actions picker applied to the text it was /// asked of as one undo step, the tag put to rest first (its caret back /// where it was, then moved with the edit); one with no edit here (a /// command's, or one reaching other files) said and not applied. fn apply(p: *Pardes, pk: *Pick, index: usize) void { const act = action(pk, index) orelse return; const id = p.paneBySerial(pk.landing) orelse return TagState.toRest(p); TagState.toRest(p); var said: Kind.Buf(256) = .{}; if (std.mem.eql(u8, act.records, "@elsewhere\n")) return p.reportFailure(id, said.print("Actions: {s}: its edit reaches other files, not applied", .{act.title})); if (act.records.len == 0) return p.reportFailure(id, said.print("Actions: {s}: no edit to apply", .{act.title})); if (!pardes.lsp.Ask.applyAction(p, p.panes[id].?, pk.revision, act.records)) return p.reportFailure(id, said.print("Actions: {s}: not applied, the text is not what it was asked of", .{act.title})); p.setMessage(.at(id), said.print("Actions: {s}", .{act.title})); } /// The live code actions picker's preview in its body (SPEC §5.1, the /// coordinator's R3): the edit of the action under the cursor, the lines it /// changes on the deleted ground and what they become after them as ghost /// rows on the added ground, the rows below pushed down and the last off /// the view. Drawn, never written; the rows shown alone. pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: pardes.Rect, body_h: u16) !void { const pk = live(p) orelse return; if (pk.source != .actions or !pk.previews or pk.landing != pane.serial) return; const f = if (pane.file) |*file| file else return; if (f.revision != pk.revision) return; const records = (action(pk, refAt(p, pk) orelse return) orelse return).records; const edits = pardes.lsp.Ask.parseLspEdits(arena, records, null) orelse return; const text = f.content; const index = try File.lineIndex(p.gpa, f); // The edits by the lines they touch: each run of them its old lines // [lo, hi) and their new text, which goes before line hi. const Group = struct { lo: usize, hi: usize, new: []const u8 }; var groups: std.ArrayList(Group) = .empty; var k: usize = 0; while (k < edits.len) { const begin = File.bufferOffset(f, edits[k].start, false); if (begin > text.len) return; const lo = Places.lineOf(index, begin); var new: std.ArrayList(u8) = .empty; try new.appendSlice(arena, text[index[lo]..begin]); var hi = lo; var at = begin; while (k < edits.len) : (k += 1) { const from = File.bufferOffset(f, edits[k].start, false); const to = File.bufferOffset(f, edits[k].end, edits[k].end > edits[k].start); if (from < at or to < from or to > text.len) return; if (from > begin and Places.lineOf(index, from) >= hi) break; try new.appendSlice(arena, text[at..from]); try new.appendSlice(arena, edits[k].text); at = to; const line = Places.lineOf(index, to); // Up to a line's start, from one or past its own text: that // line is not changed. hi = if (to == index[line] and (to > begin or begin == index[lo])) line else line + 1; } try new.appendSlice(arena, text[at..if (hi < index.len) index[hi] else text.len]); try groups.append(arena, .{ .lo = lo, .hi = hi, .new = new.items }); } const tab = p.settings.tab; const y0 = p.bodyTop(pane, r); const rows: usize = @min(body_h, s.rows -| y0); const first: usize = pane.context_rows; if (rows <= first) return; const w: usize = s.cols; const old = try arena.dupe(Cell, s.cells[(y0 + first) * w .. (y0 + rows) * w]); 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; var g: usize = 0; var vr: usize = first; while (vr < rows and out < rows) : (vr += 1) { const shown = pane.wrapAt(tab, @intCast(vr)).line; const line: usize = if (shown < 0) index.len else @intCast(shown); if (vr == first or pane.wrapAt(tab, @intCast(vr - 1)).line != shown) { while (g < groups.items.len and groups.items[g].hi < line) g += 1; while (g < groups.items.len and groups.items[g].hi == line) : (g += 1) { var news = std.mem.splitScalar(u8, std.mem.trimEnd(u8, groups.items[g].new, "\n"), '\n'); if (groups.items[g].new.len > 0) while (news.next()) |l| { 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 = 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, chrome.del.row, null); out += 1; } } // ---- keys ---- /// A key in the live picker (keys.zig tagStateKey, SPEC §5.4). Esc is /// the tag's: TagState.toRest rolls it up. pub fn key(p: *Pardes, k: Key) void { const pk = live(p) orelse return TagState.toRest(p); const s = &p.view().tag_state; const n: u16 = @intCast(@min(count(p, pk), std.math.maxInt(u16))); const plain = !k.ctrl and !k.alt; const ctrl = k.ctrl and !k.alt; const alt = k.alt and !k.ctrl; if (pk.spine == .sources) { pk.spine = .rows; for (spine_rows) |src| if (plain and k.cp == src.key) return switchTo(p, pk, src.source); 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 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); pardes.colors.setThemeIndex(p, at); return; } if (plain and k.cp == Key.enter) return apply(p, pk, refAt(p, pk) orelse return); if (pk.source == .actions and plain and s.field.len == 0 and k.cp >= '1' and k.cp <= '9') return apply(p, pk, k.cp - '1'); if (s.rows.key(k, n)) { pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown); return; } if (s.field.key(k)) filter(p, pk); return; } if (pk.spine == .edit) { if (plain and k.cp == Key.enter) return editRows(p, pk); if (plain and k.cp == Key.backspace and s.field.len == 0 or alt and k.cp == 'h') { s.field.set(pk.query.slice()); pk.spine = .rows; return; } _ = 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; return; } if (plain and k.cp == Key.enter) return land(p, if (k.shift) .below else .walk); if (ctrl and k.cp == 's') return land(p, .below); if (ctrl and k.cp == 'v') return land(p, .column); if (plain and k.cp == Key.tab) { if (n == 0) return; toggle(p, pk, idOf(pk, s.rows.at)); _ = s.rows.key(.{ .cp = if (k.shift) Key.up else Key.down }, n); return; } if (alt and k.cp == 'a') return markAll(p, pk); if (alt and k.cp == 'h') { pk.spine = .sources; return; } 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; if (!pk.previews) putBack(p, pk); return; } if (plain and k.cp == Key.backspace and s.field.len == 0) return back(p, pk); // A cursor gone past the rows sorted sorts as far (Names.reach). if (s.rows.key(k, n)) { if (fuzzy(pk)) pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown); return; } 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 }, .{ .key = 'g', .word = "Grep", .source = .grep }, .{ .key = 'r', .word = "Recent", .source = .recent }, .{ .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 }, }; /// The live picker's source another (`null`: Help over the binding tree), /// its query kept, its landing pane the same. fn switchTo(p: *Pardes, pk: *Pick, source: ?Source) void { const s = &p.view().tag_state; const to = source orelse { var query: Kind.Buf(256) = .{}; query.set(s.field.text()); TagState.toRest(p); TagState.openHelp(p, null, ""); 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); pk.nrefined = 0; pk.marks.clearRetainingCapacity(); const from_panes = pk.source == .panes; pk.source = to; pk.word.set(words.get(to).word); pk.keys.set(words.get(to).keys); // From Panes, which previews in no pane (hostIn), to a source that // does: its preview where it would have been had it opened as this one. if (from_panes and to != .panes) { var query: Kind.Buf(256) = .{}; query.set(s.field.text()); hostIn(p, pk, p.paneBySerial(pk.owner) orelse p.view().active) catch |err| return p.reportError(.at(p.view().active), "pick", err); unroll(p, pk, query.slice()); } start(p, pk); filter(p, pk); } fn toggle(p: *Pardes, pk: *Pick, id: u32) void { if (marked(pk, id)) |at| { _ = pk.marks.orderedRemove(at); return; } const at = std.sort.lowerBound(u32, pk.marks.items, id, struct { fn order(a: u32, b: u32) std.math.Order { return std.math.order(a, b); } }.order); pk.marks.insert(p.gpa, at, id) catch |err| p.reportError(.at(p.view().active), "pick", err); } /// Every row marked, or none when every one is. fn markAll(p: *Pardes, pk: *Pick) void { const n = count(p, pk); const all = pk.marks.items.len == n; pk.marks.clearRetainingCapacity(); if (all) return; pk.marks.ensureTotalCapacity(p.gpa, n) catch |err| return p.reportError(.at(p.view().active), "pick", err); for (0..n) |i| pk.marks.appendAssumeCapacity(idOf(pk, i)); std.mem.sort(u32, pk.marks.items, {}, std.sort.asc(u32)); } /// C-SPC: the rows the query keeps become the list, the query starts /// empty; a Grep's lines and All's become names to score from here. fn refine(p: *Pardes, pk: *Pick, drop: bool) void { const s = &p.view().tag_state; const q = std.mem.trim(u8, s.field.text(), " "); if (q.len == 0 and !drop or pk.nrefined == max_refine) return; // Dropped: the marked rows, or the current one. const current = if (count(p, pk) > 0) idOf(pk, s.rows.at) else std.math.maxInt(u32); var next: Names = .{}; if (fuzzy(pk)) { for (pk.names.hits.items) |h| { 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); defer arena.deinit(); for (0..count(p, pk)) |i| { if (drop and (if (pk.marks.items.len > 0) marked(pk, @intCast(i)) != null else i == current)) continue; _ = arena.reset(.retain_capacity); const row = rowAt(p, pk, arena.allocator(), i) catch break; const at = switch (row.target) { .place => |t| t, else => continue, }; const ln = std.fmt.allocPrint(arena.allocator(), "{s}:{d}:{d} {s}", .{ relative(at.path, pk.dir.slice()), at.at.line, at.at.col, row.text[@min(row.text.len, row.pre + 1)..] }) catch break; next.add(p.gpa, ln, 0, ln.len, 0, @intCast(i)) catch break; } 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); } pk.refined[pk.nrefined] = .{ .names = pk.names }; pk.refined[pk.nrefined].query.set(q); pk.nrefined += 1; pk.names = next; pk.marks.clearRetainingCapacity(); s.field.clear(); filter(p, pk); } 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; } /// Backspace on an empty field: the last refinement undone, its query /// back; else back a step, to the leader's level the picker was run from. fn back(p: *Pardes, pk: *Pick) void { const v = p.view(); const s = &v.tag_state; if (pk.nrefined > 0) { pk.nrefined -= 1; const r = &pk.refined[pk.nrefined]; pk.names.deinit(p.gpa); pk.names = r.names; pk.marks.clearRetainingCapacity(); s.field.set(r.query.slice()); s.rows.at = 0; pk.shown = no_row; // A live source's own rows again: All's places are found anew. 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; v.prefix = .leader; @memcpy(v.leader_keys[0..keys.len], keys.slice()); v.leader_n = @intCast(keys.len); s.root = .leader; 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. fn keep(p: *Pardes, pk: *Pick) void { const s = &p.view().tag_state; const from = p.paneBySerial(pk.owner) orelse p.view().active; // The history kept is the +Messages (SPEC §10.4). if (pk.source == .messages) { TagState.toRest(p); return Output.openMessages(p, from) catch |err| p.reportError(.at(from), "messages", err); } var out: std.Io.Writer.Allocating = .init(p.gpa); defer out.deinit(); var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); out.writer.print("{s} ", .{pk.word.slice()}) catch return; for (pk.refined[0..pk.nrefined]) |r| out.writer.print("{s} | ", .{r.query.slice()}) catch return; out.writer.print("{s}\n", .{s.field.text()}) catch return; if (fuzzy(pk)) pk.names.reachTo(Query.max_rows); var kept: usize = 0; for (0..count(p, pk)) |i| { if (kept == Query.max_rows) break; if (pk.marks.items.len > 0 and marked(pk, idOf(pk, i)) == null) continue; _ = arena.reset(.retain_capacity); 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, row.text }) catch break else out.writer.print("{s}\n", .{row.text}) catch break, else => out.writer.print("{s}\n", .{row.text}) catch break, } kept += 1; } TagState.toRest(p); const free = p.freeSlot() orelse return p.reportError(.at(from), "pick", error.NoPaneSlots); const content = out.toOwnedSlice() catch |err| return p.reportError(.at(from), "pick", err); _ = Output.open(p, free, pk.dir.slice(), .search, "", content) catch |err| { p.gpa.free(content); return p.reportError(.at(from), "pick", err); }; layout.placeNew(p, from, from, free, .doc); } /// How Enter lands: a walk step, a new pane below, a new column; `queue`: /// a walk step to the first, the others queued for C-i (the act Walk). const How = enum { walk, below, column, queue }; /// Enter: the current row, or the marked ones, looked at from the asking /// pane (look.open, the walk's way: a reading pane steps, a held one's /// reader does), the first as `how` says, the others each in a pane below. /// The list rolls into the landing pane's trail as its word (item 4). From /// an untouched pane S-Enter and C-v are Enter: it is the free space a new /// pane would take (UX J1). fn land(p: *Pardes, wanted: How) void { const pk = live(p) orelse return; var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); 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(); pk.queue_at = 0; if (wanted == .queue) for (picked[1..]) |t| switch (t) { .place => |at| { const q: Queued = .{ .path = @intCast(pk.queue_bytes.items.len), .len = @intCast(@min(at.path.len, std.math.maxInt(u16))), .line = std.math.lossyCast(u32, at.at.line), .col = std.math.lossyCast(u32, at.at.col) }; pk.queue_bytes.appendSlice(p.gpa, at.path[0..q.len]) catch break; pk.queue.append(p.gpa, q) catch break; }, else => {}, }; TagState.toRest(p); const v = p.view(); const owner = p.paneBySerial(pk.owner) orelse v.active; const how: How = if ((wanted == .below or wanted == .column) and Trail.untouched(p, p.panes[owner].?)) .walk else wanted; // A step from the pane it lands in when that reads (its owner's reader // or itself), else from its owner, whose reader the place opens as: // where the pane made for the picker was, or in the untouched pane it // previewed in (UX J1), given back now. const landing = p.paneBySerial(pk.landing) orelse owner; const from = if ((how == .walk or how == .queue) and Trail.reading(p, p.panes[landing].?)) landing else owner; v.active = from; v.jumps.force = true; for (picked, 0..) |t, k| switch (t) { .none => {}, .pane => |serial| if (p.paneBySerial(serial)) |tid| { v.active = tid; if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); } else { _ = 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, word), } } else if (k == 0 and how == .column) { // A column made only where there is no free space (UX J1). if (layout.freeSpace(p, from, .doc) == null) { layout.newColumn(p, from); p.exec_column = layout.activeColumn(p) orelse continue; } defer p.exec_column = null; pardes.tagline.exitHeader(p); _ = look.open(p, from, at.path, at.at, .below); } else if (how != .queue) { _ = 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})); } } // ---- after Enter: the list word ---- /// The list as its word in a trail says it (SPEC §5.6): its source, its /// query, where its cursor is among its rows, and its marks: /// `Find pick 3/6 •2`. fn wordOf(p: *const Pardes, pk: *const Pick, buf: *Kind.Buf(Trail.max_text)) []const u8 { var w: std.Io.Writer = .fixed(&buf.bytes); w.writeAll(pk.word.slice()) catch {}; if (pk.root) w.writeAll(" root") catch {}; for (pk.refined[0..pk.nrefined]) |r| w.print(" {s} |", .{r.query.slice()}) catch {}; if (pk.query.len > 0) w.print(" {s}", .{pk.query.slice()}) catch {}; const n = count(p, pk); w.print(" {d}/{d}", .{ if (n == 0) 0 else pk.at + 1, n }) catch {}; if (pk.marks.items.len > 0) w.print(" •{d}", .{pk.marks.items.len}) catch {}; buf.len = @intCast(w.buffered().len); 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; 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 }); // The newest list or search is the word n and N walk (SPEC §6.3): a // search's tints go with it (§7.3: lit while it is n's). if (pane.places.provenance == .search) pane.places.clear(p.gpa); } /// `n` and `N` in a reading pane whose trail's newest list or search word /// is a list's: its next or previous row in place of the current step /// (Trail.replaceStep), its word saying where it is now. False when there /// is no list for them to walk (normal.zig: the search's then). pub fn walkList(p: *Pardes, id: usize, forward: bool) bool { const pane = p.panes[id] orelse return false; if (!Trail.reading(p, pane)) return false; const t = &pane.trail; var i: usize = @min(t.cur, t.n); while (i > 0) { i -= 1; switch (t.steps[i]) { .list => break, .search => return false, else => {}, } } else return false; const pk = byId(p, t.steps[i].list.index) orelse return false; const n = count(p, pk); if (n == 0) return false; if (if (forward) pk.at + 1 >= n else pk.at == 0) { p.setMessage(.at(id), if (forward) "n: the list's last row" else "N: the list's first row"); return true; } pk.at = if (forward) pk.at + 1 else pk.at - 1; var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const row = rowAt(p, pk, arena.allocator(), pk.at) catch return true; const at = switch (row.target) { .place => |x| x, else => return true, }; _ = wordOf(p, pk, &t.steps[i].list.text); _ = Trail.replaceStep(p, id, at.path, at.at) catch |err| p.reportError(.at(id), "walk", err); return true; } /// 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 under that /// reading pane's tag, which asks it now and previews it, 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.owner = pane.serial; pk.landing = pane.serial; pk.made = false; p.view().active = id; 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. fn unrollRows(p: *Pardes, pk: *Pick) void { const at = pk.at; if (!fuzzy(pk) and pk.source == .all) filter(p, pk); p.view().tag_state.rows.at = @intCast(@min(at, std.math.maxInt(u16))); } /// Exec on a list word (SPEC §6.3): its source run again with its query, /// from pane `id`. pub fn rerun(p: *Pardes, id: usize, index: u32) void { const pk = byId(p, index) orelse return p.setMessage(.at(id), "walk: that list is gone: the last 8 are kept"); var query: Kind.Buf(256) = .{}; query.set(pk.query.slice()); // One Root asked runs at the root again. const was = p.exec_root; p.exec_root = was or pk.root; defer p.exec_root = was; open(p, id, pk.source, pk.word.slice(), query.slice(), pk.rows); } /// 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 { 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`, under its tag (UX DESIGN O1). 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; } /// Enter on the live picker's current row: B3 on its text where it /// previews (mouse.zig, UX DESIGN O3). 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); } /// A press on row `row` of the live picker's band (mouse.zig bandPress, UX /// DESIGN O2): B1 (`enter` false) puts the cursor on it, the list's or the /// act step's; B3 does what Enter does there (`below`: Shift-B3, as /// S-Enter): the row landed, the act applied, the source switched to, the /// theme worn, the action applied. A row of the act step or the source /// spine is its key's, its first byte (actStep, steps). pub fn press(p: *Pardes, row: Band.Row, enter: bool, below: bool) void { const pk = live(p) orelse return; const s = &p.view().tag_state; if ((pk.spine == .acts or pk.spine == .sources) and row.key > 0) { if (enter) return key(p, .{ .cp = row.text[0] }); if (pk.spine == .acts) pk.act_at = @intCast(row.index); return; } if (pk.spine != .rows or row.index >= count(p, pk)) return; s.rows.at = row.index; if (!enter) return; if (pk.source == .lists) return reopenListed(p, pk); if (pk.source == .themes or pk.source == .actions) return key(p, .{ .cp = Key.enter }); land(p, if (below) .below else .walk); } /// The wheel over the live picker's head or band (UX DESIGN O2): its /// cursor `delta` rows on, the band's eleven following it and the preview /// with them, as the keys move it. pub fn wheel(p: *Pardes, delta: i32) void { const pk = live(p) orelse return; const s = &p.view().tag_state; const n = @min(count(p, pk), std.math.maxInt(u16)); if (n == 0 or pk.spine != .rows) return; s.rows.at = @intCast(std.math.clamp(@as(i64, s.rows.at) + delta, 0, @as(i64, @intCast(n)) - 1)); if (fuzzy(pk)) pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown); } /// Whether screen row `row` of pane `id` is text the live picker previews: /// its landing pane's body, a place shown in it (UX DESIGN O3). B2 and B3 /// there land it first: acting on the file is taking it. pub fn previewsAt(p: *const Pardes, id: usize, row: u16) bool { const pk = live(p) orelse return false; const pane = p.panes[id] orelse return false; if (pane.serial != pk.landing or !pk.previewed or pk.source == .themes or pk.source == .actions) return false; return row >= p.bodyTop(pane, p.view().rects[id]); } /// The live picker, waiting or not, ended as Esc ends it when what is about /// to run changes or closes pane `id`, the pane it asks from or previews in /// (UX DESIGN O3: Del, Get, Undo, Put, Keep, a walk step there, a Look that /// lands there, the pane closed): the preview's own text back, a pane made /// for it gone with it. Anything else leaves it up. pub fn yieldFor(p: *Pardes, id: usize) void { const pk = live(p) orelse return; const pane = p.panes[id] orelse return; if (pane.serial == pk.owner or pane.serial == pk.landing) TagState.toRest(p); } /// 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; const n = count(p, pk); var picked: std.ArrayList(Target) = .empty; if (n == 0) return picked.items; if (pk.marks.items.len == 0) { try picked.append(a, (try rowAt(p, pk, a, s.rows.at)).target); } else for (0..n) |i| if (marked(pk, idOf(pk, i)) != null) { try picked.append(a, (try rowAt(p, pk, a, i)).target); }; return picked.items; } /// C-i past a reading pane's newest step (Jump.jumpBy, SPEC §6.4): the /// next place a Walk queued in it, through the list its trail holds last. pub fn stepQueue(p: *Pardes, id: usize) bool { const pane = p.panes[id] orelse return false; const t = &pane.trail; var i: usize = @min(t.cur, t.n); const pk = while (i > 0) { i -= 1; if (t.steps[i] == .list) break byId(p, t.steps[i].list.index) orelse return false; } else return false; if (pk.queue_at >= pk.queue.items.len) return false; const q = pk.queue.items[pk.queue_at]; pk.queue_at += 1; p.view().jumps.force = true; _ = look.open(p, id, pk.queue_bytes.items[q.path..][0..q.len], .{ .line = q.line, .col = q.col }, .replace); return true; } // ---- acts ---- /// What the act step offers (SPEC §5.5): the same everywhere, but a list /// of panes, whose rows are no places, has Look, Copy, Keep, Drop and Del. const Act = struct { key: u8, word: []const u8, says: []const u8 }; const acts = [_]Act{ .{ .key = 'w', .word = "Walk", .says = "here, one by one (C-i)" }, .{ .key = 'o', .word = "Look", .says = "open them (Enter)" }, .{ .key = 's', .word = "Split", .says = "each in a pane below" }, .{ .key = 'v', .word = "Newcol", .says = "in a new column" }, .{ .key = 'g', .word = "Grep", .says = "in their directory, the same pattern" }, .{ .key = 'e', .word = "Edit", .says = "a sam command on each line" }, .{ .key = 'y', .word = "Copy", .says = "the places, as text" }, .{ .key = 'k', .word = "Keep", .says = "the rows as a +Search" }, .{ .key = 'x', .word = "Drop", .says = "the picked from the list" }, .{ .key = 'd', .word = "Del", .says = "close those panes" }, }; fn offered(pk: *const Pick, act: Act) bool { if (pk.source == .panes) return std.mem.indexOfScalar(u8, "oykxd", act.key) != null; return act.key != 'd'; } /// The act step: what it acts on (`on 2 marked`, `on core/pick.zig`), /// then the acts. fn actStep(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator) !Band.Step { var rows: std.ArrayList(Band.Row) = .empty; const s = &p.view().tag_state; const on = if (pk.marks.items.len > 0) try std.fmt.allocPrint(arena, "on {d} marked", .{pk.marks.items.len}) else if (count(p, pk) > 0) on: { const row = try rowAt(p, pk, arena, s.rows.at); break :on try std.fmt.allocPrint(arena, "on {s}", .{switch (row.target) { .place => |t| relative(t.path, pk.dir.slice()), else => row.text, }}); } else "on nothing"; try rows.append(arena, .{ .text = on, .dim = true }); var k: u8 = 0; for (acts) |act| if (offered(pk, act)) { try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "{c} {s: <7} {s}", .{ act.key, act.word, act.says }), .key = 1, .on = k == pk.act_at, .index = k }); k += 1; }; return .{ .rows = rows.items }; } fn actKey(p: *Pardes, pk: *Pick, k: Key) void { const plain = !k.ctrl and !k.alt; var n: u8 = 0; for (acts) |act| n += @intFromBool(offered(pk, act)); if (plain and (k.cp == Key.down or k.cp == Key.up)) { pk.act_at = if (k.cp == Key.down) (pk.act_at + 1) % n else (pk.act_at + n - 1) % n; return; } var at: u8 = 0; for (acts) |act| if (offered(pk, act)) { if (plain and (k.cp == act.key or k.cp == Key.enter and at == pk.act_at)) return doAct(p, pk, act.key); at += 1; }; // Anything else (M-h, Left): back to the rows. pk.spine = .rows; } /// Act `key` on the picked rows. fn doAct(p: *Pardes, pk: *Pick, key_: u8) void { const s = &p.view().tag_state; pk.spine = .rows; switch (key_) { 'w' => land(p, .queue), 'o' => land(p, .walk), 's' => land(p, .below), 'v' => land(p, .column), 'k' => keep(p, pk), 'x' => refine(p, pk, true), 'e' => { pk.query.set(s.field.text()); s.field.clear(); pk.spine = .edit; }, 'g' => { var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const picked = pickedRows(p, pk, arena.allocator()) catch return; const dir = for (picked) |t| switch (t) { .place => |at| break std.Io.Dir.path.dirname(at.path) orelse pk.dir.slice(), else => {}, } else pk.dir.slice(); const q = if (pk.source == .grep) arena.allocator().dupe(u8, s.field.text()) catch return else ""; const where = arena.allocator().dupe(u8, dir) catch return; const from = p.paneBySerial(pk.owner) orelse p.view().active; TagState.toRest(p); open(p, from, .grep, "", "", ""); const grep = live(p) orelse return; grep.dir.set(where); p.view().tag_state.field.set(q); filter(p, grep); }, 'y' => { var out: std.Io.Writer.Allocating = .init(p.gpa); defer out.deinit(); var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const picked = pickedRows(p, pk, arena.allocator()) catch return; for (picked) |t| switch (t) { .place => |at| out.writer.print("{s}:{d}\n", .{ at.path, @max(1, at.at.line) }) catch return, .pane => |serial| out.writer.print(config.pane_addr ++ "{d}\n", .{serial}) catch return, .none => {}, }; p.registers.put(p.gpa, '"', out.written(), 0, 1, true) catch |err| return p.reportError(.at(p.view().active), "pick", err); var said: Kind.Buf(64) = .{}; p.setMessage(.at(p.view().active), said.print("Copy: {d} places into the \" register", .{picked.len})); }, 'd' => { var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const picked = pickedRows(p, pk, arena.allocator()) catch return; for (picked) |t| if (t == .pane) if (p.paneBySerial(t.pane)) |id| if (id != p.paneBySerial(pk.landing)) { p.removePane(id, null) catch |err| p.reportError(.at(id), "pick", err); }; pk.marks.clearRetainingCapacity(); start(p, pk); filter(p, pk); }, else => {}, } } /// Edit's Enter: its command run on each picked row's line, in the open /// text that shows its file (edit_cmd.zig, an undo step a line); a row /// whose file no pane shows is passed over, and said. fn editRows(p: *Pardes, pk: *Pick) void { const s = &p.view().tag_state; var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const a = arena.allocator(); const command = a.dupe(u8, std.mem.trim(u8, s.field.text(), " ")) catch return; const picked = pickedRows(p, pk, a) catch return; TagState.toRest(p); if (command.len == 0) return; var ran: usize = 0; // From the last line up, so an edit that adds lines moves none still to come. var k = picked.len; while (k > 0) { k -= 1; const at = switch (picked[k]) { .place => |t| t, else => continue, }; const id = for (p.panes, 0..) |slot, i| { const tp = slot orelse continue; const f = tp.file orelse continue; if (f.output == null and std.mem.eql(u8, f.path, at.path)) break i; } else continue; @import("edit_cmd.zig").run(p, id, std.fmt.allocPrint(a, "{d} {s}", .{ @max(1, at.at.line), command }) catch return); ran += 1; } var said: Kind.Buf(96) = .{}; p.setMessage(.at(p.view().active), said.print("Edit {s}: {d} of {d} lines, in open texts", .{ command[0..@min(command.len, 40)], ran, picked.len })); } /// A word of the picker's tag or band run (B2, exec.zig /// executeBuiltinLine) while it is live: an act's word acts, a source's /// switches to it (Grep, both, is the source); anything else is no /// 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); return true; }; if (std.mem.eql(u8, word, "Jumplist")) { switchTo(p, pk, .jumplist); return true; } for (acts) |act| if (offered(pk, act) and std.mem.eql(u8, word, act.word)) { doAct(p, pk, act.key); return true; }; return false; } fn testFile(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) ![]u8 { 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)]; return std.Io.Dir.path.join(p.gpa, &.{ dir, name }); } fn tagOf(p: *Pardes, arena: std.mem.Allocator, id: usize) ![]const u8 { return pardes.tagline.tagText(p, arena, p.panes[id].?); } /// The head under pane `id`'s tag (UX DESIGN M2); none at rest. fn headOf(p: *Pardes, arena: std.mem.Allocator, id: usize) ![]const u8 { const h = try TagState.head(p, arena, p.panes[id].?); return if (h) |made| made.text else ""; } fn paneCount(p: *const Pardes) usize { var n: usize = 0; for (p.panes) |slot| n += @intFromBool(slot != null); return n; } fn settle(p: *Pardes) void { var n: usize = 0; while (n < 50 and (busy(p) or p.stream.busyFor(live(p).?.id))) : (n += 1) { Stream.step(p); p.update(.tick); } } test "a picker from a held pane hangs under that pane's tag, which keeps the keyboard; its preview in a reader made for it under it, whose tag is `‹@pN ›`: the body the current row's file, Esc takes the reader away (UX DESIGN O1)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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", "const alpha = 1;\n"); defer p.gpa.free(a_path); const b_path = try testFile(p, &tmp, "pick_state.zig", "//! The state a picker keeps\nconst x = 2;\n"); defer p.gpa.free(b_path); const held = try p.setTestFile("held\n"); _ = held; const asker = p.view().active; // Held: Keep. Trail.keep(p.panes[asker].?); const dir = std.Io.Dir.path.dirname(a_path).?; p.gpa.free(p.panes[asker].?.file.?.path); p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ dir, "held.txt" }); p.stream.engine = .walk; const npanes = paneCount(p); open(p, asker, .find, "", "", ""); const pk = live(p).?; // A reader made for it, under the asker, which hangs the picker. try std.testing.expectEqual(npanes + 1, paneCount(p)); try std.testing.expect(pk.made); const reader = p.paneBySerial(pk.landing).?; try std.testing.expectEqual(@as(?usize, asker), TagState.hostOf(p)); try std.testing.expectEqual(asker, p.view().active); try std.testing.expect(p.view().rects[reader].y > p.view().rects[asker].y); settle(p); try std.testing.expectEqual(@as(usize, 2), count(p, pk)); for ("pick") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); settle(p); try std.testing.expectEqual(@as(usize, 1), count(p, pk)); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); // Its tag the owner's word alone (UX DESIGN M3, O1); the head under // the asker's. try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, a, reader), "‹@p")); try std.testing.expectEqualStrings("", try headOf(p, a, reader)); const tag = try headOf(p, a, asker); try std.testing.expect(std.mem.startsWith(u8, tag, "␣ f Find pick ") and std.mem.indexOf(u8, tag, " 1/1") != null); // The body previews the row's file, after a frame of its own. p.update(.tick); try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); _ = try p.render(a); const r = p.view().rects[asker]; try std.testing.expectEqualStrings("^", p.surface.at(r.x, r.y).grapheme()); try std.testing.expect(Band.covered(p, p.panes[asker].?, asker).band >= 1); try std.testing.expectEqual(@as(u16, 0), Band.covered(p, p.panes[reader].?, reader).over); // Esc: the reader made for it goes, the asker as it was. p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expect(live(p) == null); try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expectEqualStrings("pick", pk.query.slice()); } test "a picker's head is one row: the count and one dim hint at its right end, `M-l acts`; no row of acts and sources, the list's rows right under it; Themes hints nothing (UX DESIGN O4)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 40 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); defer p.gpa.free(a_path); _ = 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 std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); p.stream.engine = .walk; open(p, asker, .find, "", "", ""); settle(p); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const tag = try headOf(p, a, asker); try std.testing.expect(std.mem.indexOfScalar(u8, tag, '\n') == null); try std.testing.expect(std.mem.startsWith(u8, tag, "␣ f Find ") and std.mem.endsWith(u8, tag, "1/1 M-l acts")); try std.testing.expectEqual(@as(usize, pardes.tagline.tagWidth(p, asker)), File.displayWidth(p.settings.tab, tag)); const h = (try head(p, a, p.panes[asker].?)).?; try std.testing.expect(h.spans[h.spans.len - 1].style == .dim); // The band's first row the list's first. const band = (try Band.of(p, a, p.panes[asker].?, asker)).?; try std.testing.expect(std.mem.indexOf(u8, (try band.line(a, p.settings.tab, 0)).text, "▶ alpha.zig") != null); p.update(.{ .key = .{ .cp = Key.escape } }); open(p, asker, .themes, "", "", ""); const themes = try headOf(p, a, asker); try std.testing.expect(std.mem.indexOf(u8, themes, "esc") == null and std.mem.indexOf(u8, themes, "M-l") == null and std.mem.indexOf(u8, themes, "⏎") == null); p.update(.{ .key = .{ .cp = Key.escape } }); } test "a picker's band is its list's rows (UX DESIGN O4, D6): a list whose rows come later (Find) holds 3 at open, never moved by typing; a list known at open exactly its rows: SPC b b with two panes covers its head and 2 rows" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); defer p.gpa.free(a_path); _ = try p.setTestFile("held\n"); const asker = p.view().active; Trail.keep(p.panes[asker].?); // In the test's directory: its two files listed. p.gpa.free(p.panes[asker].?.file.?.path); p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); p.stream.engine = .walk; open(p, asker, .find, "", "", ""); settle(p); const reader = asker; p.sync(); const rows = Band.covered(p, p.panes[reader].?, reader).band; // One file listed: three rows, ground under it. try std.testing.expectEqual(@as(u16, 3), rows); for ("zzq") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); settle(p); p.sync(); try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?)); try std.testing.expectEqual(rows, Band.covered(p, p.panes[reader].?, reader).band); p.update(.{ .key = .{ .cp = Key.escape } }); // Two panes: SPC b b's band two rows. p.newScratchBelow(asker); p.view().active = asker; p.sync(); for (" bb") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); p.sync(); try std.testing.expectEqual(Source.panes, live(p).?.source); const at = Band.covered(p, p.panes[asker].?, asker); try std.testing.expect(at.head == 1 and at.band == 2); } test "a picker's band is capped once at open at 40 % of its asking pane's rows; the pane it previews in borrows from its column for a body of 60 %: a Grep from a held pane at 100x30 previews 8 rows at least, in a reader made under it (UX D6, DESIGN O1)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); for (0..40) |i| try text.print(std.testing.allocator, "pub fn f{d}() void {{}}\n", .{i}); const a_path = try testFile(p, &tmp, "alpha.zig", text.items); defer p.gpa.free(a_path); _ = 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 std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); p.stream.engine = .walk; p.sync(); const at_open = p.view().rects[asker].h; open(p, asker, .grep, "", "", ""); const reader = p.paneBySerial(live(p).?.landing).?; try std.testing.expect(reader != asker); for ("pub fn") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); // Its lines after the typing's pause: the band from 3 rows to its cap. if (p.stream.due_ns) |due| p.clock.now_ns = due; settle(p); try std.testing.expectEqual(@as(usize, 40), count(p, live(p).?)); p.update(.{ .key = .{ .cp = Key.down } }); p.update(.tick); p.sync(); const at = Band.covered(p, p.panes[asker].?, asker); try std.testing.expectEqual(@min(Band.Cursor.shown, at_open * 2 / 5), at.band); // The preview's rows under the reader's tag, no band over them. const r = p.view().rects[reader]; try std.testing.expectEqual(@as(u16, 0), Band.covered(p, p.panes[reader].?, reader).over); const under = r.h - p.panes[reader].?.tag_rows; try std.testing.expect(under >= 8); try std.testing.expect(@as(u32, under) * 5 >= @as(u32, r.h) * 3); } test "a picker's keys: Tab marks and moves, M-a all and none, C-SPC refines and Backspace undoes it, M-h switches source keeping the query" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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", "const alpha = 1;\n"); defer p.gpa.free(a_path); look.lookAt(p, p.view().active, a_path); const id = p.view().active; open(p, id, .list, "Refs", "", "alpha.zig:1:1 one\nalpha.zig:1:2 two\nbeta.zig:1:1 tree\nalpha.zig:1:4 four\n"); const pk = live(p).?; settle(p); const s = &p.view().tag_state; try std.testing.expectEqual(@as(usize, 4), count(p, pk)); p.update(.{ .key = .{ .cp = Key.tab } }); try std.testing.expectEqual(@as(u16, 1), s.rows.at); p.update(.{ .key = .{ .cp = Key.tab } }); try std.testing.expectEqual(@as(usize, 2), pk.marks.items.len); p.update(.{ .key = .{ .cp = Key.up } }); p.update(.{ .key = .{ .cp = Key.tab } }); try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len); try std.testing.expectEqual(@as(u16, 2), s.rows.at); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const refs = try headOf(p, frame.allocator(), id); try std.testing.expect(std.mem.indexOf(u8, refs, " Refs ") != null and std.mem.endsWith(u8, refs, " 3/4 •1 M-l acts")); p.update(.{ .key = .{ .cp = 'a', .alt = true } }); try std.testing.expectEqual(@as(usize, 4), pk.marks.items.len); p.update(.{ .key = .{ .cp = 'a', .alt = true } }); try std.testing.expectEqual(@as(usize, 0), pk.marks.items.len); // C-SPC: what `alpha` keeps becomes the list; `w` then narrows it. for ("alpha") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); settle(p); try std.testing.expectEqual(@as(usize, 3), count(p, pk)); p.update(.{ .key = .{ .cp = ' ', .ctrl = true } }); try std.testing.expectEqual(@as(u8, 1), pk.nrefined); try std.testing.expectEqual(@as(u16, 0), s.field.len); settle(p); try std.testing.expectEqual(@as(usize, 3), count(p, pk)); for ("w") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); settle(p); try std.testing.expectEqual(@as(usize, 1), count(p, pk)); _ = frame.reset(.retain_capacity); const refined = try headOf(p, frame.allocator(), id); try std.testing.expect(std.mem.indexOf(u8, refined, " Refs alpha | w ") != null and std.mem.endsWith(u8, refined, " 1/1 M-l acts")); // Backspace twice: the `w` goes, then the refinement, its query back. p.update(.{ .key = .{ .cp = Key.backspace } }); p.update(.{ .key = .{ .cp = Key.backspace } }); try std.testing.expectEqual(@as(u8, 0), pk.nrefined); try std.testing.expectEqualStrings("alpha", s.field.text()); settle(p); try std.testing.expectEqual(@as(usize, 3), count(p, pk)); // M-p: the preview off, and no frame asked for it. p.update(.{ .key = .{ .cp = 'p', .alt = true } }); try std.testing.expect(!pk.previews and !busy(p)); p.update(.{ .key = .{ .cp = 'p', .alt = true } }); // M-h r: Recent, the query kept. p.update(.{ .key = .{ .cp = 'h', .alt = true } }); try std.testing.expect(pk.spine == .sources); p.update(.{ .key = .{ .cp = 'r', .text = "r" } }); try std.testing.expectEqual(Source.recent, pk.source); try std.testing.expectEqualStrings("alpha", s.field.text()); p.update(.{ .key = .{ .cp = Key.escape } }); } test "Enter lands as a walk step in the reading pane; S-Enter opens below; from a held pane the reader made for the picker becomes its reader" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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", "const alpha = 1;\n"); defer p.gpa.free(a_path); const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); defer p.gpa.free(b_path); look.lookAt(p, p.view().active, a_path); p.sync(); const id = p.view().active; const npanes = paneCount(p); open(p, id, .list, "Refs", "", "beta.zig:3:1 three\n"); settle(p); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(live(p) == null); const here = p.panes[p.view().active].?; try std.testing.expectEqualStrings(b_path, here.file.?.path); try std.testing.expectEqual(@as(i32, 2), here.body.cur_row); try std.testing.expect(here.file.?.output == null); try std.testing.expectEqual(npanes, paneCount(p)); // Its trail: where it was, then the place. try std.testing.expect(here.trail.n >= 2); // S-Enter: a pane below, the reading pane as it was. open(p, p.view().active, .list, "Refs", "", "alpha.zig:1:7 alpha\n"); settle(p); p.update(.{ .key = .{ .cp = Key.enter, .shift = true } }); try std.testing.expectEqual(npanes + 1, paneCount(p)); try std.testing.expectEqualStrings(a_path, p.panes[p.view().active].?.file.?.path); // From a held pane: the reader made for the picker is taken away and // the place opens as the held pane's reader, its trail its owner's. const held = p.view().active; Trail.keep(p.panes[held].?); open(p, held, .list, "Refs", "", "beta.zig:2:1 two\n"); const pk = live(p).?; try std.testing.expect(pk.made); settle(p); p.update(.{ .key = .{ .cp = Key.enter } }); const reader = Trail.readerOf(p, p.panes[held].?).?; try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); try std.testing.expectEqual(npanes + 2, paneCount(p)); } test "M-l unrolls the act step, which says what it acts on; Copy puts the places in the register, Drop takes the picked rows out, Walk queues the rest for C-i" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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\nthree\nfour\n"); defer p.gpa.free(a_path); look.lookAt(p, p.view().active, a_path); const id = p.view().active; const rows = "alpha.zig:1:1 one\nalpha.zig:2:1 two\nalpha.zig:3:1 three\nalpha.zig:4:1 four\n"; open(p, id, .list, "Refs", "", rows); const pk = live(p).?; settle(p); p.update(.{ .key = .{ .cp = 'l', .alt = true } }); try std.testing.expect(pk.spine == .acts); // The band as tall as the acts and what they act on, the list's rows fewer. try std.testing.expectEqual(@as(u16, 10), bandRows(p)); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const band = (try Band.of(p, frame.allocator(), p.panes[id].?, id)).?; try std.testing.expectEqual(@as(u8, 2), band.nsteps); try std.testing.expectEqualStrings("on alpha.zig", band.steps[1].rows[0].text); // y: the place copied, the act step rolled back to the rows. p.update(.{ .key = .{ .cp = 'y', .text = "y" } }); try std.testing.expect(pk.spine == .rows); // x: the current row dropped, as a refinement. p.update(.{ .key = .{ .cp = 'l', .alt = true } }); p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); settle(p); try std.testing.expectEqual(@as(usize, 3), count(p, pk)); try std.testing.expectEqual(@as(u8, 1), pk.nrefined); // Tab Tab: two marked; Walk lands on the first and queues the second. p.update(.{ .key = .{ .cp = Key.tab } }); p.update(.{ .key = .{ .cp = Key.tab } }); p.update(.{ .key = .{ .cp = 'l', .alt = true } }); _ = frame.reset(.retain_capacity); const marked_band = (try Band.of(p, frame.allocator(), p.panes[id].?, id)).?; try std.testing.expectEqualStrings("on 2 marked", marked_band.steps[1].rows[0].text); p.update(.{ .key = .{ .cp = 'w', .text = "w" } }); try std.testing.expect(live(p) == null); try std.testing.expectEqual(@as(i32, 1), p.panes[p.view().active].?.body.cur_row); try std.testing.expectEqual(@as(usize, 1), pk.queue.items.len); } test "after Enter the list is a word in the reader's trail: n and N walk its rows in place, a Look on it reopens it with its cursor and marks, Exec runs it again, Resume reopens the last" { 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\nthree\nfour\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); _ = try p.setTestFile("held\n"); const held = p.view().active; Trail.keep(p.panes[held].?); p.gpa.free(p.panes[held].?.file.?.path); p.panes[held].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); open(p, held, .list, "Refs", "", "alpha.zig:2:1 two\nbeta.zig:2:1 b2\nalpha.zig:4:1 four\n"); const pk = live(p).?; settle(p); p.update(.{ .key = .{ .cp = Key.tab } }); p.update(.{ .key = .{ .cp = Key.up } }); p.update(.{ .key = .{ .cp = Key.enter } }); // The reader: its owner, the list's word, the place. const reader = Trail.readerOf(p, p.panes[held].?).?; var t = &p.panes[reader].?.trail; try std.testing.expectEqual(@as(u8, 3), t.n); try std.testing.expect(t.steps[1] == .list); try std.testing.expectEqualStrings("Refs 1/3 •1", t.steps[1].list.text.slice()); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), reader), "‹@p") != null); try std.testing.expect(std.mem.indexOf(u8, try tagOf(p, frame.allocator(), reader), " › Refs 1/3 •1 › ") != null); // n: the next row, in place of the step (another file: a pane in its place). p.view().active = reader; p.update(.{ .key = .{ .cp = 'n', .text = "n" } }); const r2 = Trail.readerOf(p, p.panes[held].?).?; try std.testing.expectEqualStrings(b_path, p.panes[r2].?.file.?.path); t = &p.panes[r2].?.trail; try std.testing.expectEqual(@as(u8, 3), t.n); try std.testing.expectEqualStrings("Refs 2/3 •1", t.steps[1].list.text.slice()); p.update(.{ .key = .{ .cp = 'N', .text = "N", .shift = true } }); const r3 = Trail.readerOf(p, p.panes[held].?).?; try std.testing.expectEqualStrings(a_path, p.panes[r3].?.file.?.path); try std.testing.expectEqual(@as(i32, 1), p.panes[r3].?.body.cur_row); // Look on the word: the list again, in the reader's tag, as it was. Trail.lookStep(p, r3, 1); try std.testing.expect(live(p) == pk); try std.testing.expectEqual(@as(?usize, r3), TagState.hostOf(p)); try std.testing.expectEqual(@as(u16, 0), p.view().tag_state.rows.at); try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len); p.update(.{ .key = .{ .cp = Key.escape } }); // Exec on it: a new picker of the same source. Trail.execStep(p, r3, 1); try std.testing.expect(live(p) != null and live(p) != pk); p.update(.{ .key = .{ .cp = Key.escape } }); // Resume: the last one. exec.runBuiltin(p, .Resume, held, "", null); try std.testing.expect(live(p) != null); p.update(.{ .key = .{ .cp = Key.escape } }); } test "pick-ui §14.3 phase 4: SPC f f from a held pane opens in its reader and Esc removes it; from a reading pane it unrolls there; Enter lands as a step leaving the list word; n walks; a Look on the word reopens it with its cursor and marks" { 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 a_path = try testFile(p, &tmp, "pick.zig", "const pick = 1;\n"); defer p.gpa.free(a_path); const b_path = try testFile(p, &tmp, "pick_test.zig", "test {}\n"); defer p.gpa.free(b_path); const c_path = try testFile(p, &tmp, "other.zig", "x\n"); defer p.gpa.free(c_path); _ = try p.setTestFile("held\n"); const held = p.view().active; Trail.keep(p.panes[held].?); p.gpa.free(p.panes[held].?.file.?.path); p.panes[held].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); const npanes = paneCount(p); const typeIn = struct { fn f(pp: *Pardes, keys: []const u8) void { for (keys) |c| pp.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); } }.f; // SPC f f from the held pane: a reader made for it, which Esc takes. typeIn(p, " ff"); try std.testing.expect(live(p) != null and live(p).?.made); try std.testing.expectEqual(npanes + 1, paneCount(p)); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expectEqual(held, p.view().active); // Again, typed into: Enter lands in a reader of the held pane. typeIn(p, " ffpick"); const pk = live(p).?; settle(p); try std.testing.expectEqual(@as(usize, 2), count(p, pk)); p.update(.{ .key = .{ .cp = Key.tab } }); p.update(.{ .key = .{ .cp = Key.up } }); p.update(.{ .key = .{ .cp = Key.enter } }); const reader = Trail.readerOf(p, p.panes[held].?).?; const t = &p.panes[reader].?.trail; try std.testing.expect(t.n == 3 and t.steps[1] == .list); try std.testing.expect(std.mem.startsWith(u8, t.steps[1].list.text.slice(), "Find pick 1/2 •1")); const first = p.panes[reader].?.file.?.path; try std.testing.expect(std.mem.eql(u8, first, a_path) or std.mem.eql(u8, first, b_path)); // n: the other row, in place of the step. p.view().active = reader; p.update(.{ .key = .{ .cp = 'n', .text = "n" } }); const now = Trail.readerOf(p, p.panes[held].?).?; try std.testing.expect(!std.mem.eql(u8, p.panes[now].?.file.?.path, first)); try std.testing.expectEqual(@as(u8, 3), p.panes[now].?.trail.n); // SPC f f from the reader, which reads: it unrolls in the reader itself. typeIn(p, " ff"); try std.testing.expectEqual(@as(?usize, now), TagState.hostOf(p)); try std.testing.expect(!live(p).?.made); p.update(.{ .key = .{ .cp = Key.escape } }); // A Look on the list word: the list again, its cursor and its mark. Trail.lookStep(p, now, 1); try std.testing.expect(live(p) == pk); try std.testing.expectEqual(@as(u16, 1), p.view().tag_state.rows.at); try std.testing.expectEqual(@as(usize, 1), pk.marks.items.len); try std.testing.expectEqualStrings("pick", p.view().tag_state.field.text()); p.update(.{ .key = .{ .cp = Key.escape } }); } test "a picker from a reading pane unrolls in that pane, its own text set aside while it previews and back on Esc" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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", "const alpha = 1;\n"); defer p.gpa.free(a_path); const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); defer p.gpa.free(b_path); look.lookAt(p, p.view().active, a_path); p.sync(); const id = p.view().active; try std.testing.expect(Trail.reading(p, p.panes[id].?)); const npanes = paneCount(p); open(p, id, .list, "Refs", "", "beta.zig:2:1 two\nalpha.zig:1:7 alpha\n"); const pk = live(p).?; try std.testing.expect(!pk.made); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expectEqual(@as(?usize, id), TagState.hostOf(p)); settle(p); try std.testing.expectEqual(@as(usize, 2), count(p, pk)); try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path); try std.testing.expectEqual(@as(i32, 1), p.panes[id].?.body.cur_row); try std.testing.expect(pk.aside != null); // Down: the next row's file, on the frame after. p.update(.{ .key = .{ .cp = Key.down } }); try std.testing.expectEqualStrings(b_path, p.panes[id].?.file.?.path); p.update(.tick); try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pk.aside == null); try std.testing.expectEqualStrings(a_path, p.panes[id].?.file.?.path); try std.testing.expect(p.panes[id].?.file.?.output == null); try std.testing.expectEqual(npanes, paneCount(p)); } test "SPC t t is a picker of the themes in the asking pane's tag, the whole window wearing the row under the cursor and nothing dimmed; Esc puts the theme back, Enter wears it" { const Key_ = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 30 }); defer p.deinit(); _ = try p.setTestFile("one\n"); const asker = p.view().active; p.newScratchBelow(asker); p.view().active = asker; p.settings.jumps = .walk; const themes = pardes.colors.themes; const was = p.settings.theme; const worn = p.theme().name; for (" tt") |c| p.update(.{ .key = .{ .cp = c } }); const s = &p.view().tag_state; try std.testing.expectEqual(TagState.Kind.pick, s.kind); try std.testing.expectEqual(Source.themes, live(p).?.source); try std.testing.expectEqual(p.panes[asker].?.serial, s.host); try std.testing.expectEqual(@as(u16, @intCast(was)), s.rows.at); try std.testing.expectEqual(pardes.MAX_PANES, s.previewing.count()); // Down: the window wears the next theme, the session's unchanged. p.update(.{ .key = .{ .cp = if (was + 1 < themes.len) Key_.down else Key_.up } }); const shown = s.rows.at; try std.testing.expect(std.mem.eql(u8, p.theme().name, themes[shown].name) and shown != was); try std.testing.expectEqual(was, p.settings.theme); // Esc: its own again. p.update(.{ .key = .{ .cp = Key_.escape } }); try std.testing.expectEqualStrings(worn, p.theme().name); try std.testing.expect(p.theme_preview == null); // Again, and Enter wears it. for (" tt") |c| p.update(.{ .key = .{ .cp = c } }); p.update(.{ .key = .{ .cp = if (was + 1 < themes.len) Key_.down else Key_.up } }); p.update(.{ .key = .{ .cp = Key_.enter } }); try std.testing.expectEqual(@as(@TypeOf(p.settings.theme), @intCast(shown)), p.settings.theme); try std.testing.expectEqual(TagState.Kind.rest, s.kind); try std.testing.expect(p.theme_preview == null); try std.testing.expectEqualStrings(themes[shown].name, p.theme().name); } test "n and N walk the newest list or search word, or the one Looked at (SPEC §6.3, §7.3): a list landed after a search puts the search's tints out and n walks the list; Look on the search word lights it again and n steps its places" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 }); defer p.deinit(); p.settings.jumps = .walk; const pane = try p.setTestFile("dirty one\nclean\ndirty two\nclean\ndirty three\n"); const id = p.view().active; for ("/dirty") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(pane.places.started); // A list lands in the pane after the search: the list is n's. open(p, id, .list, "Refs", "", "/test.txt:2:1 clean\n/test.txt:4:1 clean\n"); landHere(p); try std.testing.expectEqual(id, p.view().active); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expect(!pane.places.started); p.update(.{ .key = .{ .cp = 'n', .text = "n" } }); try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); // Look on the search word: lit again, and n steps its places. var i: u8 = 0; while (i < pane.trail.n and pane.trail.steps[i] != .search) i += 1; try std.testing.expect(i < pane.trail.n); Trail.lookStep(p, id, i); try std.testing.expect(pane.places.started); const was = pane.places.current; p.update(.{ .key = .{ .cp = 'n', .text = "n" } }); try std.testing.expect(pane.places.current != null and !std.meta.eql(was, pane.places.current)); } test "code actions: a picker in the asking pane's tag, the one under the cursor its edit in the body (the lines it changes on the deleted ground, what they become after them), Enter or its digit applies it as one undo step, a command's said" { const Key_ = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); p.settings.jumps = .walk; const pane = try p.setTestFile("one\ntwo add\nthree\n"); const id = p.view().active; // `add` is bytes 8..11. const rows = "x:1:1 extract\nx:1:1 add a line\n@put 0 0 //%20top%0A\nx:1:1 rename add to sum\n@put 8 11 sum\n"; open(p, id, .actions, "", "", rows); live(p).?.revision = pane.file.?.revision; const s = &p.view().tag_state; try std.testing.expectEqual(Source.actions, live(p).?.source); try std.testing.expectEqual(pane.serial, s.host); try std.testing.expectEqual(@as(usize, 3), count(p, live(p).?)); // The rename: `two add` on the deleted ground, `two sum` after it. p.update(.{ .key = .{ .cp = Key_.down } }); p.update(.{ .key = .{ .cp = Key_.down } }); settle(p); p.sync(); var shot = try p.render(frame.allocator()); const r = p.view().rects[id]; const x = r.x + config.GUTTER + File.gutterWidth(pane); const y = p.bodyTop(pane, r); 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 = 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 // action's preview is its edit on the Changes grounds). try std.testing.expect(landingLine(p, frame.allocator(), pane) == null); try std.testing.expect(!std.mem.eql(u8, "▸", shot.at(x - 1, y + 1).grapheme())); var notice: [pardes.Messages.notice_row_cap]u8 = undefined; try std.testing.expect(!pardes.Messages.noticeRow(p, 100, ¬ice).quiet_left); // Up: the line put in at the top, before line 1, nothing deleted. p.update(.{ .key = .{ .cp = Key_.up } }); settle(p); p.sync(); frame.deinit(); 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 = 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 = 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); try std.testing.expectEqualStrings("one\ntwo sum\nthree\n", pane.file.?.content); p.update(.{ .key = .{ .cp = 'u', .text = "u" } }); try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content); // Enter on a command's: said, nothing changed. open(p, id, .actions, "", "", rows); live(p).?.revision = pane.file.?.revision; p.update(.{ .key = .{ .cp = Key_.enter } }); try std.testing.expectEqual(TagState.Kind.rest, s.kind); try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content); try std.testing.expectEqualStrings("Actions: extract: no edit to apply", p.messages.saidBy(pane)); } test "the themes picker marks the theme in use: `in use` at its row's right end in the dim ink, the cursor on it when it opens, the mark staying on it while the window wears another (POLISH 12, UX A15)" { const Key_ = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); const pane = try p.setTestFile("one\n"); const id = p.view().active; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const was = p.settings.theme; for (" tt") |c| p.update(.{ .key = .{ .cp = c } }); const s = &p.view().tag_state; try std.testing.expectEqual(@as(u16, @intCast(was)), s.rows.at); // The band's spines hang from the head's first `cells` spans: its key // cells (`␣ t`), never its dim hint. const h = (try head(p, a, pane)).?; try std.testing.expectEqual(@as(u8, 2), h.cells); for (h.spans[0..h.cells]) |span| try std.testing.expectEqual(TagState.Style.key, span.style); const Find = struct { fn row(band: Band, text: []const u8) ?Band.Row { for (band.steps[0..band.nsteps]) |step| for (step.rows) |r| if (std.mem.eql(u8, r.text, text)) return r; return null; } }; var band = (try Band.of(p, a, pane, id)).?; const worn = Find.row(band, pardes.colors.themes[was].name).?; try std.testing.expectEqualStrings("in use", worn.meta); try std.testing.expect(worn.on); // One row says it. var said: usize = 0; for (band.steps[0..band.nsteps]) |step| for (step.rows) |r| { said += @intFromBool(r.meta.len > 0); }; try std.testing.expectEqual(@as(usize, 1), said); // Drawn at the row's right end, in the dim ink of the selection it is on. _ = try p.render(a); const layer = &p.surface.tag_layers[pardes.BAND_LAYER]; const on = &p.chrome().on(.focus).selection; var found = false; for (0..layer.rows) |row| { const cells = layer.cells[row * layer.cols ..][0..layer.cols]; var at: usize = 0; while (at + 6 <= cells.len) : (at += 1) { if (!std.mem.eql(u8, cells[at].grapheme(), "i") or !std.mem.eql(u8, cells[at + 1].grapheme(), "n") or !std.mem.eql(u8, cells[at + 3].grapheme(), "u")) continue; try std.testing.expectEqual(pardes.Color{ .rgb = on.dim }, cells[at].style.fg); found = true; } } try std.testing.expect(found); // The window wearing the next: the mark stays on the theme in use. p.update(.{ .key = .{ .cp = if (was + 1 < pardes.colors.themes.len) Key_.down else Key_.up } }); band = (try Band.of(p, a, pane, id)).?; try std.testing.expectEqualStrings("in use", Find.row(band, pardes.colors.themes[was].name).?.meta); } test "a picker's preview is legible as one (UX D7): its landing line on the hit ground with `▸` in the gutter, a third of the body above it, and the notice row saying where Enter lands" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); for (1..81) |i| try text.print(std.testing.allocator, "line {d} of the file\n", .{i}); const path = try testFile(p, &tmp, "long.zig", text.items); defer p.gpa.free(path); _ = try p.setTestFile("held\n"); const asker = p.view().active; Trail.keep(p.panes[asker].?); const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:40:6 line 40 of the file\n", .{path}); defer std.testing.allocator.free(rows); open(p, asker, .list, "Refs", "", rows); const pk = live(p).?; const reader = p.paneBySerial(pk.landing).?; p.update(.tick); const pane = p.panes[reader].?; try std.testing.expectEqualStrings(path, pane.file.?.path); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const s = try p.render(frame.allocator()); const r = p.view().rects[reader]; const body_y = p.bodyTop(pane, r); // Line 40 a third of the way down: ⌈rows/3⌉ rows of context above it. var at: ?u16 = null; for (0..pane.rows) |row| if (pane.wrapAt(p.settings.tab, @intCast(row)).line == 39) { at = @intCast(row); break; }; try std.testing.expectEqual(@as(?u16, @intCast((pane.rows + 2) / 3)), at); const y = body_y + at.?; 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 = 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 = 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); const want = try std.fmt.allocPrint(frame.allocator(), "⏎ lands in @p{d}'s reader · its text is the preview · S-⏎ a new pane", .{p.panes[asker].?.serial}); try std.testing.expect(std.mem.startsWith(u8, said.text, want)); try std.testing.expect(said.quiet_left); try std.testing.expectEqualStrings(try std.fmt.allocPrint(frame.allocator(), "@p{d}", .{p.panes[asker].?.serial}), said.text[said.word[0]..said.word[1]]); // At rest: no ground, no mark, the row back to its own. p.update(.{ .key = .{ .cp = pardes.Key.escape } }); try std.testing.expect(!pardes.Messages.noticeRow(p, 120, &buf).quiet_left); } test "a list of places (a Grep's, a list's) shows each row's `path:line` in the dim ink and its text after it in one column, the widest place shown before it (UX E7 2b)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 40 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const a_path = try testFile(p, &tmp, "a.zig", "one\ntwo\nconst x = 1;\n"); defer p.gpa.free(a_path); const b_path = try testFile(p, &tmp, "a_longer_name.zig", "fn y() void {}\n"); defer p.gpa.free(b_path); _ = try p.setTestFile("held\n"); const asker = p.view().active; Trail.keep(p.panes[asker].?); const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:3:1 const x = 1;\n{s}:1:4 fn y() void {{}}\n", .{ a_path, b_path }); defer std.testing.allocator.free(rows); open(p, asker, .list, "Refs", "", rows); p.update(.tick); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const got = (try steps(p, frame.allocator()))[0].rows; try std.testing.expectEqual(@as(usize, 2), got.len); const code = [2][]const u8{ "const x = 1;", "fn y() void {}" }; var col: [2]usize = undefined; for (got, code, &col) |row, text, *c| { const at = std.mem.indexOf(u8, row.text, text).?; c.* = File.displayWidth(8, row.text[0..at]); // The place dim up to its blank (`path:3:1`); the text after it not. try std.testing.expect(row.pre > 0); try std.testing.expectEqual(@as(u16, 0), row.quiet[0]); try std.testing.expectEqual(':', row.text[row.quiet[1] - 2]); try std.testing.expectEqual(' ', row.text[row.quiet[1]]); } try std.testing.expectEqual(col[0], col[1]); // One cell after the widest place. try std.testing.expectEqual(File.displayWidth(8, b_path) + ":1:4 ".len, col[1]); // As the band draws them, its last step the band's width (UX E3): the // text still in one column. const host = TagState.hostOf(p).?; const band = (try Band.of(p, frame.allocator(), p.panes[host].?, host)).?; const last = band.steps[band.nsteps - 1]; try std.testing.expectEqual(band.columns, last.x + last.width); for (code, &col, 0..) |text, *c, y| { const ln = try band.line(frame.allocator(), p.settings.tab, @intCast(y)); c.* = File.displayWidth(p.settings.tab, ln.text[0..std.mem.indexOf(u8, ln.text, text).?]); } try std.testing.expectEqual(col[0], col[1]); } test "code actions: a row that cannot be applied (a command's, an edit reaching other files) is dim, its meta `command` or `other files`; the edit under the cursor a third of the way down the body (UX E5 12, D7)" { const Key_ = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); p.settings.jumps = .walk; var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); for (1..81) |i| try text.print(std.testing.allocator, "line {d}\n", .{i}); const pane = try p.setTestFile(text.items); const id = p.view().active; // Line 50 starts after lines 1-49. var at: usize = 0; for (1..50) |i| at += std.fmt.count("line {d}\n", .{i}); const rows = try std.fmt.allocPrint(frame.allocator(), "x:1:1 extract\nx:1:1 move to a new file\n@elsewhere\nx:1:1 rename\n@put {d} {d} LINE\n", .{ at, at + 4 }); open(p, id, .actions, "", "", rows); live(p).?.revision = pane.file.?.revision; const got = (try steps(p, frame.allocator()))[0].rows; try std.testing.expectEqual(@as(usize, 3), got.len); try std.testing.expect(got[0].dim); try std.testing.expectEqualStrings("command", got[0].meta); try std.testing.expect(got[1].dim); try std.testing.expectEqualStrings("other files", got[1].meta); try std.testing.expect(!got[2].dim); try std.testing.expectEqualStrings("", got[2].meta); // As the band draws it, its step the band's width (UX E3): the meta // at the band's right end. const band = (try Band.of(p, frame.allocator(), pane, TagState.hostOf(p).?)).?; const ln = try band.line(frame.allocator(), p.settings.tab, 0); try std.testing.expect(std.mem.endsWith(u8, ln.text, " command")); try std.testing.expectEqual(@as(usize, band.columns), File.displayWidth(p.settings.tab, ln.text)); // The rename's: its line (50) a third of the way down the body. p.update(.{ .key = .{ .cp = Key_.down } }); p.update(.{ .key = .{ .cp = Key_.down } }); settle(p); p.sync(); var row_at: ?u16 = null; for (0..pane.rows) |row| if (pane.wrapAt(p.settings.tab, @intCast(row)).line == 49) { row_at = @intCast(row); break; }; try std.testing.expectEqual(@as(?u16, @intCast((pane.rows + 2) / 3)), row_at); } test "a picker previews the row under its cursor from the frame its rows come, when a frame with none came first: a Find's listing, a Grep's lines after their pause (UX D7)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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", "const alpha = 1;\npub fn a() void {}\n"); defer p.gpa.free(a_path); _ = 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 std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); p.stream.engine = .walk; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); // Find, its field empty: a frame before the listing comes (a host's // worker sends it by an input of its own, after the step that asked). open(p, asker, .find, "", "", ""); const reader = p.paneBySerial(live(p).?.landing).?; produceAll(p, true); try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?)); // No rows: no frame owed for a preview. try std.testing.expect(!busy(p)); settle(p); try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?)); try std.testing.expectEqualStrings(a_path, p.panes[reader].?.file.?.path); try std.testing.expectEqual(@as(usize, 0), landingLine(p, frame.allocator(), p.panes[reader].?).?.line); p.update(.{ .key = .{ .cp = Key.escape } }); // Grep: its lines come once the typing pauses, frames with none before. open(p, asker, .grep, "", "", ""); const greader = p.paneBySerial(live(p).?.landing).?; for ("pub") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); p.update(.tick); try std.testing.expectEqual(@as(usize, 0), count(p, live(p).?)); try std.testing.expect(!busy(p)); p.clock.now_ns = p.stream.due_ns.?; settle(p); try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?)); try std.testing.expectEqualStrings(a_path, p.panes[greader].?.file.?.path); try std.testing.expectEqual(@as(usize, 1), landingLine(p, frame.allocator(), p.panes[greader].?).?.line); } test "Backspace on a Messages picker's empty field goes back to the level it was run from, SPC h, unrolled and drawn: its keys are its level's, as every other picker's are" { const Key_ = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); _ = try p.setTestFile("one\ntwo\n"); for (" hm") |c| p.update(.{ .key = .{ .cp = c } }); try std.testing.expectEqual(Source.messages, live(p).?.source); p.sync(); _ = try p.render(frame.allocator()); p.update(.{ .key = .{ .cp = Key_.backspace } }); try std.testing.expect(p.view().prefix == .leader and p.view().tag_state.unrolled); try std.testing.expectEqualStrings("h", p.view().leader_keys[0..p.view().leader_n]); p.sync(); _ = try p.render(frame.allocator()); } test "a picker started in an untouched +New previews in it (UX J1): no pane made, Esc gives it back empty, Enter lands in it, the same pane by its number, reading, its trail starting at the list word; S-Enter there is Enter" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); defer p.gpa.free(b_path); const rows = try std.fmt.allocPrint(p.gpa, "{s}:3:1 three\n", .{b_path}); defer p.gpa.free(rows); _ = try p.setTestFile("first\n"); for ([_]bool{ false, true }) |shift| { exec.runBuiltin(p, .New, 0, "New", null); p.sync(); const scratch = p.view().active; const serial = p.panes[scratch].?.serial; const top = p.view().rects[scratch].y; const npanes = paneCount(p); try std.testing.expect(Trail.untouched(p, p.panes[scratch].?)); open(p, scratch, .list, "Refs", "", rows); settle(p); p.update(.tick); try std.testing.expect(!live(p).?.made); try std.testing.expectEqual(serial, live(p).?.landing); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expectEqualStrings(b_path, p.panes[scratch].?.file.?.path); // Esc: the +New as it was, still free space. p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expect(Trail.untouched(p, p.panes[scratch].?)); try std.testing.expectEqual(serial, p.panes[scratch].?.serial); // Enter (or S-Enter): the file in it. open(p, scratch, .list, "Refs", "", rows); settle(p); p.update(.{ .key = .{ .cp = Key.enter, .shift = shift } }); p.sync(); try std.testing.expect(live(p) == null); const here = p.panes[p.view().active].?; try std.testing.expectEqual(serial, here.serial); try std.testing.expectEqualStrings(b_path, here.file.?.path); try std.testing.expectEqual(@as(i32, 2), here.body.cur_row); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expectEqual(top, p.view().rects[p.view().active].y); try std.testing.expect(Trail.reading(p, here)); try std.testing.expectEqual(@as(u8, 2), here.trail.n); try std.testing.expect(here.trail.steps[0] == .list and here.trail.steps[1] == .place); } } test "a picker from a held pane previews in an untouched +New (UX J1): Esc gives it back empty, Enter makes it the held pane's reader by its number; C-v lands in an empty column rather than making one" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); defer p.gpa.free(b_path); const rows = try std.fmt.allocPrint(p.gpa, "{s}:3:1 three\n", .{b_path}); defer p.gpa.free(rows); _ = try p.setTestFile("held\n"); const held = p.view().active; Trail.keep(p.panes[held].?); exec.runBuiltin(p, .New, held, "New", null); p.sync(); const scratch = p.view().active; const serial = p.panes[scratch].?.serial; p.view().active = held; const npanes = paneCount(p); open(p, held, .list, "Refs", "", rows); settle(p); p.update(.tick); try std.testing.expect(!live(p).?.made); try std.testing.expectEqual(serial, live(p).?.landing); try std.testing.expectEqualStrings(b_path, p.panes[scratch].?.file.?.path); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expect(Trail.untouched(p, p.panes[scratch].?)); open(p, held, .list, "Refs", "", rows); settle(p); p.update(.{ .key = .{ .cp = Key.enter } }); p.sync(); const reader = Trail.readerOf(p, p.panes[held].?).?; try std.testing.expectEqual(serial, p.panes[reader].?.serial); try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); try std.testing.expectEqual(p.panes[held].?.serial, p.panes[reader].?.trail.steps[0].owner); try std.testing.expectEqual(npanes, paneCount(p)); // C-v with an empty column there: the place goes in it. Trail.keep(p.panes[reader].?); const c = layout.insertColumn(p, layout.findPane(p, held).?.col, false).?; p.sync(); const ncol = p.view().ncol; open(p, held, .list, "Refs", "", rows); settle(p); p.update(.{ .key = .{ .cp = 'v', .ctrl = true } }); p.sync(); try std.testing.expectEqual(ncol, p.view().ncol); try std.testing.expectEqual(c, layout.findPane(p, p.view().active).?.col); try std.testing.expectEqualStrings(b_path, p.panes[p.view().active].?.file.?.path); } test "a picker's preview starts under its band: its landing line ⌈visible/3⌉ rows below the band's last row, a file's line 1 on the row right under it; before its first row and after Esc the pane's own text where it was at rest (UX DESIGN I1, W1's reading)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); for (1..121) |i| try text.print(std.testing.allocator, "line {d} of the file\n", .{i}); const path = try testFile(p, &tmp, "long.zig", text.items); defer p.gpa.free(path); var own: std.ArrayList(u8) = .empty; defer own.deinit(std.testing.allocator); for (1..81) |i| try own.print(std.testing.allocator, "own {d}\n", .{i}); const pane = try p.setTestFile(own.items); const id = p.view().active; pane.focus = .body; for ("75j") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); p.sync(); const r = p.view().rects[id]; const rest = .{ pane.tag_rows, pane.rows, pane.file.?.scroll, p.bodyTop(pane, r) }; try std.testing.expect(rest[2] > 0); const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:60:1 line 60 of the file\n{s}:1:1 line 1 of the file\n", .{ path, path }); defer std.testing.allocator.free(rows); open(p, id, .list, "Refs", "", rows); p.sync(); // In the pane itself (it reads), no row shown yet: its text stays. try std.testing.expectEqual(id, p.paneBySerial(live(p).?.landing).?); try std.testing.expect(!previewing(p, id)); try std.testing.expectEqual(rest, .{ pane.tag_rows, pane.rows, pane.file.?.scroll, p.bodyTop(pane, r) }); try std.testing.expect(Band.covered(p, pane, id).over > 0); // The first row shown: the body under the band, line 60 a third of // its rows down. p.update(.tick); try std.testing.expect(previewing(p, id)); try std.testing.expectEqualStrings(path, pane.file.?.path); const at = Band.covered(p, pane, id); try std.testing.expectEqual(@as(u16, 0), pane.view.covered); try std.testing.expectEqual(p.tagTop(pane, r) + at.tag + at.over, p.bodyTop(pane, r)); try std.testing.expectEqual(@as(usize, 59 - (pane.rows + 2) / 3), pane.file.?.scroll); // Line 1: on the row right under the band. p.update(.{ .key = .{ .cp = Key.down } }); p.update(.tick); try std.testing.expectEqual(@as(usize, 0), pane.file.?.scroll); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); // Esc: the pane's own text, where it was at rest. p.update(.{ .key = .{ .cp = Key.escape } }); p.sync(); try std.testing.expect(live(p) == null); 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). _ = try p.render(a); const layer = &p.surface.tag_layers[pardes.BAND_LAYER]; const inks = p.chrome().on(.focus); 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 from the asking pane's directory, as a command runs in its window's (acme; the user's ruling of 2026-11-26 taking W8's work-tree root back): from deep in a repository Find lists that directory alone; from its top `sub/name` narrows Find, and a leading directory, the pane's directory's, narrows Grep" { 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{ ".git", "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: its own file alone, the repository's root not asked. open(p, asker, .find, "", "", ""); var pk = live(p).?; try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(deep).?, pk.dir.slice()); settle(p); try std.testing.expectEqual(@as(usize, 1), count(p, pk)); p.update(.{ .key = .{ .cp = Key.escape } }); // From the top: every file, `sub/name` narrowing them to one. p.gpa.free(p.panes[asker].?.file.?.path); p.panes[asker].?.file.?.path = try std.Io.Dir.path.join(p.gpa, &.{ root, "top.txt" }); open(p, asker, .find, "", "", ""); 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 directory, then `sub needle` in sub/ alone, its // row's path from the pane's directory, 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 } }); } test "a pane made for a picker has no rest: its tag is its owner's word alone, `‹@pN ›`, its body under it; the head hangs under the asking pane's tag (UX DESIGN M3, O1)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; p.stream.engine = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const a_path = try testFile(p, &tmp, "alpha.zig", "const alpha = 1;\n"); defer p.gpa.free(a_path); _ = 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 std.Io.Dir.path.join(p.gpa, &.{ std.Io.Dir.path.dirname(a_path).?, "held.txt" }); const npanes = paneCount(p); open(p, asker, .find, "", "", ""); const pk = live(p).?; try std.testing.expect(pk.made); const reader = p.paneBySerial(pk.landing).?; settle(p); p.update(.tick); try std.testing.expectEqualStrings(a_path, p.panes[reader].?.file.?.path); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const owner = try std.fmt.allocPrint(a, "‹@p{d} › ", .{p.panes[asker].?.serial}); try std.testing.expectEqualStrings(owner, try tagOf(p, a, reader)); const s = try p.render(a); const r = p.view().rects[reader]; var row: std.ArrayList(u8) = .empty; const ra = p.view().rects[asker]; for ([_]struct { y: u16, starts: []const u8 }{ // The tag's row, the owner's word; the body's under it. .{ .y = r.y, .starts = std.mem.trimEnd(u8, owner, " ") }, .{ .y = r.y + 1, .starts = "1▸const alpha" }, // The head under the asker's tag. .{ .y = ra.y + p.panes[asker].?.tag_rows, .starts = "␣ f Find " }, }) |want| { row.clearRetainingCapacity(); for (s.cells[@as(usize, want.y) * s.cols + r.x + pardes.TAG_TEXT_INSET ..][0 .. r.w - pardes.TAG_TEXT_INSET]) |cell| try row.appendSlice(a, cell.grapheme()); try std.testing.expect(std.mem.startsWith(u8, std.mem.trimStart(u8, row.items, " "), want.starts)); } p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(npanes, paneCount(p)); } test "SPC b b from a held pane hangs under that pane's own tag (UX DESIGN O1): no pane made, nothing set aside, the keyboard in its field; a Panes list never names a picker's preview" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); defer p.gpa.free(b_path); _ = try p.setTestFile("held\n"); const held = p.view().active; Trail.keep(p.panes[held].?); exec.runBuiltin(p, .New, held, "New", null); p.view().active = held; p.sync(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const rest = try a.dupe(u8, try tagOf(p, a, held)); const npanes = paneCount(p); for (" bb") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); const pk = live(p).?; try std.testing.expectEqual(Source.panes, pk.source); try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expect(!pk.made); try std.testing.expectEqual(p.panes[held].?.serial, pk.landing); try std.testing.expectEqual(@as(?usize, held), TagState.hostOf(p)); try std.testing.expectEqual(held, p.view().active); try std.testing.expectEqualStrings(rest, try tagOf(p, a, held)); try std.testing.expect(std.mem.startsWith(u8, try headOf(p, a, held), "␣ b Panes ")); settle(p); p.update(.tick); // Nothing previewed, nothing said of a preview: the held pane's own text. try std.testing.expect(pk.aside == null and p.panes[held].?.file.?.output == null); var said: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&said); try std.testing.expect(sentence(p, &w) == null); try std.testing.expectEqual(@as(usize, 2), count(p, pk)); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(npanes, paneCount(p)); // A list from the held pane previews in the untouched +New (UX J1); // switched to Panes, the +New previewing is not among its rows. const rows = try std.fmt.allocPrint(a, "{s}:3:1 three\n", .{b_path}); open(p, held, .list, "Refs", "", rows); settle(p); p.update(.tick); const scratch = p.paneBySerial(live(p).?.landing).?; try std.testing.expect(scratch != held); try std.testing.expectEqualStrings(b_path, p.panes[scratch].?.file.?.path); p.update(.{ .key = .{ .cp = 'h', .alt = true } }); p.update(.{ .key = .{ .cp = 'b', .text = "b" } }); try std.testing.expectEqual(Source.panes, live(p).?.source); try std.testing.expectEqual(@as(usize, 1), count(p, live(p).?)); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(Trail.untouched(p, p.panes[scratch].?)); } test "a picker from a held pane with a reader hangs under the held pane's tag and previews in the reader, whose tag names its own file; Esc gives the reader its text back; switched from Panes, it previews where it would have (UX DESIGN O1)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .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", "const alpha = 1;\n"); defer p.gpa.free(a_path); const b_path = try testFile(p, &tmp, "beta.zig", "one\ntwo\nthree\n"); defer p.gpa.free(b_path); _ = try p.setTestFile("held\n"); const held = p.view().active; Trail.keep(p.panes[held].?); // Its reader: alpha.zig, a Look from it. _ = look.open(p, held, a_path, .{ .line = 1, .col = 1 }, .replace); p.sync(); const reader = Trail.readerOf(p, p.panes[held].?).?; try std.testing.expectEqualStrings(a_path, p.panes[reader].?.file.?.path); p.view().active = held; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const reader_tag = try a.dupe(u8, try tagOf(p, a, reader)); const npanes = paneCount(p); const rows = try std.fmt.allocPrint(a, "{s}:3:1 three\n", .{b_path}); open(p, held, .list, "Refs", "", rows); settle(p); p.update(.tick); const pk = live(p).?; try std.testing.expectEqual(npanes, paneCount(p)); try std.testing.expectEqual(p.panes[reader].?.serial, pk.landing); try std.testing.expectEqual(@as(?usize, held), TagState.hostOf(p)); try std.testing.expectEqualStrings(b_path, p.panes[reader].?.file.?.path); try std.testing.expectEqualStrings(reader_tag, try tagOf(p, a, reader)); try std.testing.expectEqual(@as(i32, 2), p.panes[reader].?.body.cur_row); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqualStrings(a_path, p.panes[reader].?.file.?.path); try std.testing.expect(p.panes[reader].?.file.?.output == null); // Panes first, from the held pane: nothing set aside; then M-h r, // Recent, previews in the reader as a list opened there would. open(p, held, .panes, "", "", ""); try std.testing.expectEqual(p.panes[held].?.serial, live(p).?.landing); p.update(.{ .key = .{ .cp = 'h', .alt = true } }); p.update(.{ .key = .{ .cp = 'r', .text = "r" } }); try std.testing.expectEqual(Source.recent, live(p).?.source); try std.testing.expectEqual(p.panes[reader].?.serial, live(p).?.landing); try std.testing.expectEqual(@as(?usize, held), TagState.hostOf(p)); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqualStrings(a_path, p.panes[reader].?.file.?.path); } test "the landing line's mark shows where Enter lands, the row's own place, not the preview's caret: B1 on another line of the preview moves the caret there and the picker waits, the mark and its ground stay on the row's line; Enter from the field lands there (UX DESIGN O2, D7)" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 50 }); defer p.deinit(); p.settings.jumps = .walk; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); for (1..81) |i| try text.print(std.testing.allocator, "line {d} of the file\n", .{i}); const path = try testFile(p, &tmp, "long.zig", text.items); defer p.gpa.free(path); _ = try p.setTestFile("held\n"); const asker = p.view().active; Trail.keep(p.panes[asker].?); const rows = try std.fmt.allocPrint(std.testing.allocator, "{s}:40:6 line 40 of the file\n", .{path}); defer std.testing.allocator.free(rows); open(p, asker, .list, "Refs", "", rows); const pk = live(p).?; const reader = p.paneBySerial(pk.landing).?; p.update(.tick); const pane = p.panes[reader].?; try std.testing.expectEqual(@as(i32, 39), pane.body.cur_row); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const Shown = struct { // The screen row of the body's line `line` (from 0). fn row(q: *Pardes, t: *Pane, line: usize) u16 { const r = q.view().rects[panes.paneIdOf(q, t).?]; for (0..t.rows) |at| if (t.wrapAt(q.settings.tab, @intCast(at)).line == line) return q.bodyTop(t, r) + @as(u16, @intCast(at)); unreachable; } }; // B1 three lines under the landing line: the caret there, the // keyboard in the reader, the picker waiting. const r = p.view().rects[reader]; const tx = r.x + config.GUTTER; const gutter = File.gutterWidth(pane); const clicked = Shown.row(p, pane, 42); for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| p.update(.{ .mouse = .{ .button = .left, .kind = kind, .col = tx + gutter + 2, .row = clicked } }); try std.testing.expect(live(p) == pk and p.view().tag_state.waits and p.view().active == reader); try std.testing.expectEqual(@as(i32, 42), pane.body.cur_row); // The mark and the hit ground on line 40's row, where Enter lands; // none on the caret's. const s = try p.render(frame.allocator()); const c = p.chrome(); const landing = Shown.row(p, pane, 39); try std.testing.expectEqualStrings("▸", s.at(tx + gutter - 1, landing).grapheme()); try std.testing.expectEqual(pardes.Color{ .rgb = c.hit }, s.at(tx + gutter + 2, landing).style.bg); try std.testing.expect(!std.mem.eql(u8, "▸", s.at(tx + gutter - 1, clicked).grapheme())); try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = c.hit }, s.at(tx + gutter + 2, clicked).style.bg)); // B1 on the head gives the field the keyboard back; Enter lands on // line 40, where the mark was. const at = Band.covered(p, p.panes[asker].?, asker); const ar = p.view().rects[asker]; for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| p.update(.{ .mouse = .{ .button = .left, .kind = kind, .col = ar.x + pardes.TAG_TEXT_INSET + 8, .row = ar.y + at.tag } }); try std.testing.expect(!p.view().tag_state.waits and p.view().active == asker); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(live(p) == null); const landed = p.panes[p.view().active].?; try std.testing.expectEqualStrings(path, landed.file.?.path); try std.testing.expectEqual(@as(i32, 39), landed.body.cur_row); }