//! A picker (pick-ui SPEC.md §5, direction E): a list of places, panes or //! names unrolled in the tag of the pane its Enter lands in (§3.5): the //! asking pane when it reads, else its reader, made for the picker when it //! has none and taken away again by Esc. Its query is typed in that tag's //! field (TagState.field), its rows hang in the band under it (Band.zig) //! eleven at a time around the cursor, and that pane's body 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. //! //! 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). pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, messages, themes, actions }; /// Each source's word in the tag and the leader keys of the builtin that /// opens it, its key cells (`␣ f Find`). 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 = "hm" }, .themes = .{ .word = "Themes", .keys = "t" }, .actions = .{ .word = "Actions", .keys = "la" }, }); /// The pickers kept after they roll up, for their list words and Resume. 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) = .{}, /// The pane that asked, and the one its Enter lands in, 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 host 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, 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, /// The row the preview shows (`no_row`: none yet); asked again on the /// frame after the cursor moves, never on the key that moved it. shown: u32 = no_row, /// 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); `edit`: the field is the act Edit's /// command, the query kept in `query`. spine: enum(u8) { rows, sources, acts, edit } = .rows, /// 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, 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), never a script's word /// (a 9P exec's: the query pane, whose rows it reads back, and whose `not /// found` it hears). pub fn asked(p: *const Pardes) bool { return p.settings.jumps == .walk and (!p.fs.serving or p.fs.typed); } /// 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; } /// A picker of `source` asked from pane `from`, unrolled in the tag of the /// pane its Enter will land in (SPEC §3.5), 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); const pk = make(p, source) catch |err| return p.reportError(.at(from), "pick", err); pk.word.set(if (word.len > 0) word else words.get(source).word); pk.keys.set(words.get(source).keys); pk.dir.set(Pardes.paneDir(asker)); pk.rows = p.gpa.dupe(u8, rows) catch |err| return p.reportError(.at(from), "pick", err); hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "pick", err); if (p.paneBySerial(pk.landing)) |host| pk.cap = p.view().rects[host].h * 2 / 5; 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); } /// A new picker in the ring, the oldest kept one dropped for it. fn make(p: *Pardes, source: Source) !*Pick { var slot: ?usize = null; for (p.picks, 0..) |s, i| if (s == null) { slot = i; break; }; if (slot == null) { // The oldest not live. var oldest: ?usize = null; for (p.picks, 0..) |s, i| if (s) |pk| if (!pk.unrolled and (oldest == null or pk.id < p.picks[oldest.?].?.id)) { 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; return pk; } /// Picker `pk` asked from pane `from`: the pane it lands in is `from` when /// it reads; its reader when it is held and has one; else a pane made under /// it as its reader would be, empty until the preview fills it. The /// keyboard stays where it was: the landing pane is the tag's host. fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void { const asker = p.panes[from].?; pk.owner = asker.serial; pk.made = false; // A theme is no place: its list is the asking pane's own tag (§3.5), // and its preview the whole window; an action's is that text's edit. if (pk.source == .themes or pk.source == .actions) { pk.landing = asker.serial; p.view().active = from; return; } const reader = if (Trail.reading(p, asker)) from else Trail.readerOf(p, asker); pk.landing = p.panes[reader orelse try landingFor(p, from)].?.serial; pk.made = reader == null; p.view().active = from; } /// A pane made under pane `from` for a picker, where its reader goes. 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: its host its landing pane, 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.landing; s.field.set(query); s.rows = .{ .at = @intCast(@min(pk.at, std.math.maxInt(u16))) }; pk.unrolled = true; pk.shown = no_row; // 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), .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)) return pk.names.typed(p.gpa, q); if (pk.source == .grep) { pk.found.clearRetainingCapacity(); pk.found_bytes.clearRetainingCapacity(); if (q.len > 0) { Stream.query(p, pk.id, .grep, q, pk.dir.slice(), if (p.fs.serving) .now else .typed) catch |err| return p.reportError(.at(p.view().active), "pick", err); 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; Query.take(p, pk, kind, rows); // 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); }; } /// After every step: each live picker's names scored on (a frame's count), /// and on a frame of its own after the cursor stood, the preview of the /// current row. pub fn produceAll(p: *Pardes, tick: bool) void { for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { if (pk.names.busy()) pk.names.rescore(p.gpa); // 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 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) { if (pk.names.busy() or (pk.previews and pk.shown != p.view().tag_state.rows.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, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" }; fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { 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)); const path = 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); row.target = .{ .place = .{ .path = try std.Io.Dir.path.join(arena, &.{ dir, name }), .at = .{ .line = 1, .col = 1 } } }; }, .panes => { row.pre = cand.key -| 1; row.dim = p.paneBySerial(cand.ref) == null; row.target = .{ .pane = cand.ref }; }, .symbols => { row.pre = 6; 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 } } }; }, // 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 of the landing pane's tag (SPEC §5.3): the key cells, the /// source's word, the query, the count `cursor/total` and `•marked`; on a /// second row the other sources' words, under spines from the key cells. 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()); try text.appendSlice(arena, pk.word.slice()); try text.append(arena, ' '); for (pk.refined[0..pk.nrefined]) |r| try text.print(arena, "{s} | ", .{r.query.slice()}); 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 and actions have no acts and no other sources: no second row. if (pk.source == .themes or pk.source == .actions) { const hints = text.items.len; try b.styled(if (pk.source == .themes) "⏎ wear it · esc" else "⏎ or 1-9 apply it · esc", .dim); try b.right(counted, hints); var h = b.done(); h.caret = caret; return h; } try b.right(counted, text.items.len); // The second row, one row (UX D2): under the spines from the key // cells, from two cells right of the last, the acts, `|`, the other // sources' words, each switching to it, the `|` and the sources dim // (UX D4); what does not fit is dropped from the right (the sources // first) and the row ends in a dim `…` (M-l and M-h reach them all). try b.row(if (b.ncols > 0) b.cols[b.ncols - 1] + 2 else 0); var offer: [acts.len + 1 + std.enums.values(Source).len][]const u8 = undefined; var nw: usize = 0; for (acts) |act| if (offered(pk, act)) { offer[nw] = act.word; nw += 1; }; const nacts = nw; offer[nw] = "|"; nw += 1; inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .messages and src != .themes and src != .actions and src != pk.source) { offer[nw] = words.get(src).word; nw += 1; }; for (offer[0..nw], 0..) |word, i| { const gap: usize = @intFromBool(i > 0); const rest: usize = if (i + 1 < nw) 2 else 0; if (b.col() + gap + File.displayWidth(p.settings.tab, word) + rest > b.width) { try b.put(if (gap > 0) " " else ""); try b.styled("…", .dim); break; } try b.put(if (gap > 0) " " else ""); if (i >= nacts) try b.styled(word, .dim) else try b.put(word); } var h = b.done(); h.caret = caret; return h; } /// The band's rows (UX D6): as many as the list will show, from what the /// source has (not what the query keeps: typing never moves the body), /// four at least, eleven at most, and its `cap` at most (the host 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 have = if (!fuzzy(pk)) Band.Cursor.shown else pk.names.cands.items.len; const rows: usize = @max(1, @min(Band.Cursor.shown, @max(4, have), 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); }, .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) 2 else 1); if (pk.spine == .acts) out[1] = try actStep(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, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i), .meta = r.meta }; } // 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; } // ---- the preview ---- /// The line (from 0) 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. pub fn landingLine(p: *Pardes, arena: std.mem.Allocator, pane: *const Pane) ?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 (pk.shown != s.rows.at or count(p, pk) == 0) 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 = pane.file orelse return null; if (!std.mem.eql(u8, f.path, place.path)) return null; return @intCast(@max(0, pane.body.cur_row)); } /// 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) 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. fn preview(p: *Pardes, pk: *Pick) void { const s = &p.view().tag_state; if (pk.shown == s.rows.at or !pk.previews) return; pk.shown = s.rows.at; if (count(p, pk) == 0) return; 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; if (!std.mem.eql(u8, f.path, place.path)) { if (exec.kindOf(p.tape, place.path)) |kind| if (kind != .file) return; const bytes = openText(p, place.path) orelse (p.tape.site(.preview, p.gpa, filesystem.read, .{ p, place.path }) catch return); if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { p.gpa.free(bytes); return; } const path = p.gpa.dupe(u8, place.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; p.sync(); } 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) pane.places.search(p, pane, .list, pk.id, std.mem.trim(u8, s.field.text(), " "), true, null, false); } /// 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) { 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 (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.sync(); } /// 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()); pk.spine = .rows; pk.at = s.rows.at; pk.unrolled = false; 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 grounds = colors.Grounds.of(p.theme()); const ink = p.theme().fg orelse p.theme().tag_fg; 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 = grounds.add.row } }); _ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = grounds.add.row } }); out += 1; }; } } if (out >= rows) break; @memcpy(s.cells[(y0 + out) * w ..][0..w], old[(vr - first) * w ..][0..w]); if (g < groups.items.len and line >= groups.items[g].lo and line < groups.items[g].hi) s.tint(x0, @intCast(y0 + out), width, grounds.del.row, null); 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); // Themes: Enter wears the one under the cursor; actions: Enter, or an // action's digit with the field empty, applies it; the rows and the // field. if (pk.source == .themes or pk.source == .actions) { if (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; } 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 (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); } /// 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 = "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); }; 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(); pk.source = to; pk.word.set(words.get(to).word); pk.keys.set(words.get(to).keys); 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; } } 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; } 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; } /// 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, std.mem.trimStart(u8, row.text, " 0123456789") }) 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). fn land(p: *Pardes, how: 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; // Walk: the first now, the others queued for C-i. pk.queue.clearRetainingCapacity(); pk.queue_bytes.clearRetainingCapacity(); pk.queue_at = 0; if (how == .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 => {}, }; // 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. const landing = if (pk.made) null else p.paneBySerial(pk.landing); TagState.toRest(p); const v = p.view(); const owner = p.paneBySerial(pk.owner) orelse v.active; const from = if (how == .walk or how == .queue) landing orelse owner 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)) { switch (look.open(p, from, at.path, at.at, .replace)) { .none => {}, else => listed(p, pk), } } else if (k == 0 and how == .column) { layout.newColumn(p, from); const c = layout.activeColumn(p) orelse continue; p.exec_column = c; 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 (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 {}; 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(); } /// The list rolled into the trail of the reading pane it landed in, its /// word before the place: the list `n` and `N` walk there. fn listed(p: *Pardes, pk: *const Pick) void { const pane = p.panes[p.view().active] orelse return; if (!Trail.reading(p, pane)) 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): the list unrolled /// again in that pane's tag, its rows, marks, cursor and query as they were. pub fn reopen(p: *Pardes, id: usize, index: u32) void { 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); pk.landing = pane.serial; pk.made = false; unroll(p, pk, pk.query.slice()); unrollRows(p, pk); } /// 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()); open(p, id, pk.source, pk.word.slice(), query.slice(), pk.rows); } /// Resume (`SPC '`): the last picker reopened as it was, from pane `from`, /// in the tag of the pane its Enter lands in. pub fn resumeFrom(p: *Pardes, from: usize) void { var newest: ?*Pick = null; for (p.picks) |slot| if (slot) |pk| if (newest == null or pk.id > newest.?.id) { newest = pk; }; const pk = newest orelse return p.setMessage(.at(from), "Resume: no picker yet"); TagState.toRest(p); if (p.panes[from] == null) return; hostIn(p, pk, from) catch |err| return p.reportError(.at(from), "Resume", err); unroll(p, pk, pk.query.slice()); unrollRows(p, pk); } /// B3 on a picker's row (mouse.zig bandPress): Enter on it. pub fn landHere(p: *Pardes) void { const pk = live(p) orelse return; if (pk.spine == .rows) land(p, .walk); } /// 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; 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].?); } 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 unrolls in a reader made for it: its rows in the band, the body the current row's file, Esc takes the reader away" { 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; its tag is the picker's. 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, reader), TagState.hostOf(p)); try std.testing.expectEqual(asker, p.view().active); 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(); const tag = try tagOf(p, a, reader); // Out of rest no path (UX D1): not the previewed file's, not Keep; // the head starts the tag's text. const first = tag[0..std.mem.indexOfScalar(u8, tag, '\n').?]; try std.testing.expect(std.mem.startsWith(u8, first, "␣ f Find pick ") and std.mem.endsWith(u8, first, " 1/1")); try std.testing.expect(std.mem.indexOf(u8, tag, "│ Walk Look Split Newcol Grep Edit Copy Keep Drop | Grep Recent Panes Symbols All Jumplist") != 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[reader]; try std.testing.expectEqualStrings("^", p.surface.at(r.x, r.y).grapheme()); try std.testing.expect(p.panes[reader].?.band_rows >= 1); // 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 act row is one row under the spines, two cells right of the last: what does not fit dropped from the right, the sources first, a dim `…` ending it" { 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.stream.engine = .walk; open(p, asker, .find, "", "", ""); const reader = p.paneBySerial(live(p).?.landing).?; var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const tag = try tagOf(p, a, reader); var rows = std.mem.splitScalar(u8, tag, '\n'); try std.testing.expect(std.mem.startsWith(u8, rows.next().?, "␣ f Find ")); const acts_row = rows.next().?; try std.testing.expect(rows.next() == null); try std.testing.expect(std.mem.startsWith(u8, acts_row, "│ │ Walk Look ")); try std.testing.expect(std.mem.endsWith(u8, acts_row, " …")); try std.testing.expect(File.displayWidth(p.settings.tab, acts_row) <= pardes.tagline.tagWidth(p, reader)); const h = (try head(p, a, p.panes[reader].?)).?; try std.testing.expect(h.spans[h.spans.len - 1].style == .dim); } test "a picker's band is sized from its list at open, 4 rows at least, and typing never moves it" { 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 = p.paneBySerial(live(p).?.landing).?; p.sync(); const rows = p.panes[reader].?.band_rows; // One or two files listed: four rows, ground under them. try std.testing.expectEqual(@as(u16, 4), 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, p.panes[reader].?.band_rows); } test "a picker's band is capped once at open at 40 % of its host pane's rows; the host borrows from its column for a body of 60 % before the band gives way: a Grep from a held pane at 100x30 previews 8 rows at least" { 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(); open(p, asker, .grep, "", "", ""); const reader = p.paneBySerial(live(p).?.landing).?; const at_open = p.view().rects[reader].h; for ("pub fn") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); settle(p); p.update(.{ .key = .{ .cp = Key.down } }); p.sync(); const pane = p.panes[reader].?; const r = p.view().rects[reader]; try std.testing.expectEqual(@min(Band.Cursor.shown, at_open * 2 / 5), pane.band_rows); try std.testing.expect(r.h - pane.tag_rows >= 8); try std.testing.expect(@as(u32, r.h - pane.tag_rows) * 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 tagOf(p, frame.allocator(), id); try std.testing.expect(std.mem.indexOf(u8, refs, " Refs ") != null and std.mem.indexOf(u8, refs, " 3/4 •1\n") != null); 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 tagOf(p, frame.allocator(), id); try std.testing.expect(std.mem.indexOf(u8, refined, " Refs alpha | w ") != null and std.mem.indexOf(u8, refined, " 1/1\n") != null); // 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); 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); 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 grounds = colors.Grounds.of(p.theme()); for ([_][]const u8{ "o", "t", "t", "t" }, [_][]const u8{ "n", "w", "w", "h" }, 0..) |c0, c1, row| { try std.testing.expectEqualStrings(c0, shot.at(x, y + @as(u16, @intCast(row))).grapheme()); try std.testing.expectEqualStrings(c1, shot.at(x + 1, y + @as(u16, @intCast(row))).grapheme()); } try std.testing.expectEqualStrings("a", shot.at(x + 4, y + 1).grapheme()); try std.testing.expectEqualStrings("s", shot.at(x + 4, y + 2).grapheme()); try std.testing.expectEqual(pardes.Color{ .rgb = grounds.del.row }, shot.at(x, y + 1).style.bg); try std.testing.expectEqual(pardes.Color{ .rgb = grounds.add.row }, shot.at(x, y + 2).style.bg); try std.testing.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 = grounds.add.row }, shot.at(x, y).style.bg); try std.testing.expectEqualStrings("o", shot.at(x, y + 1).grapheme()); try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = grounds.del.row }, shot.at(x, y + 1).style.bg)); try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.chromeTheme().roles.hit }, shot.at(x, y + 1).style.bg)); // `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 roles = &p.chromeTheme().roles; const on = roles.selectedOn(if (pardes.Trail.reading(p, pane)) .reading_focused else .focused); 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 roles = &p.chromeTheme().roles; const tx = r.x + pardes.config.GUTTER; const gutter = File.gutterWidth(pane); // Its text on the hit ground across the row; the row above as it was. for (gutter..r.w - pardes.config.GUTTER) |x| try std.testing.expectEqual(pardes.Color{ .rgb = roles.hit }, s.at(tx + @as(u16, @intCast(x)), y).style.bg); try std.testing.expect(!std.meta.eql(s.at(tx + gutter + 2, y - 1).style.bg, pardes.Color{ .rgb = roles.hit })); // `▸` in the key ink in the gutter's cell after the number. const mark = s.at(tx + gutter - 1, y); try std.testing.expectEqualStrings("▸", mark.grapheme()); try std.testing.expectEqual(pardes.Color{ .rgb = roles.key }, mark.style.fg); // 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); }