From 51903dd947f90381d1a908c488a019289a1c8413 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 11:57:26 -0300 Subject: Search converge 3/6: the query pane, line 1 the query and its first word the source, rows made live like Callstack's, the owner's places showing the set, a +Preview promoted in place, Enter freezes, Esc restores --- src/Query.zig | 2155 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 2155 insertions(+) create mode 100644 src/Query.zig (limited to 'src/Query.zig') diff --git a/src/Query.zig b/src/Query.zig new file mode 100644 index 00000000..fbce95b2 --- /dev/null +++ b/src/Query.zig @@ -0,0 +1,2155 @@ +//! The query pane: the one pane search is. A +Search attached under the +//! pane that asked (its owner, layout.zig "Attached panes"), born at a +//! fixed height, whose body's line 1 is the query, editable text, and +//! whose rows below are made live from a source, read-only while live. +//! Line 1's first word names the source: `/pat` the owner's text (smart- +//! case regex), `Find pat` the files under its directory, `Grep pat` the +//! lines of those files, `Recent pat`, `Panes pat`, `Symbols pat` (the +//! owner's declarations), `All pat` (every open pane's text), and the +//! language server's `Refs`, `Def`, `Impl`, `Diagnostics`. Names are +//! matched fuzzy (Names.zig), text by regex. Editing the word changes +//! the source. +//! +//! The rows look like a Callstack's: the hit line with the match tinted +//! under a gutter line number, under the declaration it is in (when the +//! owner's parse exists: never made here on the loop), under its file +//! (Grep) or under `@pN name (count)` (All). They are addresses, all text: +//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into +//! an open pane's text, that pane's places (Places.zig) show the set: +//! tints, rail ticks, the current one selected. A row pointing at a file +//! no pane shows is shown in the +Preview attached under this pane; Enter +//! promotes the preview to the file's pane where it stands. +//! +//! Nothing moves while you type: the pane never closes, resizes or +//! rewrites line 1 on its own; zero hits is a state (`0` in the tag). +//! Enter lands on the current hit and freezes the rows into ordinary text; +//! Esc while typing puts every view back and closes the pane (or brings a +//! reused pane's frozen rows back); Del closes it. One per owner, reused +//! (SearchPane reuse|new). +const Query = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const edit = @import("edit.zig"); +const exec = @import("exec.zig"); +const layout = @import("layout.zig"); +const locations = @import("locations.zig"); +const look = @import("look.zig"); +const modal = @import("modal.zig"); +const normal = @import("normal.zig"); +const syntax = @import("syntax.zig"); +const tagline = @import("tagline.zig"); +const filesystem = @import("fs.zig"); +const colors = @import("colors.zig"); +const memory = @import("memory.zig"); +const Names = @import("Names.zig"); +const Places = @import("Places.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; +const Output = panes.Output; +const Key = pardes.Key; +const hit = pardes.hit; + +pub const Source = enum { text, find, grep, recent, panes, symbols, all, refs, defs, impls, diagnostics }; + +/// Line 1's words, each the source it names. `/` is vim's spelling, no +/// space after it; the others take one. +pub const words = [_]struct { word: []const u8, source: Source }{ + .{ .word = "Find", .source = .find }, + .{ .word = "Grep", .source = .grep }, + .{ .word = "Recent", .source = .recent }, + .{ .word = "Panes", .source = .panes }, + .{ .word = "Symbols", .source = .symbols }, + .{ .word = "All", .source = .all }, + .{ .word = "Refs", .source = .refs }, + .{ .word = "Def", .source = .defs }, + .{ .word = "Impl", .source = .impls }, + .{ .word = "Diagnostics", .source = .diagnostics }, +}; + +/// What a line 1 asks: its source and what follows its word. Null when it +/// starts with no word this knows (the user rewrote it): the rows say so. +pub fn parse(line: []const u8) ?struct { source: Source, pat: []const u8 } { + if (line.len > 0 and line[0] == '/') return .{ .source = .text, .pat = line[1..] }; + for (words) |w| { + if (std.mem.startsWith(u8, line, w.word) and (line.len == w.word.len or line[w.word.len] == ' ')) + return .{ .source = w.source, .pat = std.mem.trim(u8, line[w.word.len..], " \t") }; + } + return null; +} + +/// The word line 1 starts with for `source`, as typed after it. +pub fn wordOf(source: Source) []const u8 { + if (source == .text) return "/"; + for (words) |w| if (w.source == source) return w.word; + unreachable; +} + +/// A source whose rows can point at files no pane shows: its group is +/// made with a +Preview from the start, so nothing moves later. +fn previews(source: Source) bool { + return switch (source) { + .find, .grep, .recent, .refs, .defs, .impls, .diagnostics => true, + .text, .panes, .symbols, .all => false, + }; +} + +/// The most rows of hits a frozen list keeps: the rest are counted, and +/// said in a row. +pub const max_rows = 2000; +/// While typed, the rows are a window of this many around the current +/// place: the pane shows a few, and a row is two allocations a refill. +pub const live_rows = 100; + +/// One row's model, row `i + 1` of the pane (line 1 is the query): a hit, +/// a header (a declaration, a file, a pane) or a note. Where a row points +/// is in its locations.Row (path, at); a hit in an open pane's text also +/// knows its places there, `hit` and the `n` of them on its line. +pub const Item = struct { + kind: enum { hit, header, note }, + /// The pane whose text it is in (by serial), 0 when it is a file's. + serial: u32 = 0, + hit: usize = 0, + n: usize = 0, + /// A Panes row's pane, a Symbols row's line: Names.Cand.ref. + ref: u32 = 0, +}; + +/// A line a Grep found: its path and code in `found_bytes`. +pub const Found = struct { path: u32, path_len: u16, line: u32, col: u32, end: u32, code: u32, code_len: u32 }; + +/// The pane it answers for, by serial. +owner: u32, +/// Line 1 as the rows were last made for (gpa). +asked: []u8 = &.{}, +source: Source = .text, +/// Enter answered it: its rows are ordinary text from here, nothing remade. +frozen: bool = false, +items: std.ArrayList(Item) = .empty, +/// The current item, which Enter lands on and the places show. +current: ?usize = null, +/// The tag's `k/N`: how many places or names the rows are of, and where +/// the current one is among them (1-based; 0, none); `more` while counting. +total: usize = 0, +k: usize = 0, +more: bool = false, +/// What the rows were made of: the places' or names' generation and the +/// owner's text, so that a frame with nothing new makes nothing. +made_gen: u64 = std.math.maxInt(u64), +made_rev: u32 = 0, +/// The owner's revision seen last tick: rows follow an edit of the owner +/// once it has stood a frame (the rows refresh on idle frames). +seen_rev: u32 = 0, +/// The body cursor's row as last seen: B1, j or k on a row makes it current. +seen_row: i32 = 0, +/// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits. +window: struct { lo: usize = 0, hi: usize = 0 } = .{}, +/// Ticks the rows waited while the places are still being found: they are +/// made every third, the frame's time going to the finding. +waited: u8 = 0, +names: Names = .{}, +/// A Grep's lines, found a slice a frame (Query.grepSlice). +found: std.ArrayList(Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +grep_next: usize = 0, +grep_gen: u32 = 0, +/// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave +/// them (`path:line:col text`, gpa), filtered by what follows the word. +lsp_rows: []u8 = &.{}, +/// The +Preview under this pane, by serial; 0, none. +preview: u32 = 0, +/// A reused pane's frozen rows when a new query began in it: Esc brings +/// them back. +saved: ?Saved = null, + +pub const Saved = struct { + content: []u8, + rows: []locations.Row, + asked: []u8, + source: Source, + items: []Item, + current: ?usize, + total: usize, + k: usize, +}; + +pub fn deinit(q: *Query, gpa: std.mem.Allocator) void { + gpa.free(q.asked); + q.items.deinit(gpa); + q.names.deinit(gpa); + q.found.deinit(gpa); + q.found_bytes.deinit(gpa); + gpa.free(q.lsp_rows); + if (q.saved) |s| freeSaved(gpa, s); + q.* = undefined; +} + +fn freeSaved(gpa: std.mem.Allocator, s: Saved) void { + gpa.free(s.content); + locations.freeRows(gpa, s.rows); + gpa.free(s.asked); + gpa.free(s.items); +} + +/// The query pane `pane` is, if it is one. +pub fn of(pane: *Pane) ?*Query { + return pane.query; +} + +/// The owner's query pane (attached to it, or left where it was by +/// SearchPane new): the one a later search from it reuses. +pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize { + var found: ?usize = null; + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.owner != owner_serial) continue; + // the attached one first: an unattached one is a kept result + if (pane.attached_to == owner_serial) return i; + found = found orelse i; + } + return found; +} + +fn lineOne(content: []const u8) []const u8 { + return content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; +} + +// ---- opening ---- + +/// A search from pane `from`: its owner's query pane, made under the owner +/// (with a +Preview when `source` can need one) or reused, line 1 the +/// source's word and `arg`. With `focus` the keyboard goes to line 1's end +/// in insert mode, as to a prompt; without (`*`), it stays where it is. +pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: bool) void { + const asker = p.panes[from] orelse return; + // Asked from a query pane (`/` in it, its own SPC f g): its own line 1; + // from a +Preview, its query pane's. + var owner_id = from; + if (asker.query) |q| owner_id = p.paneBySerial(q.owner) orelse from else if (isPreview(p, asker)) |qid| { + owner_id = p.paneBySerial(p.panes[qid].?.query.?.owner) orelse from; + } + const owner = p.panes[owner_id] orelse return; + if (asker.query != null and arg.len == 0 and asker.query.?.source == source and !asker.query.?.frozen) { + // Back to typing the query it has. + if (focus) toLineOne(p, from); + return; + } + const line = std.mem.concat(p.scratch.allocator(), u8, &.{ wordOf(source), if (source == .text) "" else " ", arg }) catch return; + var id: usize = undefined; + const existing = ofOwner(p, owner.serial); + if (existing != null and (p.settings.search_pane == .reuse or existing.? == from)) { + id = existing.?; + const rp = p.panes[id].?; + const q = rp.query.?; + // Its frozen rows, kept for an Esc to bring back. + if (q.frozen and q.saved == null) q.saved = save(p, rp, q) catch null; + q.frozen = false; + const f = &rp.file.?; + const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return; + File.setContent(p, f, new); + q.reset(p); + if (rp.collapsed) layout.toggleCollapse(p, id); + } else { + if (existing) |old| { + // SearchPane new: the last one stays where it is, a result of + // its own; its places are the new one's to feed. + p.panes[old].?.attached_to = null; + } + id = create(p, owner_id, line, source) orelse return; + } + // Every view as the search found it, for Esc to put back. + owner.places.remember(p, owner); + // Before the first key: a names source lists every candidate at once. + produce(p, id, false); + // What a 9P exec reads back: the pane it filled (ninep/ctl.zig). + p.fs.refilled = p.panes[id].?.serial; + if (focus) toLineOne(p, id) else p.active = from; +} + +/// A new query pane under pane `owner_id`, `rows` of the owner's rows (the +/// SearchRows setting), its +Preview under it when `source` can need one. +fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize { + const owner = p.panes[owner_id] orelse return null; + const free = p.freeSlot() orelse { + p.reportError(owner_id, "search", error.NoPaneSlots); + return null; + }; + const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(owner); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return null; + const np = Output.open(p, free, dir, .search, "", content) catch |err| { + p.gpa.free(content); + p.reportError(owner_id, "search", err); + return null; + }; + const q = p.gpa.create(Query) catch { + p.reportError(owner_id, "search", error.OutOfMemory); + return null; + }; + q.* = .{ .owner = owner.serial }; + np.query = q; + const body: u16 = 1 + p.settings.search_rows; + const tag = @max(pardes.BOX_H, np.tag_rows); + const with_preview = previews(source); + // The preview, made right after, takes its own rows from the owner. + const want = tag + body; + if (p.settings.search_place == .column) { + // The finder column (phase 6): until it exists, under the owner. + if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + } else if (!layout.attach(p, owner_id, free, want)) { + // An owner too short to give a query pane its rows: placed as any + // new pane is, the one place a search moves another pane. + exec.placeNew(p, owner_id, owner_id, free, .doc); + } + if (with_preview) _ = makePreview(p, free); + return free; +} + +/// The keyboard to the end of line 1 of query pane `id`, in insert mode. +pub fn toLineOne(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + tagline.exitHeader(p); + p.active = id; + if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col); + rp.focus = .body; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + t.cur_row = 0; + t.cur_col = @intCast(lineOne(rp.file.?.content).len); + t.vsel.active = false; + t.nsel = 0; + t.cur_pinned = true; + rp.query.?.seen_row = 0; + edit.enterInsert(p, t, .line_end, 1); + showCurrent(rp); +} + +/// The rows' state for a new question: nothing found yet. +fn reset(q: *Query, p: *Pardes) void { + q.items.clearRetainingCapacity(); + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + q.made_gen = std.math.maxInt(u64); + p.gpa.free(q.asked); + q.asked = &.{}; +} + +fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { + const f = &rp.file.?; + const content = try p.gpa.dupe(u8, f.content); + errdefer p.gpa.free(content); + const rows = try p.gpa.alloc(locations.Row, f.location_rows.len); + var made: usize = 0; + errdefer { + for (rows[0..made]) |r| { + p.gpa.free(r.path); + p.gpa.free(r.colors); + } + p.gpa.free(rows); + } + for (f.location_rows, 0..) |r, i| { + rows[i] = r; + rows[i].path = try p.gpa.dupe(u8, r.path); + rows[i].colors = p.gpa.dupe(u8, r.colors) catch |err| { + p.gpa.free(rows[i].path); + return err; + }; + made += 1; + } + const asked = try p.gpa.dupe(u8, q.asked); + errdefer p.gpa.free(asked); + return .{ .content = content, .rows = rows, .asked = asked, .source = q.source, .items = try p.gpa.dupe(Item, q.items.items), .current = q.current, .total = q.total, .k = q.k }; +} + +// ---- making the rows ---- + +/// After every step: each live query pane whose line 1 changed, or whose +/// source has something new, has its rows made again. A walk takes a slice +/// on a tick. Nothing here is synchronous with an edit of the owner: its +/// places shift (Places.shift) and the rows follow once it stands a frame. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + if (pane.query == null) continue; + produce(p, id, tick); + } +} + +/// The frames a query pane still owes (a walk, scoring): nextWake's. +pub fn busy(p: *const Pardes) bool { + for (p.panes) |slot| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.frozen) continue; + if (q.names.busy() or (q.source == .grep and q.grep_next < q.names.cands.items.len) or q.made_rev != q.seen_rev) return true; + } + return false; +} + +fn produce(p: *Pardes, id: usize, tick: bool) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const f = if (rp.file) |*file| file else return; + const line = lineOne(f.content); + const changed = !std.mem.eql(u8, line, q.asked); + if (q.frozen and !changed) return; + if (q.frozen) { + // Line 1 of a frozen pane edited: it is a live query again. + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + q.frozen = false; + } + const owner_id = p.paneBySerial(q.owner); + const asked = parse(line); + if (changed) { + const was = q.source; + const new_asked = p.gpa.dupe(u8, line) catch return; + p.gpa.free(q.asked); + q.asked = new_asked; + q.made_gen = std.math.maxInt(u64); + if (asked) |a| { + if (a.source != was or q.names.cands.items.len == 0) startSource(p, id, q, a.source, owner_id); + q.source = a.source; + } + // The places this fed are another question's now. + if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked); + } + const a = asked orelse return noteRows(p, id, " line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n"); + // A row clicked or stepped onto (B1, j, k): current, and shown. + if (rp.body.cur_row != q.seen_row) { + q.seen_row = rp.body.cur_row; + if (rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { + const i: usize = @intCast(rp.body.cur_row - 1); + if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true); + } + } + switch (a.source) { + .text => { + const oid = owner_id orelse return noteRows(p, id, " the pane this searched is gone: Del, or / in another\n"); + const owner = p.panes[oid].?; + const of_ = owner.file orelse return noteRows(p, id, " a terminal's text is not searched here yet: / in a file\n"); + const set = &owner.places; + if (changed) { + if (a.pat.len == 0) { + if (set.from == rp.serial) set.clear(p.gpa); + set.restore(p, owner); + } else set.search(p, owner, .typed, rp.serial, a.pat, false, set.origin(owner), p.active == id); + } + // The owner edited: its places shifted at once; the rows follow + // once its text has stood a frame. + if (!changed and of_.revision != q.made_rev) { + if (!tick or of_.revision != q.seen_rev) { + q.seen_rev = of_.revision; + return; + } + } + q.seen_rev = of_.revision; + const gen: u64 = (@as(u64, set.hits_gen) << 32) | of_.revision; + if (gen == q.made_gen and !changed) return showPlacesCurrent(p, id); + if (a.pat.len > 0 and set.from != rp.serial) return; + if (!changed and !set.complete() and q.made_gen != std.math.maxInt(u64) and q.waited < 2) { + q.waited += 1; + return showPlacesCurrent(p, id); + } + q.waited = 0; + q.made_gen = gen; + q.made_rev = of_.revision; + makeTextRows(p, id, oid, false) catch |err| p.reportError(id, "search", err); + }, + .all => { + if (changed) for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (a.pat.len == 0) { + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + continue; + } + tp.places.search(p, tp, .list, rp.serial, a.pat, false, null, false); + }; + var gen: u64 = 0; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial) { + gen +%= tp.places.hits_gen +% (@as(u64, tp.serial) << 20); + }; + if (gen == q.made_gen and !changed) return; + if (!changed and !tick) return; + q.made_gen = gen; + makeAllRows(p, id) catch |err| p.reportError(id, "search", err); + }, + .find, .recent, .panes, .symbols => { + if (tick) q.names.walkSlice(p.gpa); + if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa); + if (q.names.gen == q.made_gen and !changed) return; + q.made_gen = q.names.gen; + makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + .grep => { + if (changed) { + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + q.grep_gen +%= 1; + } + if (a.pat.len == 0) { + if (changed) makeGrepRows(p, id) catch {}; + return; + } + if (tick or changed) { + q.names.walkSlice(p.gpa); + grepSlice(p, q, rp, a.pat); + } + const gen: u64 = (@as(u64, q.grep_gen) << 32) | q.found.items.len; + if (gen == q.made_gen and !changed and !(q.grep_next >= q.names.cands.items.len and q.more)) return; + q.made_gen = gen; + makeGrepRows(p, id) catch |err| p.reportError(id, "search", err); + if (changed or q.current == null) feedGrepPlaces(p, q, rp.serial, a.pat); + }, + .refs, .defs, .impls, .diagnostics => { + if (changed and q.lsp_rows.len == 0) { + // Typed, not answered: asked of the language server at the + // owner's cursor; its answer fills these rows (fillList). + // An answer opening the pane is no typing. + if (p.active != id) return; + if (owner_id) |oid| p.lspRequest(oid, switch (a.source) { + .refs => .references, + .defs => .definition, + .impls => .implementation, + else => .diagnostics, + }, ""); + return noteRows(p, id, " asked of the language server...\n"); + } + if (!changed) return; + makeListRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + } +} + +/// Whether pane `tp`'s text is one All searches: a file's or a list's, +/// not a query pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// A source begun: its candidates gathered (names), its walk started. +fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usize) void { + const rp = p.panes[id].?; + q.names.reset(); + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const gpa = p.gpa; + switch (source) { + .find, .grep => q.names.startWalk(gpa, dir) catch |err| p.reportError(id, "search", err), + .recent => { + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + Output.recentText(p, &out.writer, true) catch {}; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |ln| { + if (ln.len == 0) continue; + const rel = Names.relative(ln, dir); + const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len; + q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; + } + }, + .panes => for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + }, + .symbols => { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const f = if (owner.file) |*file| file else return; + const decls = ownerDecls(p, f, true) orelse return; + for (decls) |d| { + const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)]; + const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); + var buf: [256 + 16]u8 = undefined; + const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue; + q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; + } + }, + else => {}, + } +} + +/// The owner's declarations, from a parse that already exists: its sticky +/// headers' (TreeContext) at this revision, or the locations cache's. None +/// is made here, on the loop, unless `small` and the text is small: a +/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build. +/// ponytail: no grouping for a big file until the disk engine's worker +/// parses it (phase 4). +fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { + if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations; + const cache = &p.locations_cache; + for (cache.entries[0..cache.len]) |entry| { + if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; + } + if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null; + var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null; + if (got.owned) { + got.deinit(p.tree_sitter_gpa); + return null; + } + return got.analysis.declarations; +} + +/// A text this small is parsed on the loop for its declarations when a +/// Symbols query asks (about 40 ms in a Debug build). +const small_parse_bytes = 64 << 10; + +/// The rows as `note` says, and nothing else: no hits. +fn noteRows(p: *Pardes, id: usize, note: []const u8) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.items.append(p.gpa, .{ .kind = .note }) catch return; + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + writeRow(p, &out, &rows, note[0 .. note.len - 1], .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }) catch return; + setRows(p, rp, &out, &rows); +} + +/// One row: its text and its metadata, the path copied. +fn writeRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8, meta: locations.Row) !void { + try out.appendSlice(p.gpa, text); + try out.append(p.gpa, '\n'); + var m = meta; + m.path = try p.gpa.dupe(u8, meta.path); + errdefer p.gpa.free(m.path); + // Coloured whole (zeros where nothing coloured it): the pane's syntax + // pass then parses no fragment of it, per refill. + const code = text[@min(meta.code_start, text.len)..]; + m.colors = if (meta.colors.len >= code.len) try p.gpa.dupe(u8, meta.colors[0..code.len]) else blk: { + const c = try p.gpa.alloc(u8, code.len); + @memset(c, 0); + @memcpy(c[0..meta.colors.len], meta.colors); + break :blk c; + }; + rows.append(p.gpa, m) catch |err| { + p.gpa.free(m.path); + p.gpa.free(m.colors); + return err; + }; +} + +/// The rows made into the pane: line 1 as it is (the user's), then `out`, +/// with `rows` their metadata. The keyboard's place is left where it was. +fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) void { + defer locations.freeRowList(p.gpa, rows); + const f = &rp.file.?; + const line = lineOne(f.content); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n", out.items }) catch return; + const meta = p.gpa.alloc(locations.Row, rows.items.len + 1) catch { + p.gpa.free(content); + return; + }; + meta[0] = .{ .kind = .context, .path = p.gpa.dupe(u8, "") catch &.{}, .at = .{}, .location_end = 0, .code_start = 0 }; + @memcpy(meta[1..], rows.items); + rows.clearRetainingCapacity(); + const kept_row = rp.body.cur_row; + const kept_col = rp.body.cur_col; + if (std.mem.eql(u8, content, f.content)) { + // Same text: the metadata alone, no undo step, no syntax pass. + p.gpa.free(content); + if (locations.equalRows(f.location_rows, meta)) { + locations.freeRows(p.gpa, meta); + } else { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.syntax_dirty = true; + } + } else { + File.setContent(p, f, content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.saved_revision = f.revision; + } + gpa_free_pager(p, f); + // The cursor stays where it was typing; on a row that went, the last. + const last: i32 = @intCast(File.nlines(p.gpa, f) -| 1); + rp.body.cur_row = @min(kept_row, last); + rp.body.cur_col = if (rp.body.cur_row == kept_row) kept_col else 0; + if (rp.body.cur_row == 0 and rp.body.cur_col > line.len) rp.body.cur_col = @intCast(line.len); + rp.query.?.seen_row = rp.body.cur_row; +} + +fn gpa_free_pager(p: *Pardes, f: *File.State) void { + if (f.pager_spans.len == 0) return; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; +} + +/// The gutter a file of `nlines` lines numbers its rows in: two spaces, +/// the number right-aligned, two spaces. +fn gutterWidth(nlines: usize) usize { + var digits: usize = 1; + var n = nlines; + while (n >= 10) : (n /= 10) digits += 1; + return 2 + @max(3, digits) + 2; +} + +fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { + var lead: usize = 0; + while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1; + const code = std.mem.trimEnd(u8, whole[lead..], "\r"); + var buf: [4096 + 32]u8 = undefined; + var num: [24]u8 = undefined; + const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch ""; + const pad = width -| 2 -| number.len; + if (pad + number.len + 2 + code.len > buf.len) return; + @memset(buf[0..pad], ' '); + @memcpy(buf[pad..][0..number.len], number); + @memcpy(buf[pad + number.len ..][0..2], " "); + @memcpy(buf[pad + number.len + 2 ..][0..code.len], code); + const text = buf[0 .. pad + number.len + 2 + code.len]; + const gutter = pad + number.len + 2; + try writeRow(p, out, rows, text, .{ + .kind = .match, + .source_column = lead, + .path = @constCast(path), + .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, + .location_end = gutter, + .code_start = gutter, + .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}), + }); +} + +/// The path a row of pane `tp`'s text says: its file's, or `@pN` for a +/// text that is no file (a list, a scratch). +fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { + const f = tp.file orelse return ""; + if (f.output == null and !std.mem.startsWith(u8, std.fs.path.basename(f.path), "+")) return f.path; + return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch ""; +} + +/// Rows from pane `tp`'s places: one a line with any (two on a line are +/// one row: everywhere's bug), the declaration they are in over them when +/// its parse exists, from place `from` on, `budget` rows at most. The +/// place it stopped before. +fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize { + const f = &tp.file.?; + const set = &tp.places; + const hits = set.hits.items; + const index = try File.lineIndex(p.gpa, f); + const width = gutterWidth(index.len); + const path = addressOf(p.scratch.allocator(), tp); + const decls = ownerDecls(p, f, false) orelse &.{}; + var decl_now: ?usize = null; + var i: usize = @min(from, hits.len); + // the line of the first, found in the index + var line: usize = if (i < hits.len) blk: { + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= hits[i].start) lo = mid + 1 else hi = mid; + } + break :blk lo -| 1; + } else 0; + // a window begins at a line's first place + while (i > 0 and hits[i - 1].start >= index[line]) i -= 1; + while (i < hits.len) { + while (line + 1 < index.len and index[line + 1] <= hits[i].start) line += 1; + // the places on this line + var n: usize = 1; + const ls = index[line]; + const le = if (line + 1 < index.len) index[line + 1] - 1 else f.content.len; + while (i + n < hits.len and hits[i + n].start <= le) n += 1; + if (budget.* == 0) { + q.more = true; + break; + } + budget.* -= 1; + // the innermost declaration around it, its first line once + var inner: ?usize = null; + for (decls, 0..) |d, di| { + if (d.start_line > line) break; + if (d.end_line < line) continue; + inner = di; + } + if (inner != decl_now) { + decl_now = inner; + if (inner) |di| if (decls[di].start_line != line) { + const head_ls = index[decls[di].start_line]; + const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len; + const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r"); + var hb: [600]u8 = undefined; + const text = std.fmt.bufPrint(&hb, " {s}", .{head[0..@min(head.len, 560)]}) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 }); + }; + } + const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; + try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); + try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + i += n; + } + return i; +} + +/// The rows of a `/`: while typed, a window of `live_rows` around the +/// current place; `full` (frozen), the whole list up to `max_rows`. +fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[oid].?; + const set = &owner.places; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var budget: usize = if (full) max_rows else live_rows; + const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); + const from = if (full) 0 else at -| live_rows / 2; + q.window = .{ .lo = from, .hi = from }; + if (set.started and set.from == rp.serial) { + if (from > 0) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} places before these", .{from}) catch " ..."); + } + q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget); + q.window.lo = @min(from, q.window.hi); + } + if (q.more) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + showPlacesCurrent(p, id); +} + +fn noteRow(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8) !void { + try q.items.append(p.gpa, .{ .kind = .note }); + try writeRow(p, out, rows, text, .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }); +} + +/// The current row from the places of the pane its rows are in, the count +/// with them: for `/`, the owner's. +fn showPlacesCurrent(p: *Pardes, id: usize) void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; + const set = &owner.places; + q.total = if (set.from == rp.serial) set.hits.items.len else 0; + q.more = q.more or (set.from == rp.serial and !set.complete()); + q.k = if (set.current) |c| c + 1 else 0; + if (set.from != rp.serial) q.k = 0; + q.current = null; + // By line, not by the rows' place indices: the rows may lag the places + // a tick while they are still being found. + if (set.current) |c| if (c < set.hits.items.len) { + const at = lineOfOffset(p, &owner.file.?, set.hits.items[c].start) + 1; + const rows = rp.file.?.location_rows; + for (q.items.items, 0..) |it, i| { + if (it.kind != .hit or it.serial != owner.serial or i + 1 >= rows.len) continue; + if (rows[i + 1].at.line == at) { + q.current = i; + break; + } + } + }; + // Stepped out of the window the live rows are: made again around it. + if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); + showCurrent(rp); +} + +/// Every open pane's rows for All, grouped under `@pN name (count)` in +/// the order of the panes' serials (everywhere's other bug: it went by +/// column). +fn makeAllRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { + order[n] = i; + n += 1; + }; + std.mem.sort(usize, order[0..n], p, struct { + fn lt(pp: *Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + var budget: usize = max_rows; + q.total = 0; + for (order[0..n]) |tid| { + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp) or set.hits.items.len == 0) { + q.more = q.more or !set.complete(); + continue; + } + q.total += set.hits.items.len; + q.more = q.more or !set.complete(); + var hb: [600]u8 = undefined; + const name = if (tp.file) |f| Names.relative(f.path, std.fs.path.dirname(rp.file.?.path) orelse "") else ""; + const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); + _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget); + } + if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + // The current one: the first hit row, until a step moves it. + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +fn firstHit(q: *const Query) ?usize { + for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i; + return null; +} + +/// `k` from the current row: the hits on the rows before it, and its own. +fn countCurrent(q: *Query) void { + q.k = 0; + const c = q.current orelse return; + for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0; + q.k += 1; +} + +/// The names the query matches, best first, `Names.max_rows` of them: each +/// a row as its source has it, the matched bytes tinted. +fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { + _ = pat; + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const was_current: ?u32 = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].ref else null) else null; + _ = was_current; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var spans: std.ArrayList(pardes.pager.Span) = .empty; + errdefer spans.deinit(p.gpa); + const chrome = p.bodyChrome(); + const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; + const shown = @min(q.names.hits.items.len, Names.max_rows); + var marks: [Names.max_query * 4]u16 = undefined; + const base = lineOne(rp.file.?.content).len + 1; + for (0..shown) |i| { + var nmarks: usize = 0; + const row = q.names.row(i, &marks, &nmarks); + const cand = q.names.cands.items[q.names.hits.items[i].cand]; + const at = base + out.items.len; + // Where it points: a path (Find, Recent), a pane (Panes), a line + // of the owner (Symbols). + var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; + var pathbuf: [4096 + 32]u8 = undefined; + switch (q.source) { + .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .recent => { + const t = look.parsePathLine(row); + meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); + meta.at = t.at; + }, + .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch ""), + .symbols => { + const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; + meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); + meta.at = .{ .line = cand.ref }; + }, + else => {}, + } + try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); + try writeRow(p, &out, &rows, row, meta); + var k: usize = 0; + while (k < nmarks) { + var e = k + 1; + while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + k = e; + } + } + if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + setRows(p, rp, &out, &rows); + const f = &rp.file.?; + f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; + q.total = q.names.hits.items.len; + q.more = q.names.busy(); + // The best is current until a step or a click moves it. + q.current = if (shown > 0) 0 else null; + countCurrent(q); + showCurrent(rp); + showTarget(p, id); +} + +/// A slice of a Grep: the files the walk has found so far read and +/// searched, about 4 ms of them a frame, each line holding the pattern +/// (a literal, smart case: a capital makes it exact) kept. +/// ponytail: on the loop, a file a step; the disk engine's worker (phase +/// 4) takes this over. +fn grepSlice(p: *Pardes, q: *Query, rp: *Pane, pat: []const u8) void { + const started = Places.nowNs(); + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const fold = for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true; + var low_buf: [256]u8 = undefined; + const needle = if (fold) std.ascii.lowerString(low_buf[0..@min(pat.len, low_buf.len)], pat[0..@min(pat.len, low_buf.len)]) else pat; + while (q.grep_next < q.names.cands.items.len) { + if (q.found.items.len >= grep_cap) break; + const c = q.names.cands.items[q.grep_next]; + q.grep_next += 1; + const rel = q.names.bytes.items[c.start..][0..c.len]; + var pathbuf: [4096 + 8]u8 = undefined; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch continue; + }; + defer p.gpa.free(bytes); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) continue; + var line_no: u32 = 1; + var ls: usize = 0; + while (ls <= bytes.len) { + const le = std.mem.indexOfScalarPos(u8, bytes, ls, '\n') orelse bytes.len; + const ln = bytes[ls..le]; + const at = if (fold) std.ascii.findIgnoreCase(ln, needle) else std.mem.indexOf(u8, ln, needle); + if (at) |col| { + const path_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, rel) catch return; + const code_at: u32 = @intCast(q.found_bytes.items.len); + const code = ln[0..@min(ln.len, 400)]; + q.found_bytes.appendSlice(p.gpa, code) catch return; + q.found.append(p.gpa, .{ .path = path_at, .path_len = @intCast(rel.len), .line = line_no, .col = @intCast(col), .end = @intCast(col + needle.len), .code = code_at, .code_len = @intCast(code.len) }) catch return; + if (q.found.items.len >= grep_cap) break; + } + if (le == bytes.len) break; + ls = le + 1; + line_no += 1; + } + if (started != 0 and Places.nowNs() - started > Places.frame_ns) break; + } +} + +/// A Grep keeps this many lines: the rest wait (the disk engine's `More`). +pub const grep_cap = 2000; + +fn makeGrepRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + for (q.found.items, 0..) |fd, i| { + const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + if (!std.mem.eql(u8, rel, last_path)) { + last_path = rel; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); + try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); + } + const walking = q.names.walking() or q.grep_next < q.names.cands.items.len; + if (q.found.items.len >= grep_cap) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: type more of it"); + setRows(p, rp, &out, &rows); + q.total = q.found.items.len; + q.more = walking and q.found.items.len < grep_cap; + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +/// A Grep's hits in each open file are that pane's places: its tints, +/// ticks and n/N. +fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void { + _ = q; + for (p.panes) |slot| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output != null or tp.query != null) continue; + tp.places.search(p, tp, .list, serial, pat, true, null, false); + } +} + +/// The language server's answer for an owner's Refs, Def, Impl or +/// Diagnostics, into its query pane (made or reused) with line 1 the word: +/// what follows the word filters the rows; the places in the owner's text +/// are its places. `rows` are `path:line:col text`, as the server's +/// answer is written (lsp_client). +pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) void { + const owner = p.panes[owner_id] orelse return; + var id = ofOwner(p, owner.serial); + if (id == null or p.panes[id.?].?.query.?.source != source) { + open(p, owner_id, source, "", false); + id = ofOwner(p, owner.serial); + } + const qid = id orelse return; + const rp = p.panes[qid].?; + const q = rp.query.?; + const copy = p.gpa.dupe(u8, rows) catch return; + p.gpa.free(q.lsp_rows); + q.lsp_rows = copy; + const line = lineOne(rp.file.?.content); + const a = parse(line) orelse return; + makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); + toLineOne(p, qid); +} + +fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + const owner_id = p.paneBySerial(q.owner); + const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; + var feed: std.ArrayList(Places.Hit) = .empty; + defer feed.deinit(p.gpa); + // In order: by path, then place, as a list of places reads. + var sorted: std.ArrayList([]const u8) = .empty; + defer sorted.deinit(p.gpa); + var split = std.mem.splitScalar(u8, q.lsp_rows, '\n'); + while (split.next()) |ln| if (ln.len > 0) try sorted.append(p.gpa, ln); + std.mem.sort([]const u8, sorted.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + const ta = look.parsePathLine(a); + const tb = look.parsePathLine(b); + const order = std.mem.order(u8, ta.path, tb.path); + if (order != .eq) return order == .lt; + if (ta.at.line != tb.at.line) return ta.at.line < tb.at.line; + return ta.at.col < tb.at.col; + } + }.lt); + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + var n: usize = 0; + for (sorted.items) |ln| { + if (ln.len == 0) continue; + if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; + const t = look.parsePathLine(ln); + if (t.at.line == 0) continue; + const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + if (!std.mem.eql(u8, t.path, last_path)) { + last_path = t.path; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); + const col0 = t.at.col -| 1; + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); + // The row's text: the line in the owner when it is the owner's, + // else as the server said it. + var code: []const u8 = rest; + var col = col0; + var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; + if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { + const owner_f = &p.panes[oid].?.file.?; + if (t.at.line <= File.nlines(p.gpa, owner_f)) { + const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); + const nx = File.lineStart(p.gpa, owner_f, t.at.line); + const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; + code = owner_f.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + } + } else { + col = 0; + end = 0; + }; + try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); + n += 1; + } + if (n == 0) try noteRow(p, q, &out, &rows, " nothing"); + setRows(p, rp, &out, &rows); + q.total = n; + q.more = false; + q.current = firstHit(q); + if (owner_id) |oid| { + const owner = p.panes[oid].?; + // Current: the first place after where it was asked (the answer + // may come after the cursor moved), shown in the owner. + const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); + owner.places.feed(p, owner, rp.serial, feed.items, null); + const hits = owner.places.hits.items; + var next: ?usize = null; + for (hits, 0..) |h, i| if (h.start > asked_at) { + next = i; + break; + }; + if (next == null and hits.len > 0) next = 0; + if (next) |hi| { + owner.places.goTo(owner, hi, false); + for (q.items.items, 0..) |it, i| if (it.kind == .hit and i + 1 < rp.file.?.location_rows.len) { + const meta = rp.file.?.location_rows[i + 1]; + if (!std.mem.eql(u8, meta.path, owner_path)) continue; + const ls = File.lineStart(p.gpa, &owner.file.?, meta.at.line -| 1); + if (ls + meta.at.col -| 1 == hits[hi].start) { + q.current = i; + break; + } + }; + } + } + countCurrent(q); + showCurrent(rp); +} + +/// The places query `serial` fed in panes other than the owner, cleared +/// (a new source or pattern makes its own); the owner's too when the new +/// line is no `/`. +fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anytype) void { + _ = q; + _ = asked; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (tp.places.from != serial) continue; + if (owner_id != null and owner_id.? == i) tp.places.restore(p, tp); + tp.places.clear(p.gpa); + } +} + +// ---- the current row ---- + +/// The current row drawn as the visited row is (a line selection), while +/// the keyboard is on line 1 or elsewhere; on the rows, the cursor itself +/// is current. Scrolled into view, line 1 kept when it can be. +fn showCurrent(rp: *Pane) void { + const q = rp.query orelse return; + if (rp.body.cur_row != 0 and rp.focus == .body) return; + const c = q.current orelse { + rp.body.msel.active = false; + return; + }; + const r: i32 = @intCast(c + 1); + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + const off = rp.scroll(); + const shown = off + @as(i32, rp.rows) - 1; + if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); +} + +/// The line (0-based) of byte `at` of `f`'s text. +fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize { + const index = File.lineIndex(p.gpa, f) catch return 0; + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= at) lo = mid + 1 else hi = mid; + } + return lo -| 1; +} + +/// The first of pane `tp`'s places on line `line` (1-based), if any. +fn placeOnLine(p: *Pardes, tp: *Pane, line: usize) ?usize { + const f = &tp.file.?; + if (line == 0 or line > File.nlines(p.gpa, f)) return null; + const ls = File.lineStart(p.gpa, f, line - 1); + const next = File.lineStart(p.gpa, f, line); + const hits = tp.places.hits.items; + const i = Places.firstFrom(hits, ls); + if (i < hits.len and (hits[i].start < next or (next == ls))) return i; + return null; +} + +/// Item `i` current, and shown where it points (`show`). +fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.current = i; + const it = q.items.items[i]; + const rows = rp.file.?.location_rows; + if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { + const tp = p.panes[tid].?; + if (placeOnLine(p, tp, rows[i + 1].at.line)) |hi| { + tp.places.current = hi; + tp.places.gen +%= 1; + if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); + } else countCurrent(q); + } else countCurrent(q) else countCurrent(q); + showCurrent(rp); + if (show) showTarget(p, id); +} + +/// Step the current row `delta` hits on, round the end silently: Ctrl-n, +/// Ctrl-p, Down and Up on line 1, n and N in the pane. +pub fn step(p: *Pardes, id: usize, delta: i32) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + // A `/`: the owner's places step, the rows follow them. + if (q.source == .text) if (p.paneBySerial(q.owner)) |oid| { + const owner = p.panes[oid].?; + if (owner.places.from == rp.serial) { + const keyboard = p.active; + owner.places.step(p, owner, delta > 0, 1, false); + p.active = keyboard; + showPlacesCurrent(p, id); + return; + } + }; + const items = q.items.items; + if (items.len == 0) return; + var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); + for (0..items.len) |_| { + if (delta > 0) i = if (i + 1 >= items.len) 0 else i + 1 else i = if (i == 0) items.len - 1 else i - 1; + if (items[i].kind == .hit) break; + } else return; + setCurrent(p, id, i, true); +} + +/// Where the current row points, shown with the keyboard left where it is: +/// a place in an open pane's text selected there (its places' current), +/// in view; a file an open pane shows, its line there; any other file in +/// the +Preview under this pane. Every pane it moves remembers its view +/// first, for Esc. +fn showTarget(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const c = q.current orelse return; + const f = &rp.file.?; + if (c + 1 >= f.location_rows.len) return; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + const keyboard = p.active; + defer p.active = keyboard; + if (it.serial != 0) { + const tid = p.paneBySerial(it.serial) orelse return; + const tp = p.panes[tid].?; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + if (placeOnLine(p, tp, meta.at.line)) |hi| tp.places.goTo(tp, hi, false); + return; + } + if (q.source == .symbols) { + const oid = p.paneBySerial(q.owner) orelse return; + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + } + if (q.source == .panes) return; + if (meta.path.len == 0) return; + // A file open in a pane: shown there. + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, meta.path)) continue; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + const line0 = meta.at.line -| 1; + const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows; + if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center); + return; + } + displayPreview(p, id, meta.path, meta.at); +} + +// ---- the +Preview ---- + +/// The +Preview under query pane `qid`, if it has one: by serial. +fn previewOf(p: *Pardes, qid: usize) ?usize { + const q = p.panes[qid].?.query.?; + if (q.preview == 0) return null; + return p.paneBySerial(q.preview) orelse { + q.preview = 0; + return null; + }; +} + +/// Whether `pane` is a query pane's +Preview: that query pane's slot. +pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { + const f = pane.file orelse return null; + const o = f.output orelse return null; + if (o.from != .preview) return null; + for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; + return null; +} + +/// A +Preview made under query pane `qid`, out of its rows alone. +fn makePreview(p: *Pardes, qid: usize) ?usize { + const rp = p.panes[qid].?; + const free = p.freeSlot() orelse return null; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const content = p.gpa.dupe(u8, "") catch return null; + const np = Output.open(p, free, dir, .preview, "", content) catch { + p.gpa.free(content); + return null; + }; + layout.compute(p); + const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; + // Out of the group's root, the text that asked: the query pane keeps + // the rows it was typed into with (made later, for a reused pane). + if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + p.removePane(free, qid) catch {}; + return null; + } + rp.query.?.preview = np.serial; + return free; +} + +/// File `path` at `at` in the +Preview: its text read (once a file: a +/// file open in a pane would be shown there instead), the place centred +/// and selected. Made when the pane has none and its owner has the rows. +fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { + const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const pane = p.panes[id].?; + const f = &pane.file.?; + if (!std.mem.eql(u8, f.path, path)) { + if (exec.kindOf(path)) |kind| if (kind != .file) return; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch return; + }; + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const owned_path = p.gpa.dupe(u8, path) catch { + p.gpa.free(bytes); + return; + }; + p.gpa.free(f.path); + f.path = owned_path; + File.setContent(p, f, bytes); + f.saved_revision = f.revision; + f.scroll = 0; + f.syntax_dirty = true; + pane.hscroll = 0; + p.sync(); + } + look.clearNavigationSelection(p, pane); + if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { + f.scroll = 0; + f.syntax_dirty = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + return; + } + look.focusPaneLine(p, id, at, .center); + if (at.end_line == 0 or at.end_col <= at.col) + pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) }; +} + +/// The +Preview becomes the file's pane where it stands: same slot, same +/// serial, same rect, its scroll and selection as the preview left them. +/// It is a file pane from here: an empty undo history, the Recent entry, +/// the watch, a file's tag; and a pane of its own, no longer attached (it +/// stays when its query pane goes). +fn promote(p: *Pardes, qid: usize, id: usize) void { + const pane = p.panes[id] orelse return; + const f = &pane.file.?; + f.output = null; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; + f.saved_revision = f.revision; + f.saved_hash = null; + f.saved_len = null; + f.disk_gone = false; + f.syntax_dirty = true; + pane.attached_to = null; + if (Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path); + if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + pardes.ctlfs.events.noteLog(p, .rename, pane); + p.panes[qid].?.query.?.preview = 0; +} + +// ---- Enter, Esc ---- + +/// Enter on line 1 (or on a row, `row`): the keyboard to the current hit +/// in its pane (the +Preview promoted to the file's pane when it shows +/// it), a `/` into the register, and the rows frozen into ordinary text. +pub fn land(p: *Pardes, id: usize, row: ?usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true); + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + freeze(p, id); + const owner_id = p.paneBySerial(q.owner); + if (q.source == .text) { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const set = &owner.places; + // The whole list now, once, every place found: a result from here. + if (set.started and set.from == rp.serial) { + set.fill(p, owner, std.math.maxInt(usize), @import("regexp.zig").Regex.budget); + makeTextRows(p, id, oid, true) catch {}; + } + if (set.started and set.from == rp.serial) { + if (set.literal) { + var escaped: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&escaped, p.scratch.allocator(), set.pattern) catch {}; + p.registers.put(p.gpa, '/', escaped.items, 0, 1, true); + } else p.registers.put(p.gpa, '/', set.pattern, 0, 1, true); + p.registers.last_search = '/'; + set.provenance = .search; + } + p.jump_force = true; + p.active = oid; + return; + } + const c = q.current orelse { + if (owner_id) |oid| p.active = oid; + return; + }; + const f = &rp.file.?; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + p.jump_force = true; + if (it.serial != 0) { + if (p.paneBySerial(it.serial)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + } + return; + } + switch (q.source) { + .symbols => if (owner_id) |oid| { + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + }, + .panes => if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + }, + else => {}, + } + // The preview shows it: promoted where it stands. + if (previewOf(p, id)) |pid| if (std.mem.eql(u8, p.panes[pid].?.file.?.path, meta.path)) { + promote(p, id, pid); + p.active = pid; + if (q.source == .grep) { + const a = parse(q.asked) orelse return; + const pp = p.panes[pid].?; + pp.places.search(p, pp, .list, rp.serial, a.pat, true, null, false); + } + return; + }; + var buf: [4096 + 64]u8 = undefined; + const address = if (meta.at.line > 0) + std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path + else + meta.path; + look.lookAt(p, id, address); +} + +/// The rows frozen: ordinary text from here, Save works on them; the +/// places they fed stay, while the pane lives; every view stays where the +/// search left it; the preview, of no more use, goes. +fn freeze(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + q.frozen = true; + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial or tp.serial == q.owner) tp.places.forget(p.gpa); + if (previewOf(p, id)) |pid| { + const pv = p.panes[pid].?; + // A preview showing the current row is promoted by `land`: one + // showing another file goes. + _ = pv; + } +} + +/// Esc on line 1 while typing: every view as the search found it, the +/// places it fed gone, and the pane closed (nothing was answered); a +/// reused pane's frozen rows come back instead, and their places. +pub fn cancel(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + const owner_id = p.paneBySerial(q.owner); + for (p.panes) |slot| if (slot) |tp| { + if (tp.places.from != rp.serial and tp.serial != q.owner) continue; + tp.places.restore(p, tp); + tp.places.forget(p.gpa); + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; + if (q.saved) |s| { + q.saved = null; + // A preview made for the query Esc took back has no use: its rows + // go to the text whose rows they were. + if (previewOf(p, id)) |pid| { + p.panes[pid].?.attached_to = null; + p.removePane(pid, owner_id) catch {}; + q.preview = 0; + } + const f = &rp.file.?; + File.setContent(p, f, s.content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = s.rows; + p.gpa.free(q.asked); + q.asked = s.asked; + q.source = s.source; + q.items.clearRetainingCapacity(); + q.items.appendSlice(p.gpa, s.items) catch {}; + p.gpa.free(s.items); + q.current = s.current; + q.total = s.total; + q.k = s.k; + q.frozen = true; + rp.body.cur_row = 0; + rp.body.cur_col = 0; + showCurrent(rp); + // Its places again, as Enter left them. + if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { + const owner = p.panes[oid].?; + owner.places.search(p, owner, .search, rp.serial, a.pat, false, null, false); + }; + if (owner_id) |oid| p.active = oid; + return; + } + if (owner_id) |oid| { + p.removePane(id, oid) catch {}; + p.active = oid; + if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); + } else p.removePane(id, null) catch {}; +} + +/// The pane going (Del, its owner's Del): the places it fed go with it. +pub fn release(p: *Pardes, pane: *Pane) void { + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) { + tp.places.forget(p.gpa); + tp.places.clear(p.gpa); + }; +} + +// ---- keys, the mouse, edits ---- + +/// The keys a query pane answers itself, before its text has them. On +/// line 1, typing: Enter lands, Esc cancels, Ctrl-n, Ctrl-p, Down and Up +/// step the current row. In normal mode: Enter on a hit row lands on it, +/// n and N step. Anything else is ordinary text editing (line 1) or is +/// refused (the rows, while live: clampEdit). Tab stays the exec chord. +pub fn key(p: *Pardes, id: usize, k: Key) bool { + const rp = p.panes[id] orelse return false; + const q = rp.query orelse return false; + if (rp.focus != .body) return false; + const t = &rp.body; + if (q.frozen) return false; + if (t.mode == .normal) { + if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; + if (k.cp == 'n' or k.cp == 'N') { + step(p, id, if (k.cp == 'n') 1 else -1); + return true; + } + if (hit(k, config.look_key) and t.cur_row > 0) { + land(p, id, @intCast(t.cur_row - 1)); + return true; + } + return false; + } + if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false; + if (hit(k, config.escape)) { + cancel(p, id); + return true; + } + if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) { + land(p, id, null); + return true; + } + const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); + const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + if (down or up) { + step(p, id, if (down) 1 else -1); + return true; + } + return false; +} + +/// An edit of a live query pane's text (edit.setEditTextSpan): inside line +/// 1, as typed; one from line 1 into the rows, cut at line 1's end (and a +/// newline put in it, a blank); one wholly in the rows refused, as a tag's +/// prefix refuses one. Null: refused. Lifted from queryline. +pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { + const end = std.mem.indexOfScalar(u8, old, '\n') orelse old.len; + const span = File.spanOf(old, new); + const old_to = old.len - span.tail; + const put = new[span.head .. new.len - span.tail]; + const rows_same = old_to <= end and std.mem.indexOfScalar(u8, put, '\n') == null; + if (rows_same) return new; + if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) { + t.refused = true; + if (t.pane()) |pane| if (p.paneIdOf(pane)) |id| + p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)"); + return null; + } + // From inside line 1 into the rows: what it put in, flat, and what is + // left of line 1 after it; the rows as they were. + const kept = if (old_to < end) old[old_to..end] else ""; + const out = std.mem.concat(p.gpa, u8, &.{ old[0..span.head], put, kept, old[end..] }) catch return null; + for (out[0 .. span.head + put.len + kept.len]) |*c| if (c.* == '\n') { + c.* = ' '; + }; + return out; +} + +/// B3 on a row's gutter (its line number): the row's address, as a +Diff +/// line's prefix is its place (exec.operandAt). Null off a gutter. +pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 { + if (pane.query == null) return null; + const f = pane.file orelse return null; + if (row == 0 or row >= f.location_rows.len) return null; + const meta = f.location_rows[row]; + if (meta.kind != .match or meta.path.len == 0 or meta.location_end == 0 or col >= meta.location_end) return null; + if (meta.at.line == 0) return std.fmt.bufPrint(buf, "{s}", .{meta.path}) catch null; + return std.fmt.bufPrint(buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch null; +} + +/// The tag's start for a query pane: its name and where it is, `+Search +/// 3/27`, `0` with nothing found, `+` while it still counts. +pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![]const u8 { + const name = std.fs.path.basename(path); + const more = if (q.more and !q.frozen) "+" else ""; + if (q.total == 0) return std.fmt.allocPrint(arena, "{s} 0{s}", .{ name, more }); + if (q.k == 0) return std.fmt.allocPrint(arena, "{s} {d}{s}", .{ name, q.total, more }); + return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more }); +} + +/// The other places on a hit row's line tinted, from the pane its rows are +/// in (the first is the row's own mark, Output.decorateRow): the current +/// one strongest, as in that pane's text. +pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const q = pane.query orelse return; + const f = if (pane.file) |*file| file else return; + const th = p.theme(); + const strong = p.chromeTheme().search_bg; + const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + var vr: i32 = 0; + var last: i32 = -1; + while (vr < body_h) : (vr += 1) { + const row = pane.wrapAt(vr).line; + if (row == last or row < 1) continue; + last = row; + const i: usize = @intCast(row - 1); + if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue; + const it = q.items.items[i]; + if (it.kind != .hit or it.serial == 0) continue; + const tid = p.paneBySerial(it.serial) orelse continue; + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp)) continue; + const tf = &tp.file.?; + const meta = f.location_rows[@intCast(row)]; + // Its line's places as they are now, found by the line: the rows + // may be a tick behind the places. + if (meta.at.line == 0 or meta.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, meta.at.line - 1); + const next = File.lineStart(p.gpa, tf, meta.at.line); + const line = modal.lineSlice(f.content, @intCast(row)); + var hi = Places.firstFrom(set.hits.items, ls); + while (hi < set.hits.items.len and set.hits.items[hi].start < next) : (hi += 1) { + const h = set.hits.items[hi]; + if (h.start < ls + meta.source_column) continue; + const a = meta.code_start + (h.start - ls - meta.source_column); + const b = @min(line.len, meta.code_start + (@min(h.end, next) - ls - meta.source_column)); + if (b <= a or a >= line.len) continue; + const current = set.current != null and set.current.? == hi; + File.paintWordSelection(p, s, pane, r, row, @intCast(a), @intCast(b), if (current) strong else quiet); + } + } +} + +// ---- tests ---- + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn queryPane(p: *Pardes) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null) return i; + return null; +} + +test "parse: line 1's first word names the source" { + try std.testing.expectEqual(Source.text, parse("/alpha").?.source); + try std.testing.expectEqualStrings("alpha", parse("/alpha").?.pat); + try std.testing.expectEqual(Source.find, parse("Find lay").?.source); + try std.testing.expectEqualStrings("lay", parse("Find lay").?.pat); + try std.testing.expectEqual(Source.grep, parse("Grep").?.source); + try std.testing.expectEqual(Source.all, parse("All x y").?.source); + try std.testing.expectEqualStrings("x y", parse("All x y").?.pat); + try std.testing.expectEqual(Source.refs, parse("Refs").?.source); + try std.testing.expect(parse("Findx") == null); + try std.testing.expect(parse("grep x") == null); + try std.testing.expect(parse("") == null); +} + +test "a / query: keystroke by keystroke, the owner shows the set, rows from its own rows alone, zero hits a state, Esc puts all back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + p.newScratchBelow(0); + const below = p.col_panes[0][1]; + p.active = 0; + layout.compute(p); + const before = p.rects; + // cursor on line 3 (row 2) + pane.body.cur_row = 2; + pane.body.cur_col = 0; + typeKeys(p, "/"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid)); + try std.testing.expectEqual(qid, p.active); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + const born = p.rects[qid]; + try std.testing.expectEqualStrings("/", lineOne(qp.file.?.content)); + // keystroke 1 + typeKeys(p, "a"); + const q = qp.query.?; + try std.testing.expectEqual(Source.text, q.source); + try std.testing.expect(pane.places.started and pane.places.from == qp.serial); + try std.testing.expect(q.total > 0); + try std.testing.expectEqualDeep(born, p.rects[qid]); + // keystroke 2 .. `alph`: four places on four lines (rows), the + // current the first at or after the cursor (line 3's alphabet) + typeKeys(p, "lph"); + try std.testing.expectEqual(@as(usize, 4), q.total); + try std.testing.expectEqual(@as(usize, 2), q.k); + try std.testing.expectEqual(@as(?usize, 1), pane.places.current); + const sel = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 15), @min(sel.anchor, sel.head)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expectEqual(qid, p.active); + // Ctrl-n steps, the owner follows + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(usize, 3), q.k); + // drawn: rows, tints, ticks + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + try std.testing.expect(p.surface.nrail_ticks > 0); + // zero hits: a state, the pane stays where it was, line 1 as typed + typeKeys(p, "zz"); + try std.testing.expectEqual(@as(usize, 0), q.total); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expectEqualStrings("/alphzz", lineOne(qp.file.?.content)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + const tag = try tagline.pathPrefix(p, p.scratch.allocator(), qp); + try std.testing.expectEqualStrings("+Search 0", tag); + // Esc: the pane gone, its rows back to the owner, the owner as it was + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expectEqual(@as(usize, 0), p.active); + layout.compute(p); + try std.testing.expectEqualDeep(before[0], p.rects[0]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expect(!pane.places.started); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); +} + +test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + typeKeys(p, "/alpha"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(q.frozen); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("alpha", p.registers.value('/', 0).?); + try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance); + const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content); + defer std.testing.allocator.free(frozen); + // the rows: one a line (gamma alpha has one), a gutter number each + try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); + // n and N in the owner step the same set, round the end silently + const logged = p.messages.len; + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + typeKeys(p, "nnn"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + try std.testing.expect(pane.places.wrapped); + try std.testing.expectEqual(logged, p.messages.len); + typeKeys(p, "N"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + // a later `/` reuses the pane: line 1 fresh, the rows the new query's + typeKeys(p, "/"); + try std.testing.expectEqual(qid, queryPane(p).?); + try std.testing.expectEqual(qid, p.active); + try std.testing.expect(!q.frozen); + typeKeys(p, "beta"); + try std.testing.expectEqual(@as(usize, 1), q.total); + // Esc: the frozen rows of `/alpha` again, the owner's places with them + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expect(q.frozen); + try std.testing.expectEqualStrings(frozen, qp.file.?.content); + try std.testing.expectEqualStrings("alpha", pane.places.pattern); + // Del closes it, its places with it + exec.runBuiltin(p, .Del, qid, "", null); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!pane.places.started); +} + +/// A test's file pane in `tmp`, named `name`, holding `text`. +fn testFileIn(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) !*Pane { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, name }); + return pane; +} + +fn leader(p: *Pardes, keys: []const u8) void { + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + typeKeys(p, keys); +} + +fn settle(p: *Pardes) void { + var frames: usize = 0; + while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick); + p.update(.tick); +} + +test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "src"); + for ([_][]const u8{ "src/layout.zig", "src/look.zig", "notes.md" }) |name| + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "pub fn split() void {}\nconst x = 1;\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "x.txt", "x\n"); + p.newScratchBelow(0); + const other = p.col_panes[0][1]; + try std.testing.expect(layout.splitColumn(p, other, other, false)); + p.active = 0; + layout.compute(p); + const before = p.rects; + leader(p, "ff"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + try std.testing.expectEqual(Source.find, q.source); + try std.testing.expectEqualStrings("Find ", lineOne(p.panes[qid].?.file.?.content)); + // the group: owner, query pane, +Preview, out of the owner's rows alone + const pv = previewOf(p, qid).?; + try std.testing.expectEqual(@as(usize, 0), layout.groupRoot(p, pv)); + try std.testing.expectEqualDeep(before[other], p.rects[other]); + try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[qid].h + p.rects[pv].h); + settle(p); + // an empty query lists every name + try std.testing.expectEqual(@as(usize, 4), q.total); + const born = p.rects; + typeKeys(p, "lay"); + settle(p); + try std.testing.expectEqual(@as(usize, 1), q.total); + try std.testing.expectEqualDeep(born[qid], p.rects[qid]); + try std.testing.expectEqualDeep(born[pv], p.rects[pv]); + // the current one in the preview, never by the pointer + try std.testing.expect(std.mem.endsWith(u8, p.panes[pv].?.file.?.path, "src/layout.zig")); + try std.testing.expectEqual(qid, p.active); + const serial = p.panes[pv].?.serial; + const rect = p.rects[pv]; + p.update(.{ .key = .{ .cp = Key.enter } }); + // promoted where it stands: same slot, serial, rect; a file pane now + try std.testing.expectEqual(pv, p.active); + try std.testing.expectEqual(serial, p.panes[pv].?.serial); + try std.testing.expect(p.panes[pv].?.file.?.output == null); + try std.testing.expect(p.panes[pv].?.attached_to == null); + layout.compute(p); + try std.testing.expectEqualDeep(rect, p.rects[pv]); + try std.testing.expect(q.frozen); + try std.testing.expectEqualDeep(before[other], p.rects[other]); +} + +test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "one needle\ntwo\n"); + leader(p, "fg"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + typeKeys(p, "needle"); + settle(p); + // a.txt's one, b.zig's three lines + try std.testing.expectEqual(@as(usize, 3), q.total); + const body = p.panes[qid].?.file.?.content; + try std.testing.expect(std.mem.indexOf(u8, body, "\nb.zig\n") != null); + // the open file's hits are its places + try std.testing.expect(a.places.started and a.places.hits.items.len == 1); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!a.places.started); + + // All: a second pane, both searched, grouped by serial + p.newScratchBelow(0); + const s = p.active; + const sf = &p.panes[s].?.file.?; + File.setContent(p, sf, try p.gpa.dupe(u8, "needle needle twice\n")); + p.active = 0; + leader(p, "/"); + const aid = queryPane(p).?; + const aq = p.panes[aid].?.query.?; + try std.testing.expectEqual(Source.all, aq.source); + typeKeys(p, "needle"); + settle(p); + try std.testing.expectEqual(@as(usize, 3), aq.total); + const all = p.panes[aid].?.file.?.content; + var hb: [32]u8 = undefined; + const first = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{a.serial})).?; + const second = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{p.panes[s].?.serial})).?; + try std.testing.expect(a.serial < p.panes[s].?.serial and first < second); + try std.testing.expect(second < std.mem.indexOf(u8, all, "twice").?); + // two places on one line are one row + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all, "twice")); +} + +test "zz query timings on the 1.2 MB stress file (QUERY_TIMES=)" { + const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(8 << 20)); + defer std.testing.allocator.free(bytes); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + pane.body.cur_row = 15000; + pane.ensureCursorVisible(); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const Clock = struct { + fn step(pp: *Pardes, fr: *std.heap.ArenaAllocator, ev: pardes.Event) !u64 { + const t0 = Places.nowNs(); + pp.update(ev); + _ = fr.reset(.retain_capacity); + _ = try pp.render(fr.allocator()); + return Places.nowNs() - t0; + } + }; + var report: std.ArrayList(u8) = .empty; + defer report.deinit(std.testing.allocator); + var base: u64 = 0; + for (0..10) |_| base += try Clock.step(p, &frame, .{ .key = .{ .cp = 'j', .text = "j" } }); + try report.print(std.testing.allocator, "a cursor move and its frame, no search: {d} us\n", .{base / 10 / 1000}); + const t_open = try Clock.step(p, &frame, .{ .key = .{ .cp = '/', .text = "/" } }); + try report.print(std.testing.allocator, "open / {d} us\n", .{t_open / 1000}); + for ("pane.v") |c| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + var ticks: usize = 0; + var worst: u64 = 0; + while (busy(p) or pane.places.busy(pane)) : (ticks += 1) { + if (ticks > 500) break; + worst = @max(worst, try Clock.step(p, &frame, .tick)); + } + const qid = queryPane(p).?; + try report.print(std.testing.allocator, "key '{c}': {d} us, then {d} ticks (worst {d} us), {d} places\n", .{ c, t / 1000, ticks, worst / 1000, p.panes[qid].?.query.?.total }); + } + // Enter: frozen; then edits in the owner with the pane open. + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = Key.enter } }); + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = 'i', .text = "i" } }); + var worst_edit: u64 = 0; + var sum: u64 = 0; + for (0..20) |_| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + worst_edit = @max(worst_edit, t); + sum += t; + const t2 = try Clock.step(p, &frame, .tick); + worst_edit = @max(worst_edit, t2); + } + try report.print(std.testing.allocator, "edit in the owner (insert x, then a tick): mean {d} us, worst {d} us\n", .{ sum / 20 / 1000, worst_edit / 1000 }); + // The same edits with no query pane at all, for the editor's own cost. + p.update(.{ .key = .{ .cp = Key.escape } }); + exec.runBuiltin(p, .Del, queryPane(p).?, "", null); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + sum = 0; + for (0..20) |_| sum += try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + try report.print(std.testing.allocator, "the same edit, no search: mean {d} us\n", .{sum / 20 / 1000}); + std.debug.print("{s}", .{report.items}); +} + +test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration; SearchPane new leaves the last where it is" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text + typeKeys(p, "e*"); + const qid = queryPane(p).?; + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/")); + try std.testing.expect(pane.places.started); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + // SPC b b: the open panes by name; Enter goes to the marked one + p.newScratchBelow(0); + const other = p.active; + p.active = 0; + leader(p, "bb"); + const bid = queryPane(p).?; + try std.testing.expectEqual(bid, qid); + try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source); + try std.testing.expect(p.panes[bid].?.query.?.total >= 1); + // SPC s s: the declarations, fuzzy; Enter lands on the line + p.update(.{ .key = .{ .cp = Key.escape } }); + p.active = 0; + leader(p, "ss"); + const sid = queryPane(p).?; + try std.testing.expectEqual(Source.symbols, p.panes[sid].?.query.?.source); + // (context declarations span lines: a one-line fn is none of them) + typeKeys(p, "bet"); + try std.testing.expectEqual(@as(usize, 1), p.panes[sid].?.query.?.total); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + _ = other; + // SearchPane new: the frozen one stays, unattached; a new one under the owner + p.settings.search_pane = .new; + typeKeys(p, "/"); + const nid = queryPane2(p, sid).?; + try std.testing.expect(nid != sid); + try std.testing.expect(p.panes[sid].?.attached_to == null); + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, nid)); +} + +fn queryPane2(p: *Pardes, not: usize) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i; + return null; +} -- cgit v1.3 From 8ac6db5662dd2db0f082e1651835f1db36e235f8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 11:57:35 -0300 Subject: Search converge 4/6: the disk engine, Grep and Find's listing on a worker (rg when there, else a sorted walk), generation-numbered batches, a debounce, a 2000-line cap and More, and the declarations parse off the loop --- docs/typ/builtins-gui.json | 1 + docs/typ/builtins-tty.json | 1 + src/Names.zig | 85 +--- src/Query.zig | 190 ++++--- src/Stream.zig | 1177 ++++++++++++++++++++++++++++++++++++++++++++ src/builtins.zig | 8 + src/config.zig | 1 + src/detached/server.zig | 10 + src/detached/wire.zig | 6 +- src/gui/gui.zig | 16 + src/host_io.zig | 35 ++ src/macos.zig | 2 + src/pardes.zig | 23 +- src/syntax.zig | 45 +- src/tagline.zig | 4 +- src/tty/tty.zig | 28 +- 16 files changed, 1462 insertions(+), 170 deletions(-) create mode 100644 src/Stream.zig (limited to 'src/Query.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index a502836e..c238955c 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -81,6 +81,7 @@ {"name": "Messages", "leader": "SPC h m", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the messages shown so far."}, {"name": "Mini", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Open a minimap of the file in braille dots."}, {"name": "Mode", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Cycle the pane's input modes: terminals add raw tty mode to normal/insert."}, + {"name": "More", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "A query pane's Grep stopped at its 2000 lines goes on for 2000 more."}, {"name": "Motion", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "off, crisp, smooth, bouncy, playful", "doc": "How animations move: off, crisp, smooth, bouncy or playful."}, {"name": "Mount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Mount another pardes's 9P tree under /n/, given its dial address."}, {"name": "Msg", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show its argument on this pane's message row."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 7e9ba678..791eef63 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -71,6 +71,7 @@ {"name": "Messages", "leader": "SPC h m", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the messages shown so far."}, {"name": "Mini", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Open a minimap of the file in braille dots."}, {"name": "Mode", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Cycle the pane's input modes: terminals add raw tty mode to normal/insert."}, + {"name": "More", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "A query pane's Grep stopped at its 2000 lines goes on for 2000 more."}, {"name": "Motion", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "off, crisp, smooth, bouncy, playful", "doc": "How animations move: off, crisp, smooth, bouncy or playful."}, {"name": "Mount", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Mount another pardes's 9P tree under /n/, given its dial address."}, {"name": "Msg", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show its argument on this pane's message row."}, diff --git a/src/Names.zig b/src/Names.zig index 48447f56..0c8ba075 100644 --- a/src/Names.zig +++ b/src/Names.zig @@ -1,5 +1,5 @@ //! Names a query pane picks from by a fuzzy query: the files under a -//! directory (walked a slice a frame), the recent files, the open panes, +//! directory (listed by the disk engine, Stream.zig), the recent files, the open panes, //! a file's declarations. Each keystroke scores them again with a small //! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses //! at the starts of words and path segments), a frame's budget at a time, @@ -12,7 +12,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const panes = @import("panes.zig"); const config = @import("config.zig"); -const filesystem = @import("fs.zig"); const Pardes = pardes.Pardes; /// The candidates' rows, back to back, no newlines. @@ -31,9 +30,6 @@ pending: std.ArrayList(u32) = .empty, pending_at: usize = 0, query_buf: [max_query]u8 = undefined, query_len: u8 = 0, -/// The files walk, while it lasts (Find in a query pane until the disk -/// engine has it). -walk: ?Walk = null, /// Bumped whenever `hits` change: the rows are made again only then. gen: u32 = 0, @@ -59,30 +55,10 @@ pub const max_query = 64; /// A candidate is scored over its first this many bytes. const max_text = 512; const max_cands = 200_000; -/// Entries a walk reads a frame: ~1-3 ms warm. -const walk_slice = 2000; -const walk_max_depth = 16; /// A keystroke's scoring, and a frame's: what is left waits a frame. const score_budget_ns = 4 * std.time.ns_per_ms; -const Walk = struct { - root: std.Io.Dir, - walker: std.Io.Dir.SelectiveWalker, - done: bool = false, - skipped: u32 = 0, - - fn deinit(w: *Walk) void { - const io = std.Io.Threaded.global_single_threaded.io(); - // The walker closes a directory only as it leaves it: the ones it - // is still in (all but the root, which is ours) are closed here. - if (w.walker.stack.items.len > 1) for (w.walker.stack.items[1..]) |*item| item.iter.reader.dir.close(io); - w.walker.deinit(); - w.root.close(io); - } -}; - pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { - if (n.walk) |*w| w.deinit(); n.bytes.deinit(gpa); n.lower.deinit(gpa); n.cands.deinit(gpa); @@ -93,8 +69,6 @@ pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { /// No candidates, no walk: for a source filled again. pub fn reset(n: *Names) void { - if (n.walk) |*w| w.deinit(); - n.walk = null; n.bytes.clearRetainingCapacity(); n.lower.clearRetainingCapacity(); n.cands.clearRetainingCapacity(); @@ -136,62 +110,9 @@ pub fn baseOf(path: []const u8) u16 { return @intCast(@min(slash + 1, max_text)); } -/// The files under `dir`, walked from now on a slice a frame (`walkSlice`): -/// the first slice now, so a small tree is whole before the first frame. -pub fn startWalk(n: *Names, gpa: std.mem.Allocator, dir: []const u8) !void { - if (comptime !filesystem.platform_has_fs) return error.NoFilesystem; - const io = std.Io.Threaded.global_single_threaded.io(); - pardes.turn.yield(); - defer pardes.turn.back(); - var dir_handle = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - errdefer dir_handle.close(io); - n.walk = .{ .root = dir_handle, .walker = try dir_handle.walkSelectively(gpa) }; - n.walkSlice(gpa); -} - -/// One frame's slice of a walk: up to `walk_slice` entries, files kept, -/// what a Find skips skipped and dot-directories too. -pub fn walkSlice(n: *Names, gpa: std.mem.Allocator) void { - const w = if (n.walk) |*w| w else return; - if (w.done) return; - const io = std.Io.Threaded.global_single_threaded.io(); - pardes.turn.yield(); - defer pardes.turn.back(); - var steps: usize = 0; - walk: while (steps < walk_slice) : (steps += 1) { - const e = (w.walker.next(io) catch { - w.skipped += 1; - continue; - }) orelse { - w.done = true; - break; - }; - if (e.kind != .directory) { - n.add(gpa, e.path, 0, e.path.len, baseOf(e.path), 0) catch { - w.done = true; - break; - }; - if (n.cands.items.len >= max_cands) { - w.done = true; - break; - } - continue; - } - if (e.depth() >= walk_max_depth or e.basename[0] == '.') continue; - for (filesystem.find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.walker.enter(io, e) catch { - w.skipped += 1; - }; - } -} - -pub fn walking(n: *const Names) bool { - return if (n.walk) |w| !w.done else false; -} - -/// Still walking, or still scoring what it has: it wants the next frame. +/// Still scoring what it has: it wants the next frame. pub fn busy(n: *const Names) bool { - return n.walking() or n.scored < n.cands.items.len or n.pending_at < n.pending.items.len; + return n.scored < n.cands.items.len or n.pending_at < n.pending.items.len; } /// A new query: scored again, from what the last one matched when it only diff --git a/src/Query.zig b/src/Query.zig index fbce95b2..48378a18 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -46,6 +46,7 @@ const colors = @import("colors.zig"); const memory = @import("memory.zig"); const Names = @import("Names.zig"); const Places = @import("Places.zig"); +const Stream = @import("Stream.zig"); const Surface = @import("surface.zig").Surface; const Pardes = pardes.Pardes; const Pane = panes.Pane; @@ -152,16 +153,17 @@ window: struct { lo: usize = 0, hi: usize = 0 } = .{}, /// made every third, the frame's time going to the finding. waited: u8 = 0, names: Names = .{}, -/// A Grep's lines, found a slice a frame (Query.grepSlice). +/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`). found: std.ArrayList(Found) = .empty, found_bytes: std.ArrayList(u8) = .empty, -grep_next: usize = 0, grep_gen: u32 = 0, /// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave /// them (`path:line:col text`, gpa), filtered by what follows the word. lsp_rows: []u8 = &.{}, /// The +Preview under this pane, by serial; 0, none. preview: u32 = 0, +/// Its disk search waits at its cap: the tag says More. +capped: bool = false, /// A reused pane's frozen rows when a new query began in it: Esc brings /// them back. saved: ?Saved = null, @@ -387,7 +389,7 @@ pub fn busy(p: *const Pardes) bool { const pane = slot orelse continue; const q = pane.query orelse continue; if (q.frozen) continue; - if (q.names.busy() or (q.source == .grep and q.grep_next < q.names.cands.items.len) or q.made_rev != q.seen_rev) return true; + if (q.names.busy() or p.stream.busyFor(pane.serial) or q.made_rev != q.seen_rev) return true; } return false; } @@ -482,32 +484,29 @@ fn produce(p: *Pardes, id: usize, tick: bool) void { makeAllRows(p, id) catch |err| p.reportError(id, "search", err); }, .find, .recent, .panes, .symbols => { - if (tick) q.names.walkSlice(p.gpa); if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa); if (q.names.gen == q.made_gen and !changed) return; q.made_gen = q.names.gen; makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); }, .grep => { + const dir = std.fs.path.dirname(f.path) orelse "/"; if (changed) { q.found.clearRetainingCapacity(); q.found_bytes.clearRetainingCapacity(); - q.grep_next = 0; q.grep_gen +%= 1; + q.current = null; + // On the disk engine's worker, once the typing pauses. + if (a.pat.len > 0) Stream.query(p, rp.serial, .grep, a.pat, dir, .typed) else if (p.stream.target == rp.serial) { + _ = p.stream.stop(); + } + feedGrepPlaces(p, q, rp.serial, a.pat); } - if (a.pat.len == 0) { - if (changed) makeGrepRows(p, id) catch {}; - return; - } - if (tick or changed) { - q.names.walkSlice(p.gpa); - grepSlice(p, q, rp, a.pat); - } - const gen: u64 = (@as(u64, q.grep_gen) << 32) | q.found.items.len; - if (gen == q.made_gen and !changed and !(q.grep_next >= q.names.cands.items.len and q.more)) return; + const searching = p.stream.target == rp.serial and p.stream.state != .done and p.stream.state != .stopped and p.stream.state != .failed and p.stream.state != .idle; + const gen: u64 = (@as(u64, q.grep_gen) << 32) | (q.found.items.len << 1) | @intFromBool(searching); + if (gen == q.made_gen and !changed) return; q.made_gen = gen; - makeGrepRows(p, id) catch |err| p.reportError(id, "search", err); - if (changed or q.current == null) feedGrepPlaces(p, q, rp.serial, a.pat); + makeGrepRows(p, id, false) catch |err| p.reportError(id, "search", err); }, .refs, .defs, .impls, .diagnostics => { if (changed and q.lsp_rows.len == 0) { @@ -544,11 +543,12 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz q.names.reset(); q.found.clearRetainingCapacity(); q.found_bytes.clearRetainingCapacity(); - q.grep_next = 0; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; const gpa = p.gpa; switch (source) { - .find, .grep => q.names.startWalk(gpa, dir) catch |err| p.reportError(id, "search", err), + // The files under the directory, listed once on the disk engine's + // worker (rg --files, else the walk); each keystroke scores them. + .find => Stream.query(p, rp.serial, .files, "", dir, .now), .recent => { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); @@ -575,7 +575,11 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz const oid = owner_id orelse return; const owner = p.panes[oid].?; const f = if (owner.file) |*file| file else return; - const decls = ownerDecls(p, f, true) orelse return; + const decls = ownerDecls(p, f, false) orelse { + // Parsed on the worker; listed when it is done (declsArrived). + Stream.parseFor(p, oid); + return; + }; for (decls) |d| { const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)]; const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); @@ -821,6 +825,8 @@ fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { defer out.deinit(p.gpa); var rows: std.ArrayList(locations.Row) = .empty; var budget: usize = if (full) max_rows else live_rows; + // Grouped once a parse of the text exists: asked of the worker now. + if (ownerDecls(p, &owner.file.?, false) == null) Stream.parseFor(p, oid); const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); const from = if (full) 0 else at -| live_rows / 2; q.window = .{ .lo = from, .hi = from }; @@ -927,6 +933,7 @@ fn firstHit(q: *const Query) ?usize { /// `k` from the current row: the hits on the rows before it, and its own. fn countCurrent(q: *Query) void { + if (q.source == .grep) return countGrepCurrent(q); q.k = 0; const c = q.current orelse return; for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0; @@ -992,7 +999,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { const f = &rp.file.?; f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; q.total = q.names.hits.items.len; - q.more = q.names.busy(); + q.more = q.names.busy() or p.stream.busyFor(rp.serial); // The best is current until a step or a click moves it. q.current = if (shown > 0) 0 else null; countCurrent(q); @@ -1000,70 +1007,30 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { showTarget(p, id); } -/// A slice of a Grep: the files the walk has found so far read and -/// searched, about 4 ms of them a frame, each line holding the pattern -/// (a literal, smart case: a capital makes it exact) kept. -/// ponytail: on the loop, a file a step; the disk engine's worker (phase -/// 4) takes this over. -fn grepSlice(p: *Pardes, q: *Query, rp: *Pane, pat: []const u8) void { - const started = Places.nowNs(); - const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; - const fold = for (pat) |c| { - if (std.ascii.isUpper(c)) break false; - } else true; - var low_buf: [256]u8 = undefined; - const needle = if (fold) std.ascii.lowerString(low_buf[0..@min(pat.len, low_buf.len)], pat[0..@min(pat.len, low_buf.len)]) else pat; - while (q.grep_next < q.names.cands.items.len) { - if (q.found.items.len >= grep_cap) break; - const c = q.names.cands.items[q.grep_next]; - q.grep_next += 1; - const rel = q.names.bytes.items[c.start..][0..c.len]; - var pathbuf: [4096 + 8]u8 = undefined; - const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; - const bytes = blk: { - pardes.turn.yield(); - defer pardes.turn.back(); - break :blk filesystem.read(p, path) catch continue; - }; - defer p.gpa.free(bytes); - if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) continue; - var line_no: u32 = 1; - var ls: usize = 0; - while (ls <= bytes.len) { - const le = std.mem.indexOfScalarPos(u8, bytes, ls, '\n') orelse bytes.len; - const ln = bytes[ls..le]; - const at = if (fold) std.ascii.findIgnoreCase(ln, needle) else std.mem.indexOf(u8, ln, needle); - if (at) |col| { - const path_at: u32 = @intCast(q.found_bytes.items.len); - q.found_bytes.appendSlice(p.gpa, rel) catch return; - const code_at: u32 = @intCast(q.found_bytes.items.len); - const code = ln[0..@min(ln.len, 400)]; - q.found_bytes.appendSlice(p.gpa, code) catch return; - q.found.append(p.gpa, .{ .path = path_at, .path_len = @intCast(rel.len), .line = line_no, .col = @intCast(col), .end = @intCast(col + needle.len), .code = code_at, .code_len = @intCast(code.len) }) catch return; - if (q.found.items.len >= grep_cap) break; - } - if (le == bytes.len) break; - ls = le + 1; - line_no += 1; - } - if (started != 0 and Places.nowNs() - started > Places.frame_ns) break; - } -} - /// A Grep keeps this many lines: the rest wait (the disk engine's `More`). pub const grep_cap = 2000; -fn makeGrepRows(p: *Pardes, id: usize) !void { +/// A Grep's rows: each file's name over its lines, while typed a window +/// of `live_rows` around the current one, `full` (frozen) every one sent. +fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { const rp = p.panes[id].?; const q = rp.query.?; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const at: usize = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].hit else 0) else 0; q.items.clearRetainingCapacity(); var out: std.ArrayList(u8) = .empty; defer out.deinit(p.gpa); var rows: std.ArrayList(locations.Row) = .empty; var last_path: []const u8 = ""; var pathbuf: [4096 + 8]u8 = undefined; - for (q.found.items, 0..) |fd, i| { + const lo = if (full) 0 else at -| live_rows / 2; + const hi = if (full) q.found.items.len else @min(q.found.items.len, lo + live_rows); + if (lo > 0) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} lines before these", .{lo}) catch " ..."); + } + var current: ?usize = null; + for (q.found.items[lo..hi], lo..) |fd, i| { const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; if (!std.mem.eql(u8, rel, last_path)) { @@ -1072,19 +1039,62 @@ fn makeGrepRows(p: *Pardes, id: usize) !void { try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); } const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + if (i == at) current = q.items.items.len; try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); } - const walking = q.names.walking() or q.grep_next < q.names.cands.items.len; - if (q.found.items.len >= grep_cap) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: type more of it"); + if (hi < q.found.items.len) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} lines after these", .{q.found.items.len - hi}) catch " ..."); + } + if (p.stream.target == rp.serial and p.stream.state == .capped) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: More in the tag goes on"); setRows(p, rp, &out, &rows); q.total = q.found.items.len; - q.more = walking and q.found.items.len < grep_cap; - if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); - countCurrent(q); + q.more = p.stream.busyFor(rp.serial); + q.current = current orelse firstHit(q); + countGrepCurrent(q); showCurrent(rp); } +/// `k` for a Grep: the current row's line among all the lines sent. +fn countGrepCurrent(q: *Query) void { + q.k = 0; + const c = q.current orelse return; + if (c < q.items.items.len and q.items.items[c].kind == .hit) q.k = q.items.items[c].hit + 1; +} + +/// The disk engine's rows for query pane `q` (Stream.receive): a Grep's +/// lines (`path:line:col-end code`, relative to the pane's directory) kept +/// as found, a listing's names added to what Find scores. +pub fn take(p: *Pardes, q: *Query, kind: Stream.Kind, rows: []const u8) void { + var lines = std.mem.splitScalar(u8, rows, '\n'); + while (lines.next()) |ln| { + if (ln.len == 0) continue; + switch (kind) { + .files => q.names.add(p.gpa, ln, 0, ln.len, Names.baseOf(ln), 0) catch return, + .grep => { + const t = look.parsePathLine(ln); + if (t.at.line == 0 or t.path.len == 0) continue; + const code = if (t.end < ln.len) ln[t.end + 1 ..] else ""; + const path_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, t.path) catch return; + const code_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, code) catch return; + q.found.append(p.gpa, .{ + .path = path_at, + .path_len = @intCast(t.path.len), + .line = @intCast(t.at.line), + .col = @intCast(t.at.col -| 1), + .end = @intCast(if (t.at.end_col > 0) t.at.end_col else t.at.col), + .code = code_at, + .code_len = @intCast(code.len), + }) catch return; + }, + } + } + q.names.gen +%= 1; +} + /// A Grep's hits in each open file are that pane's places: its tints, /// ticks and n/N. fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void { @@ -1552,6 +1562,8 @@ pub fn land(p: *Pardes, id: usize, row: ?usize) void { } return; }; + // A Grep's whole list, now it is a result. + if (q.source == .grep) makeGrepRows(p, id, true) catch {}; var buf: [4096 + 64]u8 = undefined; const address = if (meta.at.line > 0) std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path @@ -1634,8 +1646,26 @@ pub fn cancel(p: *Pardes, id: usize) void { } else p.removePane(id, null) catch {}; } -/// The pane going (Del, its owner's Del): the places it fed go with it. +/// A parse of pane `serial`'s text came back (Stream.receiveParse): its +/// query panes' rows are made again, under the declarations now, and a +/// Symbols query gathers them. +pub fn declsArrived(p: *Pardes, serial: u32) void { + for (p.panes, 0..) |slot, id| { + const rp = slot orelse continue; + const q = rp.query orelse continue; + if (q.owner != serial or q.frozen) continue; + q.made_gen = std.math.maxInt(u64); + if (q.source == .symbols) { + startSource(p, id, q, .symbols, p.paneBySerial(serial)); + if (parse(q.asked)) |a| q.names.typed(p.gpa, a.pat); + } + } +} + +/// The pane going (Del, its owner's Del): the places it fed go with it, +/// and a disk search still running for it. pub fn release(p: *Pardes, pane: *Pane) void { + if (p.stream.target == pane.serial) _ = p.stream.stop(); for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) { tp.places.forget(p.gpa); tp.places.clear(p.gpa); @@ -1932,6 +1962,8 @@ fn leader(p: *Pardes, keys: []const u8) void { } fn settle(p: *Pardes) void { + // a typed Grep's pause run out on the clock + p.advance(p.now_ns + Stream.debounce_ns + std.time.ns_per_ms); var frames: usize = 0; while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick); p.update(.tick); diff --git a/src/Stream.zig b/src/Stream.zig new file mode 100644 index 00000000..eb420b42 --- /dev/null +++ b/src/Stream.zig @@ -0,0 +1,1177 @@ +//! The disk engine: a query pane's Grep, and the file listing its Find +//! scores, run on a worker thread away from the loop (lifted from the +//! stream prototype). ripgrep when `rg` is on PATH (`rg --json --sort path +//! --fixed-strings --smart-case`, `rg --files --sort path`: it knows +//! .gitignore and is 5-15x faster on a real tree), else pardes's own sorted +//! walk with fs.zig's skips. Rows come back in batches, each stamped with +//! the generation it was started for; a new query bumps the generation and +//! cancels the worker, and the loop drops any batch that is not the live +//! generation's (the race test proves it). A typed Grep starts once the +//! typing pauses (`debounce_ns`); a worker stops at `soft_cap` hits and +//! waits there for `More`. Embedded in Pardes as `stream`: one search on +//! disk at a time, the query pane `target` names. +//! +//! Hosts with workers perform the `search` effect (host_io.Host.search): +//! `start` runs `work` on io.concurrent, posting through the shell's +//! inbox. A host without (a test, a board) runs it on the loop (`runHere`), +//! its cap a hard stop. +const Stream = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const look = @import("look.zig"); +const panes = @import("panes.zig"); +const syntax = @import("syntax.zig"); +const Pardes = pardes.Pardes; + +pub const Kind = enum { grep, files }; +pub const Engine = enum { rg, walk }; +pub const State = enum { idle, waiting, searching, capped, done, stopped, failed }; + +/// A keystroke's Grep starts when no other has come for this long. +pub const debounce_ns = 80 * std.time.ns_per_ms; +/// Hits (a Grep's lines, a listing's files) a worker sends before it waits +/// for More. +pub const soft_cap = 2000; +/// A listing of files keeps going this far before it waits: the names are +/// scored on the loop, the cap is for a runaway tree. +pub const files_cap = 200_000; +/// A worker's batch goes once its first row is this old, or it is this big; +/// the first batch goes at its first file with a hit. +const batch_ns = 16 * std.time.ns_per_ms; +const batch_bytes = 256 * 1024; +/// A bigger file is not searched. +const max_file_bytes = 16 << 20; + +/// What a worker sends: rows as fs.zig wrote them (`path:line:col-end +/// text`, a listing's `path`), relative to the search's directory. Owned by +/// the message until taken; the core copies what it keeps. +pub const Batch = struct { + gen: u32, + rows: []u8 = &.{}, + hits: u32 = 0, + /// Files with a hit in this batch's rows. + files: u32 = 0, + /// Files read since the last batch (rg: all of them, at its end). + scanned: u32 = 0, + /// Directories it might not open. + skipped: u32 = 0, + engine: Engine = .walk, + /// The worker waits at its soft cap until More. + capped: bool = false, + end: ?End = null, + /// The worker's own time, start to end (in the last batch). + took_ns: u64 = 0, + /// A parse's answer (`parseFor`): the declarations of pane `serial`'s + /// text at `revision`. + parsed: ?struct { serial: u32, revision: u32 } = null, + decls: []syntax.ContextDeclaration = &.{}, + + pub const End = enum { done, failed }; + + pub fn deinit(b: *const Batch, gpa: std.mem.Allocator) void { + gpa.free(b.rows); + gpa.free(b.decls); + } +}; + +/// A parse of a pane's text for its declarations, on a worker: the rows of +/// a `/` group under them, and Symbols lists them, once it is done. The +/// loop never parses a big text (a 1.2 MB file is seconds in Debug). +pub const ParseJob = struct { + gpa: std.mem.Allocator, + /// What its answer is made with: the shell's, which frees a batch. + out: std.mem.Allocator, + gen: u32, + serial: u32, + revision: u32, + path: []u8, + content: []u8, + /// Set when it is no longer wanted: the parse ends early. + stop: std.atomic.Value(bool) = .init(false), + + pub fn deinit(job: *ParseJob) void { + job.gpa.free(job.path); + job.gpa.free(job.content); + job.gpa.destroy(job); + } +}; + +const ParseTask = struct { job: *ParseJob, future: ?std.Io.Future(void) = null, io: ?std.Io = null }; + +/// Where a worker hands a batch: false when it was turned away (the inbox +/// closed, the wait for room canceled), and the worker stops. +pub const Sink = *const fn (ctx: ?*anyopaque, batch: Batch) bool; + +/// One search, the worker's: copied from the core when it starts. +pub const Job = struct { + gpa: std.mem.Allocator, + gen: u32, + kind: Kind, + pattern: []u8, + /// Rows name files relative to this, the query pane's directory, which + /// is also the one root searched. + base: []u8, + /// Forced (tests, PARDES_STREAM_ENGINE); else rg when there is one. + engine: ?Engine, + /// Hits it may send before it waits; More raises it and wakes it. Run + /// on the loop (no worker) it is a hard stop. + cap: std.atomic.Value(u32) = .init(soft_cap), + waits: bool = true, + + pub fn deinit(job: *Job) void { + const gpa = job.gpa; + gpa.free(job.pattern); + gpa.free(job.base); + gpa.destroy(job); + } +}; + +const Task = struct { job: *Job, future: std.Io.Future(void), io: std.Io }; + +gen: u32 = 0, +state: State = .idle, +kind: Kind = .grep, +/// The query pane the rows are for, by serial. +target: u32 = 0, +pattern: std.ArrayList(u8) = .empty, +dir: std.ArrayList(u8) = .empty, +/// A typed query's start, once the pause runs out (step). +due_ns: ?u64 = null, +task: ?Task = null, +/// Forced engine (tests); null, rg when it runs. +engine: ?Engine = null, +used: Engine = .walk, +hits: u32 = 0, +files: u32 = 0, +scanned: u32 = 0, +skipped: u32 = 0, +/// Stale batches dropped (the race test counts them). +dropped: usize = 0, +started_ns: u64 = 0, +first_ns: ?u64 = null, +finished_ns: u64 = 0, +worker_ns: u64 = 0, +/// The parse running or about to (one at a time), its generation, and the +/// one asked for while it ran (pane serial and revision), started after it. +parse: ?ParseTask = null, +parse_gen: u32 = 0, +parse_next: ?struct { serial: u32, revision: u32 } = null, +/// What the last parse cost the worker. +parse_ns: u64 = 0, + +pub fn deinit(s: *Stream, gpa: std.mem.Allocator) void { + s.cancelTask(); + s.cancelParse(); + s.pattern.deinit(gpa); + s.dir.deinit(gpa); +} + +/// The parse's worker told to stop and joined: short, its progress +/// callback hears the flag. +pub fn cancelParse(s: *Stream) void { + const t = s.parse orelse return; + s.parse = null; + t.job.stop.store(true, .release); + if (t.future) |f| { + pardes.turn.yield(); + var future = f; + future.cancel(t.io.?); + pardes.turn.back(); + } + t.job.deinit(); +} + +/// Pane `id`'s declarations asked for, as its text is now, unless a parse of +/// that text is already on its way. With workers, on one; without (a test), +/// here only for a small text, else not at all (the rows stay ungrouped). +pub fn parseFor(p: *Pardes, id: usize) void { + const s = &p.stream; + const pane = p.panes[id] orelse return; + const f = pane.file orelse return; + if (!syntax.supportsPath(f.path) or f.content.len == 0) return; + if (s.parse) |t| { + if (t.job.serial == pane.serial and t.job.revision == f.revision) return; + // A parse of a text that has changed since: told to stop; this one + // after it. + t.job.stop.store(true, .release); + s.parse_next = .{ .serial = pane.serial, .revision = f.revision }; + return; + } + const workers = p.host.vtable.search != null and !p.fs.serving; + if (!workers and f.content.len > 64 << 10) return; + const job = p.gpa.create(ParseJob) catch return; + const path = p.gpa.dupe(u8, f.path) catch { + p.gpa.destroy(job); + return; + }; + const content = p.gpa.dupe(u8, f.content) catch { + p.gpa.free(path); + p.gpa.destroy(job); + return; + }; + s.gen +%= 1; + s.parse_gen = s.gen; + job.* = .{ .gpa = p.gpa, .out = p.gpa, .gen = s.parse_gen, .serial = pane.serial, .revision = f.revision, .path = path, .content = content }; + s.parse = .{ .job = job }; + if (workers) return p.emit(.{ .search = .{ .gen = s.parse_gen } }); + // Here and now: a small text, a host with no workers. + var got: Collect = .{ .gpa = p.gpa }; + defer got.batches.deinit(p.gpa); + parseWork(std.Io.Threaded.global_single_threaded.io(), job, &got, Collect.take); + for (got.batches.items) |*b| { + receive(p, b); + b.deinit(p.gpa); + } +} + +fn parseWork(io: std.Io, job: *ParseJob, ctx: ?*anyopaque, sink: Sink) void { + const began = std.Io.Clock.awake.now(io); + const decls: []syntax.ContextDeclaration = syntax.declarationsApart(job.out, job.path, job.content, &job.stop) catch @constCast(&[_]syntax.ContextDeclaration{}); + const took: u64 = @intCast(@max(0, began.durationTo(std.Io.Clock.awake.now(io)).nanoseconds)); + _ = sink(ctx, .{ .gen = job.gen, .decls = decls, .parsed = .{ .serial = job.serial, .revision = job.revision }, .end = .done, .took_ns = took }); +} + +fn now() u64 { + if (comptime !filesystem.platform_has_fs) return 0; + const t = std.Io.Clock.awake.now(std.Io.Threaded.global_single_threaded.io()); + return @intCast(@max(0, t.nanoseconds)); +} + +/// Joins the worker, if one runs: a cancel interrupts its waits and reads, +/// so this is short. The turn goes out for it, as for any blocking call: +/// the worker may be reading through a mount of this very session. +pub fn cancelTask(s: *Stream) void { + const t = s.task orelse return; + s.task = null; + pardes.turn.yield(); + var future = t.future; + future.cancel(t.io); + pardes.turn.back(); + t.job.deinit(); +} + +/// A new question for query pane `target`: a Grep of `pattern`, or the +/// listing of the files (`.files`), under `dir`. The generation before it +/// is over (its worker canceled, its batches dropped when they come); +/// `typed`, it starts once the typing pauses, else at the next step. +pub fn query(p: *Pardes, target: u32, kind: Kind, pattern: []const u8, dir: []const u8, how: enum { typed, now }) void { + const s = &p.stream; + s.cancelTask(); + s.gen +%= 1; + s.kind = kind; + s.target = target; + s.pattern.clearRetainingCapacity(); + s.pattern.appendSlice(p.gpa, pattern) catch return; + s.dir.clearRetainingCapacity(); + s.dir.appendSlice(p.gpa, dir) catch return; + s.hits = 0; + s.files = 0; + s.scanned = 0; + s.skipped = 0; + s.first_ns = null; + s.state = .waiting; + s.due_ns = if (how == .typed) p.now_ns + debounce_ns else p.now_ns; +} + +/// Over: the worker canceled, nothing more of it lands. +pub fn stop(s: *Stream) bool { + if (s.state != .waiting and s.state != .searching and s.state != .capped) return false; + s.cancelTask(); + s.due_ns = null; + s.gen +%= 1; + s.state = .stopped; + s.finished_ns = now(); + return true; +} + +/// More: a worker waiting at its cap goes on for another `soft_cap` hits. +pub fn more(s: *Stream) bool { + if (s.state != .capped) return false; + const t = s.task orelse return false; + _ = t.job.cap.fetchAdd(soft_cap, .release); + t.io.futexWake(u32, &t.job.cap.raw, 1); + s.state = .searching; + return true; +} + +/// The `More` word: the query pane's disk search past its cap. +pub fn moreFor(p: *Pardes, id: usize) bool { + if (!p.stream.more()) return false; + if (p.panes[id]) |pane| if (pane.query) |q| { + q.capped = false; + }; + if (p.paneBySerial(p.stream.target)) |tid| if (p.panes[tid].?.query) |q| { + q.capped = false; + }; + return true; +} + +/// Whether query pane `serial`'s rows are still coming. +pub fn busyFor(s: *const Stream, serial: u32) bool { + return s.target == serial and (s.state == .waiting or s.state == .searching); +} + +/// On each tick: a query whose pause ran out starts, on a worker where the +/// host has one, else here and now. +pub fn step(p: *Pardes) void { + const s = &p.stream; + const due = s.due_ns orelse return; + if (p.now_ns < due) return; + s.due_ns = null; + s.state = .searching; + s.started_ns = now(); + // A script's write (whose answer says whether it found anything) and a + // host with no workers: done before this returns. + if (p.host.vtable.search != null and !p.fs.serving) p.emit(.{ .search = .{ .gen = s.gen } }) else runHere(p, s.gen); +} + +/// When the core next needs a tick for the stream: the end of the pause. +pub fn wake(s: *const Stream, next_frame: u64) ?u64 { + const due = s.due_ns orelse return null; + return @max(due, next_frame); +} + +/// Start generation `gen` on a worker that sends to `sink` (a shell's +/// inbox). Called by the shell for the `search` effect, on the loop. +pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: Sink) void { + const s = &p.stream; + // A parse's generation: its own task. + if (s.parse) |*t| if (gen == s.parse_gen and t.job.gen == gen and t.future == null) { + t.job.out = gpa; + t.future = io.concurrent(parseWork, .{ io, t.job, ctx, sink }) catch { + const job = t.job; + s.parse = null; + job.deinit(); + return; + }; + t.io = io; + return; + }; + if (gen != s.gen or s.state != .searching) return; + s.cancelTask(); + const job = makeJob(gpa, s) catch |err| { + s.state = .failed; + return p.reportError(p.active, "search", err); + }; + const future = io.concurrent(work, .{ io, job, ctx, sink }) catch { + // No worker to be had: it runs here, on the loop. + job.deinit(); + return runHere(p, gen); + }; + s.task = .{ .job = job, .future = future, .io = io }; +} + +fn makeJob(gpa: std.mem.Allocator, s: *const Stream) !*Job { + const job = try gpa.create(Job); + errdefer gpa.destroy(job); + const pattern = try gpa.dupe(u8, s.pattern.items); + errdefer gpa.free(pattern); + const base = try gpa.dupe(u8, s.dir.items); + job.* = .{ .gpa = gpa, .gen = s.gen, .kind = s.kind, .pattern = pattern, .base = base, .engine = s.engine }; + if (s.kind == .files) job.cap = .init(files_cap); + return job; +} + +/// A host with no workers (a test's, the fallback when none can be had): +/// the whole search on the loop, the turn out for it, its batches taken in +/// as a worker's would be. Its cap is a hard stop. +pub fn runHere(p: *Pardes, gen: u32) void { + if (comptime !filesystem.platform_has_fs) { + p.stream.state = .failed; + return; + } + const s = &p.stream; + if (gen != s.gen or s.state != .searching) return; + const job = makeJob(p.gpa, s) catch |err| { + s.state = .failed; + return p.reportError(p.active, "search", err); + }; + defer job.deinit(); + job.waits = false; + var got: Collect = .{ .gpa = p.gpa }; + defer got.batches.deinit(p.gpa); + { + pardes.turn.yield(); + defer pardes.turn.back(); + work(std.Io.Threaded.global_single_threaded.io(), job, &got, Collect.take); + } + for (got.batches.items) |*b| { + receive(p, b); + b.deinit(p.gpa); + } +} + +const Collect = struct { + gpa: std.mem.Allocator, + batches: std.ArrayList(Batch) = .empty, + + fn take(ctx: ?*anyopaque, batch: Batch) bool { + const c: *Collect = @ptrCast(@alignCast(ctx.?)); + c.batches.append(c.gpa, batch) catch { + batch.deinit(c.gpa); + return false; + }; + return true; + } +}; + +/// A batch from a worker (`Event.search`), borrowed: the live generation's +/// rows go to its query pane (a Grep's lines, a listing's names); any other +/// generation's are dropped whole. +pub fn receive(p: *Pardes, b: *const Batch) void { + const s = &p.stream; + if (b.parsed) |parsed| return receiveParse(p, b, parsed.serial, parsed.revision); + if (b.gen != s.gen or (s.state != .searching and s.state != .capped)) { + s.dropped += 1; + return; + } + s.used = b.engine; + s.hits += b.hits; + s.files += b.files; + s.scanned += b.scanned; + s.skipped += b.skipped; + if (s.first_ns == null and b.rows.len > 0) s.first_ns = now(); + if (b.capped) s.state = .capped; + if (b.end) |end| { + s.worker_ns = b.took_ns; + s.state = if (end == .failed) .failed else .done; + s.finished_ns = now(); + // It sent its last: its join is a return away. + if (s.task) |t| { + s.task = null; + pardes.turn.yield(); + var future = t.future; + future.await(t.io); + pardes.turn.back(); + t.job.deinit(); + } + } + p.needs_frame = true; + const id = p.paneBySerial(s.target) orelse return; + const q = p.panes[id].?.query orelse return; + q.capped = s.state == .capped; + panes.Query.take(p, q, s.kind, b.rows); +} + +/// A parse's answer: its task joined; the declarations kept as the pane's +/// (File.State.context_declarations, for its revision) when its text is +/// still what was parsed; the query panes of that text told; and a parse +/// asked for while it ran started. +fn receiveParse(p: *Pardes, b: *const Batch, serial: u32, revision: u32) void { + const s = &p.stream; + if (s.parse) |t| if (t.job.gen == b.gen) { + s.parse = null; + if (t.future) |f| { + pardes.turn.yield(); + var future = f; + future.await(t.io.?); + pardes.turn.back(); + } + t.job.deinit(); + }; + s.parse_ns = b.took_ns; + if (p.paneBySerial(serial)) |id| if (p.panes[id].?.file) |*f| if (f.revision == revision and b.decls.len > 0) { + if (p.tree_sitter_gpa.dupe(syntax.ContextDeclaration, b.decls)) |copy| { + if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); + f.context_declarations = copy; + f.context_revision = revision; + panes.Query.declsArrived(p, serial); + } else |_| {} + }; + p.needs_frame = true; + if (s.parse_next) |next| { + s.parse_next = null; + if (p.paneBySerial(next.serial)) |id| parseFor(p, id); + } +} + +// ---- the worker ---- + +const Worker = struct { + io: std.Io, + gpa: std.mem.Allocator, + job: *Job, + ctx: ?*anyopaque, + sink: Sink, + engine: Engine = .walk, + exact: bool, + rows: std.ArrayList(u8) = .empty, + hits: u32 = 0, + files: u32 = 0, + scanned: u32 = 0, + skipped: u32 = 0, + total: u32 = 0, + sent: bool = false, + batch_began: ?std.Io.Timestamp = null, + began: std.Io.Timestamp, + /// One read buffer for every file: grown to the biggest, never 0xAA'd per file. + buf: std.ArrayList(u8) = .empty, + + fn deinit(w: *Worker) void { + w.rows.deinit(w.gpa); + w.buf.deinit(w.gpa); + } + + fn send(w: *Worker, end: ?Batch.End, capped: bool) error{ Refused, OutOfMemory }!void { + const rows = try w.rows.toOwnedSlice(w.gpa); + const batch: Batch = .{ + .gen = w.job.gen, + .rows = rows, + .hits = w.hits, + .files = w.files, + .scanned = w.scanned, + .skipped = w.skipped, + .engine = w.engine, + .capped = capped, + .end = end, + .took_ns = if (end != null) @intCast(@max(0, w.began.durationTo(std.Io.Clock.awake.now(w.io)).nanoseconds)) else 0, + }; + w.hits = 0; + w.files = 0; + w.scanned = 0; + w.skipped = 0; + w.sent = true; + w.batch_began = null; + if (!w.sink(w.ctx, batch)) return error.Refused; + } + + /// After a file with hits: the first batch goes at once (what the user + /// sees first), the others once old or big enough. + fn maybeSend(w: *Worker) !void { + if (w.rows.items.len == 0) return; + const began = w.batch_began orelse { + w.batch_began = std.Io.Clock.awake.now(w.io); + if (!w.sent) try w.send(null, false); + return; + }; + const age = began.durationTo(std.Io.Clock.awake.now(w.io)).nanoseconds; + if (age >= batch_ns or w.rows.items.len >= batch_bytes) try w.send(null, false); + } + + /// At the cap, what is gathered goes, and the worker waits for More (a + /// cancel ends the wait); on the loop it is the end. + fn checkCap(w: *Worker) !bool { + var cap = w.job.cap.load(.acquire); + if (w.total < cap) return false; + if (!w.job.waits) return true; + try w.send(null, true); + while (w.total >= cap) { + try w.io.futexWait(u32, &w.job.cap.raw, cap); + cap = w.job.cap.load(.acquire); + } + return false; + } + + /// Smart case: a pattern with a capital matches exactly, else in any case. + fn find(w: *const Worker, hay: []const u8) ?usize { + return if (w.exact) std.mem.indexOf(u8, hay, w.job.pattern) else std.ascii.findIgnoreCase(hay, w.job.pattern); + } + + fn grepText(w: *Worker, path: []const u8, text: []const u8) !u32 { + var found: u32 = 0; + var line: usize = 0; + var it = std.mem.splitScalar(u8, text, '\n'); + while (it.next()) |raw| { + line += 1; + if (w.total >= w.job.cap.load(.acquire)) break; + const at = w.find(raw) orelse continue; + try w.row(path, line, at, at + w.job.pattern.len, raw); + found += 1; + } + return found; + } + + fn row(w: *Worker, path: []const u8, line: usize, from: usize, end: usize, raw: []const u8) !void { + const ln = std.mem.trimEnd(u8, raw, " \t\r\n"); + var cut = @min(ln.len, 400); + while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; + try w.rows.print(w.gpa, "{s}:{d}:{d}{c}{d} {s}\n", .{ path, line, from + 1, config.range_sep, end, ln[0..cut] }); + w.hits += 1; + w.total += 1; + } + + /// A listing's file: its name, relative to the base. + fn file(w: *Worker, path: []const u8) !bool { + try w.rows.print(w.gpa, "{s}\n", .{path}); + w.hits += 1; + w.total += 1; + w.files += 1; + try w.maybeSend(); + return w.checkCap(); + } + + /// The name a row gives `abs`: under the base, relative to it. + fn shown(w: *const Worker, abs: []const u8) []const u8 { + const base = std.mem.trimEnd(u8, w.job.base, "/"); + if (abs.len > base.len + 1 and std.mem.startsWith(u8, abs, base) and abs[base.len] == '/') return abs[base.len + 1 ..]; + if (std.mem.startsWith(u8, abs, "./")) return abs[2..]; + return abs; + } + + // ---- our own walk: sorted, depth first, fs.zig's skips ---- + + fn walk(w: *Worker) !void { + var dir = std.Io.Dir.cwd().openDir(w.io, w.job.base, .{ .iterate = true }) catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return, + }; + defer dir.close(w.io); + _ = try w.walkDir(dir, "", 0); + } + + /// Whether the cap ended it (on the loop). + fn walkDir(w: *Worker, dir: std.Io.Dir, prefix: []const u8, depth: usize) anyerror!bool { + try w.io.checkCancel(); + var arena: std.heap.ArenaAllocator = .init(w.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const Entry = struct { name: []const u8, kind: std.Io.File.Kind }; + var entries: std.ArrayList(Entry) = .empty; + var it = dir.iterate(); + while (true) { + const e = it.next(w.io) catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => { + w.skipped += 1; + break; + }, + } orelse break; + try entries.append(a, .{ .name = try a.dupe(u8, e.name), .kind = e.kind }); + } + std.mem.sort(Entry, entries.items, {}, struct { + fn lt(_: void, x: Entry, y: Entry) bool { + return std.mem.lessThan(u8, x.name, y.name); + } + }.lt); + for (entries.items) |e| { + const path = if (prefix.len == 0) e.name else try std.fmt.allocPrint(a, "{s}/{s}", .{ prefix, e.name }); + switch (e.kind) { + .directory => { + if (depth + 1 >= filesystem.WalkNotes.max_depth or e.name[0] == '.') continue; + if (for (filesystem.find_skip) |skip| { + if (std.mem.eql(u8, e.name, skip)) break true; + } else false) continue; + var sub = dir.openDir(w.io, e.name, .{ .iterate = true }) catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => { + w.skipped += 1; + continue; + }, + }; + defer sub.close(w.io); + if (try w.walkDir(sub, path, depth + 1)) return true; + }, + .file => switch (w.job.kind) { + .grep => if (try w.grepFile(dir, e.name, path)) return true, + .files => if (try w.file(path)) return true, + }, + else => {}, + } + } + return false; + } + + fn grepFile(w: *Worker, dir: std.Io.Dir, name: []const u8, path: []const u8) !bool { + const f = dir.openFile(w.io, name, .{}) catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return false, + }; + defer f.close(w.io); + const len = f.length(w.io) catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return false, + }; + // ponytail: a file past 16 MiB is passed over unsaid; a chunked + // read, as fs.grep's, would search it. + if (len > max_file_bytes) return false; + try w.buf.resize(w.gpa, @intCast(len)); + const n = f.readPositionalAll(w.io, w.buf.items, 0) catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return false, + }; + const text = w.buf.items[0..n]; + w.scanned += 1; + if (std.mem.indexOfScalar(u8, text[0..@min(text.len, 1024)], 0) != null) return false; + const found = try w.grepText(path, text); + if (found == 0) return false; + w.files += 1; + try w.maybeSend(); + return w.checkCap(); + } + + // ---- ripgrep: a child on the worker, parsed, never shown ---- + + /// error.NoRipgrep when there is none to run: the walk does it. + fn ripgrep(w: *Worker) !void { + var argv: std.ArrayList([]const u8) = .empty; + defer argv.deinit(w.gpa); + switch (w.job.kind) { + .grep => { + try argv.appendSlice(w.gpa, &.{ "rg", "--json", "--sort", "path", "--fixed-strings", "--smart-case", "--no-messages", "--" }); + try argv.append(w.gpa, w.job.pattern); + }, + .files => try argv.appendSlice(w.gpa, &.{ "rg", "--files", "--sort", "path", "--no-messages" }), + } + // As selection_pipe's children: this thread's mask is the child's. + const none = std.posix.sigemptyset(); + var kept: std.posix.sigset_t = undefined; + std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, &kept); + var child = std.process.spawn(w.io, .{ + .argv = argv.items, + .cwd = if (w.job.base.len == 0) .inherit else .{ .path = w.job.base }, + .stdin = .ignore, + .stdout = .pipe, + .stderr = .ignore, + }) catch |err| { + std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); + return if (err == error.Canceled) error.Canceled else error.NoRipgrep; + }; + std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); + w.engine = .rg; + // Canceled, capped on the loop, failed: it is killed and reaped. + defer if (child.id != null) child.kill(w.io); + var line: std.ArrayList(u8) = .empty; + defer line.deinit(w.gpa); + var json_arena: std.heap.ArenaAllocator = .init(w.gpa); + defer json_arena.deinit(); + var file_hits: u32 = 0; + var file_path: std.ArrayList(u8) = .empty; + defer file_path.deinit(w.gpa); + // Cut at the cap (on the loop), rg is left to the kill. + var cut = false; + var chunk: [64 * 1024]u8 = undefined; + read: while (true) { + const n = child.stdout.?.readStreaming(w.io, &.{&chunk}) catch |err| switch (err) { + error.EndOfStream => break, + error.Canceled => return error.Canceled, + else => return error.ReadFailed, + }; + if (n == 0) break; + var at: usize = 0; + while (std.mem.indexOfScalarPos(u8, chunk[0..n], at, '\n')) |nl| { + try line.appendSlice(w.gpa, chunk[at..nl]); + at = nl + 1; + defer line.clearRetainingCapacity(); + if (w.job.kind == .files) { + // a dot-file is passed over, as the walk passes over + // dot-directories + if (std.mem.startsWith(u8, std.fs.path.basename(line.items), ".")) continue; + w.scanned += 1; + if (try w.file(w.shown(line.items))) { + cut = true; + break :read; + } + continue; + } + _ = json_arena.reset(.retain_capacity); + const value = std.json.parseFromSliceLeaky(std.json.Value, json_arena.allocator(), line.items, .{}) catch continue; + const obj = if (value == .object) value.object else continue; + const kind = (obj.get("type") orelse continue); + if (kind != .string) continue; + const data = if (obj.get("data")) |d| (if (d == .object) d.object else continue) else continue; + if (std.mem.eql(u8, kind.string, "begin")) { + file_hits = 0; + file_path.clearRetainingCapacity(); + const text = jsonText(data.get("path")) orelse continue; + try file_path.appendSlice(w.gpa, w.shown(text)); + } else if (std.mem.eql(u8, kind.string, "match")) { + if (file_path.items.len == 0 or w.total >= w.job.cap.load(.acquire)) continue; + const text = jsonText(data.get("lines")) orelse continue; + const number = data.get("line_number") orelse continue; + if (number != .integer) continue; + var from: usize = 0; + var end: usize = w.job.pattern.len; + if (data.get("submatches")) |subs| if (subs == .array and subs.array.items.len > 0 and subs.array.items[0] == .object) { + const first = subs.array.items[0].object; + if (first.get("start")) |v| if (v == .integer) { + from = @intCast(v.integer); + }; + if (first.get("end")) |v| if (v == .integer) { + end = @intCast(v.integer); + }; + }; + try w.row(file_path.items, @intCast(number.integer), from, end, text); + file_hits += 1; + } else if (std.mem.eql(u8, kind.string, "end")) { + if (file_hits == 0) continue; + w.files += 1; + file_hits = 0; + try w.maybeSend(); + // At the cap rg is left blocked on its full pipe: its + // own backpressure, until More or a cancel. + if (try w.checkCap()) { + cut = true; + break :read; + } + } else if (std.mem.eql(u8, kind.string, "summary")) { + if (data.get("stats")) |stats| if (stats == .object) if (stats.object.get("searches")) |v| if (v == .integer) { + w.scanned = @intCast(v.integer); + }; + } + } + try line.appendSlice(w.gpa, chunk[at..n]); + } + if (!cut and child.id != null) { + _ = child.wait(w.io) catch |err| if (err == error.Canceled) return error.Canceled; + child.id = null; + } + } +}; + +/// rg's `{"text": …}` (a name or line that is not UTF-8 comes as bytes, +/// and is passed over). +fn jsonText(v: ?std.json.Value) ?[]const u8 { + const o = v orelse return null; + if (o != .object) return null; + const t = o.object.get("text") orelse return null; + return if (t == .string) t.string else null; +} + +fn work(io: std.Io, job: *Job, ctx: ?*anyopaque, sink: Sink) void { + var exact = false; + for (job.pattern) |c| exact = exact or std.ascii.isUpper(c); + var w: Worker = .{ .io = io, .gpa = job.gpa, .job = job, .ctx = ctx, .sink = sink, .exact = exact, .began = std.Io.Clock.awake.now(io) }; + defer w.deinit(); + const forced: ?Engine = job.engine orelse if (std.c.getenv("PARDES_STREAM_ENGINE")) |v| + std.meta.stringToEnum(Engine, std.mem.span(v)) + else + null; + const ran = if ((forced orelse .rg) == .rg) w.ripgrep() else error.NoRipgrep; + ran catch |err| switch (err) { + error.Canceled, error.Refused => return, + error.NoRipgrep => { + w.engine = .walk; + w.walk() catch |walk_err| switch (walk_err) { + error.Canceled, error.Refused => return, + else => { + w.send(.failed, false) catch {}; + return; + }, + }; + }, + else => { + w.send(.failed, false) catch {}; + return; + }, + }; + w.send(.done, false) catch {}; +} + +// ---- tests ---- + +const host_io = @import("host_io.zig"); +const testing = std.testing; + +/// The shell's half, in a test: perform the `search` effect on a real +/// worker, hand what it posts to the core. +const TestShell = struct { + q: host_io.Inbox, + + fn init() TestShell { + return .{ .q = .{ .gpa = testing.allocator, .lsp_allocator = testing.allocator, .io = testing.io } }; + } + + const vtable: pardes.Host.VTable = .{ .search = struct { + fn f(_: ?*anyopaque, _: u32) void {} + }.f }; + + fn attach(p: *Pardes) void { + p.host = .{ .vtable = &vtable }; + } + + fn pump(t: *TestShell, p: *Pardes) void { + while (p.nextEffect()) |e| switch (e) { + .search => |s| start(testing.io, testing.allocator, p, s.gen, &t.q, host_io.Inbox.pushSearch), + else => {}, + }; + var batch: host_io.Inbox.Batch = .{}; + t.q.takeInto(&batch); + for (batch.slice()) |m| switch (m) { + .search => |b| { + p.update(.{ .search = b }); + b.deinit(testing.allocator); + }, + else => m.deinit(testing.allocator, testing.allocator), + }; + } + + /// Pump until the search is over (or `limit_ms` passes: a failure). + fn finish(t: *TestShell, p: *Pardes, limit_ms: i64) !void { + const until = std.Io.Clock.awake.now(testing.io).toMilliseconds() + limit_ms; + while (p.stream.state == .searching or p.stream.state == .waiting) { + if (std.Io.Clock.awake.now(testing.io).toMilliseconds() > until) return error.Timeout; + if (p.stream.state == .waiting) p.update(.tick); + t.pump(p); + testing.io.sleep(.fromMicroseconds(200), .awake) catch {}; + } + } +}; + +/// A worker that never heard of the cancel: it pushes rows of a stale +/// generation for as long as the live one streams. +const Rogue = struct { + q: *host_io.Inbox, + gen: u32, + stop: std.atomic.Value(bool) = .init(false), + done: std.atomic.Value(bool) = .init(false), + pushed: usize = 0, + + fn run(r: *Rogue) void { + defer r.done.store(true, .release); + while (!r.stop.load(.acquire) and r.pushed < 200) { + const rows = testing.allocator.dupe(u8, "d00/f000.txt:1:3-8 stale stale\n") catch return; + if (!host_io.Inbox.pushSearch(r.q, .{ .gen = r.gen, .rows = rows, .hits = 1, .files = 1 })) return; + r.pushed += 1; + std.Thread.yield() catch {}; + } + } +}; + +test "Stream: a stale generation's rows never land in the query pane, however two generations race (walk and rg)" { + if (comptime !filesystem.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var root_buf: [4096]u8 = undefined; + const files = 120; + var name_buf: [64]u8 = undefined; + for (0..files) |i| { + const name = try std.fmt.bufPrint(&name_buf, "d{d:0>2}/f{d:0>3}.txt", .{ i / 10, i }); + try tmp.dir.createDirPath(testing.io, std.fs.path.dirname(name).?); + try tmp.dir.writeFile(testing.io, .{ .sub_path = name, .data = "a needle line\nsome hay here\nneedle again\nhay hay\nmore hay\n" }); + } + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("x\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ root, "main.txt" }); + p.advance(1); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + shell.q.deinit(); + } + // The query pane the rows are for: a Grep's. + panes.Query.open(p, 0, .grep, "", false); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const qp = p.panes[qid].?; + const q = qp.query.?; + var dropped_total: usize = 0; + for ([_]Engine{ .walk, .rg }) |engine| { + p.stream.engine = engine; + for (0..12) |round| { + // A starts and runs a little (0, 1 or 2 pumps: its batches in + // flight, queued, or taken in), then B replaces it, typed (its + // pause run out on the clock) or at once. + const a = if (round % 2 == 0) "needle" else "hay"; + const b = if (round % 2 == 0) "hay" else "needle"; + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + query(p, qp.serial, .grep, a, root, .now); + p.update(.tick); + for (0..round % 3) |_| shell.pump(p); + var rogue: Rogue = .{ .q = &shell.q, .gen = p.stream.gen }; + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + if (round % 4 == 3) { + query(p, qp.serial, .grep, b, root, .typed); + try testing.expectEqual(State.waiting, p.stream.state); + p.advance(p.now_ns + debounce_ns + std.time.ns_per_ms); + } else query(p, qp.serial, .grep, b, root, .now); + try testing.expect(p.stream.gen != rogue.gen); + const thread = try std.Thread.spawn(.{}, Rogue.run, .{&rogue}); + const finished = shell.finish(p, 20_000); + // It may be waiting for room: the queue is taken until it ends. + rogue.stop.store(true, .release); + while (!rogue.done.load(.acquire)) shell.pump(p); + thread.join(); + shell.pump(p); // whatever it pushed last + try finished; + try testing.expectEqual(State.done, p.stream.state); + // b's lines, every one, and not one of a's nor the rogue's. + const per_file: usize = if (std.mem.eql(u8, b, "hay")) 3 else 2; + try testing.expectEqual(files * per_file, q.found.items.len); + try testing.expect(std.mem.indexOf(u8, q.found_bytes.items, "stale") == null); + for (q.found.items) |fd| { + const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + try testing.expect(std.ascii.findIgnoreCase(code, b) != null); + } + if (engine == .rg and p.stream.used != .rg) return; // no rg here: the walk was the test + dropped_total += p.stream.dropped; + p.stream.dropped = 0; + } + } + try testing.expect(dropped_total > 0); +} + +test "Stream: the listing of files for Find on a worker, a cap of hits stops the walk on the loop" { + if (comptime !filesystem.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var root_buf: [4096]u8 = undefined; + try tmp.dir.createDirPath(testing.io, "src"); + try tmp.dir.createDirPath(testing.io, ".git"); + for ([_][]const u8{ "src/a.zig", "src/b.zig", "notes.md", ".git/config" }) |name| + try tmp.dir.writeFile(testing.io, .{ .sub_path = name, .data = "needle\n" }); + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("x\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ root, "main.txt" }); + p.advance(1); + p.stream.engine = .walk; + // No host workers: the listing runs on the loop at the next tick. + panes.Query.open(p, 0, .find, "", false); + p.update(.tick); + p.update(.tick); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const q = p.panes[qid].?.query.?; + // the three files, not the dot-directory's + try testing.expectEqual(@as(usize, 3), q.names.cands.items.len); + try testing.expectEqual(State.done, p.stream.state); +} + +test "Stream: a big text's declarations are parsed on a worker, never the loop, and the rows of its / regroup under them" { + if (comptime !filesystem.platform_has_fs) return; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(testing.allocator); + for (0..4000) |i| try text.print(testing.allocator, "fn f{d}() void {{\n _ = needle;\n}}\n", .{i}); + const pane = try p.setTestFile(text.items); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/big.zig"); + p.advance(1); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + p.stream.cancelParse(); + shell.q.deinit(); + } + for ("/needle") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const qp = p.panes[qid].?; + // Not grouped yet: no parse on the loop; one asked of the worker. + try testing.expect(p.stream.parse != null); + try testing.expect(std.mem.indexOf(u8, qp.file.?.content, "fn f") == null); + const until = std.Io.Clock.awake.now(testing.io).toMilliseconds() + 60_000; + while (pane.file.?.context_revision == null or pane.file.?.context_revision.? != pane.file.?.revision) { + if (std.Io.Clock.awake.now(testing.io).toMilliseconds() > until) return error.Timeout; + shell.pump(p); + p.update(.tick); + testing.io.sleep(.fromMilliseconds(2), .awake) catch {}; + } + p.update(.tick); + // Now under their declarations: `fn fN() void {` headers. + try testing.expect(std.mem.indexOf(u8, qp.file.?.content, "fn f") != null); + try testing.expect(p.stream.parse == null); +} + +test "zz stream timings on the stress file with a worker (QUERY_TIMES=)" { + const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const bytes = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, testing.allocator, .limited(8 << 20)); + defer testing.allocator.free(bytes); + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + p.advance(1); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + p.stream.cancelParse(); + shell.q.deinit(); + } + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + pane.body.cur_row = 15000; + pane.ensureCursorVisible(); + _ = try p.render(frame.allocator()); + const t0 = now(); + for ("/pane") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + const typed = now() - t0; + var worst_wait: u64 = 0; + while (pane.file.?.context_revision == null or pane.file.?.context_revision.? != pane.file.?.revision) { + const t1 = now(); + shell.pump(p); + p.update(.tick); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + worst_wait = @max(worst_wait, now() - t1); + testing.io.sleep(.fromMilliseconds(2), .awake) catch {}; + } + var worst_key: u64 = 0; + for (".v") |c| { + const t2 = now(); + p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + worst_key = @max(worst_key, now() - t2); + for (0..12) |_| p.update(.tick); + } + std.debug.print("stream: '/pane' typed in {d} us; the worker's parse {d} ms; worst frame while it parsed {d} us; a keystroke with grouped rows {d} us\n", .{ typed / 1000, p.stream.parse_ns / std.time.ns_per_ms, worst_wait / 1000, worst_key / 1000 }); +} + +test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's tag goes on" { + if (comptime !filesystem.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var root_buf: [4096]u8 = undefined; + var name_buf: [64]u8 = undefined; + var text: std.ArrayList(u8) = .empty; + defer text.deinit(testing.allocator); + for (0..20) |_| try text.appendSlice(testing.allocator, "a needle here\n"); + for (0..150) |i| try tmp.dir.writeFile(testing.io, .{ .sub_path = try std.fmt.bufPrint(&name_buf, "f{d:0>3}.txt", .{i}), .data = text.items }); + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("x\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ root, "main.txt" }); + p.advance(1); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + shell.q.deinit(); + } + p.stream.engine = .walk; + panes.Query.open(p, 0, .grep, "needle", false); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const qp = p.panes[qid].?; + p.advance(p.now_ns + debounce_ns + std.time.ns_per_ms); + const until = std.Io.Clock.awake.now(testing.io).toMilliseconds() + 20_000; + while (p.stream.state != .capped) { + if (std.Io.Clock.awake.now(testing.io).toMilliseconds() > until) return error.Timeout; + p.update(.tick); + shell.pump(p); + testing.io.sleep(.fromMicroseconds(200), .awake) catch {}; + } + p.update(.tick); + try testing.expectEqual(@as(usize, soft_cap), qp.query.?.found.items.len); + try testing.expect(qp.query.?.capped); + try testing.expectEqualStrings(" More Del", @import("tagline.zig").curTail(qp)); + pardes.exec.runBuiltin(p, .More, qid, "", null); + try shell.finish(p, 20_000); + p.update(.tick); + try testing.expectEqual(State.done, p.stream.state); + try testing.expectEqual(@as(usize, 3000), qp.query.?.found.items.len); + try testing.expect(!qp.query.?.capped); +} diff --git a/src/builtins.zig b/src/builtins.zig index 7cdee9de..c8909e66 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1756,6 +1756,14 @@ pub const Search = struct { } }; +/// A query pane's Grep stopped at its 2000 lines goes on for 2000 more. +pub const More = struct { + pub const quiet = true; + pub fn run(c: Ctx) void { + if (!pardes.Stream.moreFor(c.p, c.id)) c.p.reportFailure(c.id, "More: no search is waiting at its cap"); + } +}; + /// Pick an open pane by its name in a query pane under this one (SPC b b). pub const Panes = struct { pub const takes_arg = true; diff --git a/src/config.zig b/src/config.zig index 2fa4a55d..25c9dc5a 100644 --- a/src/config.zig +++ b/src/config.zig @@ -119,6 +119,7 @@ pub const leader_path = paths: { .SearchRows = null, .Search = null, .Panes = null, + .More = null, .BootShell = null, .LookWord = null, .DirLook = null, diff --git a/src/detached/server.zig b/src/detached/server.zig index 124a4c5a..eefce93e 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -166,6 +166,8 @@ pub const Session = struct { s.inbox.lsp_task = null; } s.pipe_tasks.cancelAll(s.io); + // Its worker may be waiting on the inbox for room. + s.core.stream.cancelTask(); _ = s.drainCompletions(false); } @@ -197,6 +199,7 @@ pub const Session = struct { var buf: [256]u8 = undefined; s.core.setStatus(s.core.active, message.stamp(&buf, "lsp", status)); }, + .search => |b| s.core.update(.{ .search = b }), // Ptys are read in the loop's own poll, not through the inbox. .output, .eof, .files_changed, .fs_ready => {}, } @@ -350,8 +353,15 @@ pub const Session = struct { .detach = detach, .lsp = lspRequest, .pipe = pipeRequest, + .search = searchRequest, }; + fn searchRequest(ctx: ?*anyopaque, gen: u32) void { + const s = of(ctx); + if (s.wake[0] < 0) return pardes.Stream.runHere(s.core, gen); + pardes.Stream.start(s.io, s.worker_gpa, s.core, gen, &s.inbox, host_io.Inbox.pushSearch); + } + fn lspRequest(ctx: ?*anyopaque, request: host_io.Lsp.Request) void { const s = of(ctx); _ = s.drainCompletions(true); diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 2318d319..82614b4f 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -856,7 +856,7 @@ fn clientTag(msg: ClientMsg) ClientTag { return switch (msg) { .event => |ev| switch (ev) { // Machine-local reports and 9P requests belong to the session owner. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, inline else => |_, t| @field(ClientTag, @tagName(t)), }, inline else => |_, t| @field(ClientTag, @tagName(t)), @@ -986,7 +986,7 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { .pointer_leave => {}, .focus => |focused| try w.writeByte(@intFromBool(focused)), // See `clientTag`: no tag, so nothing to encode. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, }, } try finishMessage(&w, at); @@ -1137,7 +1137,7 @@ pub fn clientBound(msg: ClientMsg) usize { .paste => |b| b.len, .command => |line| line.len, // See `clientTag`: not on this wire in this direction. - .output, .eof, .exited, .lsp_resp, .pipe_resp, .file_changed, .tick => unreachable, + .output, .eof, .exited, .lsp_resp, .pipe_resp, .search, .file_changed, .tick => unreachable, }, }; } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 5017ab53..49a98f5b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2202,6 +2202,8 @@ fn localSession( }; defer { if (queue.lsp_task) |*task| task.future.cancel(io); + // Its worker may be waiting on the queue for room. + core.stream.cancelTask(); queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -2573,6 +2575,8 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { }; defer { if (queue.lsp_task) |*task| task.future.cancel(io); + // Its worker may be waiting on the queue for room. + core.stream.cancelTask(); queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -3815,6 +3819,7 @@ const Shell = struct { .open_link = openLink, .lsp = lsp, .pipe = pipe, + .search = search, }; const grid_vtable: pardes.Host.VTable = vt: { @@ -3908,6 +3913,11 @@ const Shell = struct { s.saw_event = true; s.pipe_tasks.finish(s.io, response_value.id); }, + .search => |b| { + s.core.update(.{ .search = b }); + b.deinit(s.gpa); + s.saw_event = true; + }, .files_changed => check_files = true, .fs_ready => {}, }; @@ -4473,6 +4483,12 @@ fn pipe(ctx: ?*anyopaque, id: u32) void { s.core.reportError(s.core.active, "pipe", error.WorkersUnavailable); } +fn search(ctx: ?*anyopaque, gen: u32) void { + const s = shellOf(ctx); + if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.queue, Queue.pushSearch); + pardes.Stream.runHere(s.core, gen); +} + fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { for (ptys, 0..) |slot, id| if (slot) |pt| { if (pt.fd < 0) continue; diff --git a/src/host_io.zig b/src/host_io.zig index b32fff55..f5d6f375 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -48,6 +48,9 @@ pub const Host = struct { open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null, lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, + /// Start the streaming search of this generation on a worker + /// (pardes.Stream.start); absent, it runs on the loop. + search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null, }; }; @@ -129,6 +132,9 @@ pub const Inbox = struct { lsp: struct { id: u32, rows: ?[]u8 }, lsp_status: []u8, pipe: selection_pipe.Response, + /// A streaming search's rows (pardes.Stream), of whatever generation: + /// the core drops a stale one. + search: pardes.Stream.Batch, files_changed, fs_ready, @@ -141,6 +147,7 @@ pub const Inbox = struct { var response = response_value; response.deinit(gpa); }, + .search => |b| b.deinit(gpa), .eof, .files_changed, .fs_ready => {}, } } @@ -425,6 +432,34 @@ pub const Inbox = struct { q.push(.{ .pipe = response }); } + /// A streaming search's batch (pardes.Stream.start's sink). Never + /// dropped for want of room, as output is not: the worker waits for + /// room, a wait its cancel ends (false: it stops). + pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { + const q: *Inbox = @ptrCast(@alignCast(ctx.?)); + q.lock(); + while (!q.closed and q.len >= output_capacity) { + q.waiting += 1; + q.space.wait(q.io, &q.mutex) catch { + q.waiting -= 1; + q.unlock(); + batch.deinit(q.gpa); + return false; + }; + q.waiting -= 1; + } + if (q.closed) { + q.unlock(); + batch.deinit(q.gpa); + return false; + } + q.items[(q.head + q.len) % q.items.len] = .{ .search = batch }; + q.len += 1; + q.unlock(); + q.wake(); + return true; + } + /// A watched child exited (setExitWake): wake the loop, which takes it. pub fn wakeForExit(ctx: ?*anyopaque) void { const q: *Inbox = @ptrCast(@alignCast(ctx.?)); diff --git a/src/macos.zig b/src/macos.zig index 9378359c..7599a02d 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1101,6 +1101,8 @@ fn drainInbox(st: *State) bool { } }); st.pipe_tasks.finish(st.io, value.id); }, + // ponytail: no `search` host entry here, so Stream runs on the loop. + .search => |b| st.core.update(.{ .search = b }), // The SDL shell's: this one's file watches and 9P are its own. .files_changed, .fs_ready => {}, } diff --git a/src/pardes.zig b/src/pardes.zig index 1b4e9920..3ccfee5f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -25,6 +25,7 @@ pub const Messages = @import("Messages.zig"); pub const Registers = @import("Registers.zig"); pub const Macro = @import("Macro.zig"); pub const Pipe = @import("Pipe.zig"); +pub const Stream = @import("Stream.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; @@ -488,6 +489,7 @@ test { _ = @import("Places.zig"); _ = @import("Query.zig"); _ = @import("Names.zig"); + _ = @import("Stream.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -3669,6 +3671,8 @@ pub const Event = union(enum) { failure: ?selection_pipe.Failure = null, }, file_changed: struct { pane: u8, bytes: []const u8 }, + /// A disk search's batch (Stream.zig), borrowed for the step. + search: Stream.Batch, paste: []const u8, command: []const u8, /// Native shells may preserve sub-cell wheel distance in physical pixels. @@ -3725,6 +3729,9 @@ pub const Effect = union(enum) { /// Snapshot the matching request with pipeRequest(id), then run it away /// from the UI/event loop and answer with pipe_resp. pipe: struct { id: u32 }, + /// Start the disk search of this generation (Stream.start) on a worker + /// posting into the shell's inbox. + search: struct { gen: u32 }, /// Write what an Edit's `w` took (`Pipe.writes`), in order. edit_write, watch: struct { pane: u8, on: bool, mode: WatchMode = .reconcile }, @@ -4584,6 +4591,8 @@ pub const Pardes = struct { } = null, pipe: Pipe = .{}, + /// A query pane's Grep, and its Find's listing, on a worker (Stream.zig). + stream: Stream = .{}, fs: filesystem.Namespace = .{}, boot: Boot = .shell, @@ -4950,6 +4959,7 @@ pub const Pardes = struct { if (p.chord_arg) |a| gpa.free(a); for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); + p.stream.deinit(gpa); p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); @@ -5547,7 +5557,7 @@ pub const Pardes = struct { pub fn postEvent(p: *Pardes, ev: Event) void { switch (ev) { .key => |k| std.debug.assert(k.text.len == 0), - .output, .paste, .lsp_resp, .pipe_resp, .file_changed, .command => unreachable, + .output, .paste, .lsp_resp, .pipe_resp, .search, .file_changed, .command => unreachable, else => {}, } if (p.in_len == p.in_q.len) return; @@ -5846,6 +5856,8 @@ pub const Pardes = struct { f(p.host.ctx, q.id) else p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), + // No workers here (a test, a board): it runs on the loop. + .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen), .edit_write => { // Each write takes the bytes `w` took when it ran: the text // as it was before the Edit's changes. @@ -5995,7 +6007,8 @@ pub const Pardes = struct { pane.msg_announcement = false; }; switch (ev) { - .tick => {}, + // A batch of rows coming in is no gesture: a Look's hover stays. + .tick, .search => {}, .mouse => |m| if (!(m.button == .none and m.kind == .motion)) { p.raw_hover_intent = false; look.cancelLookHover(p); @@ -6026,6 +6039,7 @@ pub const Pardes = struct { p.clip_pending = null; }, .tick => { + Stream.step(p); Messages.advanceMessages(p); for (0..p.panes.len) |id| exec.flushReplEnter(p, id, false); }, @@ -6090,6 +6104,7 @@ pub const Pardes = struct { }, .lsp_resp => |r| p.lspResponse(r.id, r.rows), .pipe_resp => |r| Pipe.pipeResponse(p, r.id, r.success, r.outputs, r.failure), + .search => |b| Stream.receive(p, &b), .file_changed => |fc| _ = p.applyWatchedFileChanged(fc.pane, fc.bytes), .key => |key| { p.can_ask = true; @@ -7632,7 +7647,11 @@ pub const Pardes = struct { // Places still to find resume on the next frame. for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; if (panes.Query.busy(p)) return next; + // A typed Grep waiting out its pause. + const streaming = p.stream.wake(next); + if (streaming) |due| if (due <= next) return next; var frames: ?u64 = null; + if (streaming) |due| frames = @max(1, (due -| p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames orelse return next; frames = @max(1, delay -| waiting.frames); diff --git a/src/syntax.zig b/src/syntax.zig index 803d815a..81722ce5 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -572,7 +572,7 @@ pub fn analyzeSource(gpa: std.mem.Allocator, path: []const u8, content: []const defer tree.destroy(); var result: SourceAnalysis = .{}; errdefer result.deinit(gpa); - if (want_declarations) result.declarations = try declarationsFromTree(gpa, content, tree); + if (want_declarations) result.declarations = try declarationsFromTree(gpa, content, tree, null); if (want_colors) { result.colors = try gpa.alloc(u8, content.len); @memset(result.colors, 0); @@ -586,14 +586,55 @@ pub fn contextDeclarations(gpa: std.mem.Allocator, path: []const u8, content: [] return analysis.declarations; } -fn declarationsFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.Tree) ![]ContextDeclaration { +/// The declarations of `content` (its path's language), parsed with a +/// parser of its own, so a worker thread may ask: the loop's parsers +/// (`ensure`'s, one a language) are not touched, and a language is safe to +/// share. `stop`, set from another thread, ends the parse and the walk +/// early (error.Canceled): a 1.2 MB file is seconds in a Debug build. +pub fn declarationsApart(gpa: std.mem.Allocator, path: []const u8, content: []const u8, halt: *const std.atomic.Value(bool)) ![]ContextDeclaration { + if (comptime !enabled) return &.{}; + if (content.len == 0) return &.{}; + const ext = std.fs.path.extension(path); + const spec = specs: for (&specs) |*spec| { + for (spec.exts) |choice| if (std.ascii.eqlIgnoreCase(ext, choice)) break :specs spec; + } else return &.{}; + const parser = ts.Parser.create(); + defer parser.destroy(); + try parser.setLanguage(spec.language()); + const Reader = struct { + text: []const u8, + fn read(payload: ?*anyopaque, byte: u32, _: ts.Point, n: *u32) callconv(.c) [*c]const u8 { + const r: *@This() = @ptrCast(@alignCast(payload.?)); + const at = @min(byte, r.text.len); + n.* = @intCast(r.text.len - at); + return r.text.ptr + at; + } + fn progress(state: *ts.Parser.State) callconv(.c) bool { + const flag: *const std.atomic.Value(bool) = @ptrCast(@alignCast(state.payload.?)); + return flag.load(.monotonic); + } + }; + var reader: Reader = .{ .text = content }; + const tree = parser.parseWithOptions( + .{ .payload = &reader, .read = Reader.read, .encoding = .utf8 }, + null, + .{ .payload = @constCast(halt), .progress_callback = @ptrCast(&Reader.progress) }, + ) orelse return error.Canceled; + defer tree.destroy(); + return declarationsFromTree(gpa, content, tree, halt); +} + +fn declarationsFromTree(gpa: std.mem.Allocator, content: []const u8, tree: *ts.Tree, halt: ?*const std.atomic.Value(bool)) ![]ContextDeclaration { var result: std.ArrayList(ContextDeclaration) = .empty; errdefer result.deinit(gpa); // The cursor retains its ancestor stack: sibling visits do not repeatedly // reconstruct parents in broad syntax trees. Preorder preserves source order. var cursor = tree.rootNode().walk(); defer cursor.destroy(); + var visited: usize = 0; while (true) { + visited += 1; + if (halt) |flag| if (visited % 4096 == 0 and flag.load(.monotonic)) return error.Canceled; const node = cursor.node(); if (node.isNamed()) if (contextSpan(node, content)) |span| { if (result.items.len == 0 or result.items[result.items.len - 1].start_line != span.start_line or diff --git a/src/tagline.zig b/src/tagline.zig index 89152a3a..3c8dd3e1 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -39,6 +39,8 @@ pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; /// them into text a Save keeps; Unattach leaves it where it stands. pub const query_live_tail = " Del"; pub const query_frozen_tail = " Save Unattach Del"; +/// ...and while its Grep waits at 2000 lines for More (Stream.zig). +pub const query_capped_tail = " More Del"; /// A file with changes it has not saved. pub fn dirty(pane: *const panes.Pane) bool { const f = pane.file orelse return false; @@ -181,7 +183,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; - if (pane.query) |q| return if (q.frozen) query_frozen_tail else query_live_tail; + if (pane.query) |q| return if (q.frozen) query_frozen_tail else if (q.capped) query_capped_tail else query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 8f5f102a..572a6f2a 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -94,6 +94,8 @@ pub const Command = struct { lsp_done: struct { id: u32, rows: ?[]u8 }, lsp_status: []u8, pipe_done: selection_pipe.Response, + /// A streaming search's rows (pardes.Stream). + search_rows: pardes.Stream.Batch, files_changed, fs_ready, } = .nop; @@ -1354,6 +1356,8 @@ fn localSession( sh.lsp_task = null; } sh.pipe_tasks.cancelAll(io); + // Its worker may be waiting on the loop's queue for room. + core.stream.cancelTask(); file_watch.stop(sh.inotify_fd); if (sh.watch_task) |*t| { t.cancel(io) catch {}; @@ -1372,6 +1376,7 @@ fn localSession( var response = response_value; response.deinit(gpa); }, + .search_rows => |b| b.deinit(gpa), else => {}, }; } @@ -1557,6 +1562,7 @@ const Shell = struct { .open_link = openLink, .lsp = lsp, .pipe = pipe, + .search = search, }; fn clockNow(ctx: ?*anyopaque) u64 { @@ -1719,6 +1725,10 @@ const Shell = struct { response.deinit(s.gpa); s.pipe_tasks.finish(s.io, response_value.id); }, + .search_rows => |b| { + core.update(.{ .search = b }); + b.deinit(s.gpa); + }, } return false; } @@ -2027,6 +2037,22 @@ const Shell = struct { selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); } + fn search(ctx: ?*anyopaque, gen: u32) void { + const s = of(ctx); + if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); + pardes.Stream.runHere(s.core, gen); + } + + /// The loop's queue waits for room (a wait the worker's cancel ends). + fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { + const s = of(ctx); + s.loop.postEvent(.{ .search_rows = batch }) catch { + batch.deinit(s.gpa); + return false; + }; + return true; + } + fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { const s = of(ctx); var owned = response; @@ -2876,7 +2902,7 @@ const Attach = struct { fn apply(a: *Attach, event: @TypeOf(Command.value)) ?AttachEnd { switch (event) { - .nop, .wake, .fs_ready, .lsp_done, .lsp_status, .pipe_done, .pty_read, .pty_eof, .files_changed => {}, + .nop, .wake, .fs_ready, .lsp_done, .lsp_status, .pipe_done, .search_rows, .pty_read, .pty_eof, .files_changed => {}, .quit => return .none, .focus_in => return a.send(.{ .focus = true }), .focus_out => { -- cgit v1.3 From 1af098381515fbe3a4fe678cd023c7fd74418ae1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 12:43:02 -0300 Subject: Search converge 5/6: the old search pipeline phased out, the notice-band / for texts, Find/Grep prompts and walks on the loop, +Recent, n/N as Look-the-next-row; docs, tutor, Help and goldens to the query pane --- docs/helix-keys.md | 8 +- docs/typ/builtins-gui.json | 2 +- docs/typ/builtins-tty.json | 2 +- docs/typ/cheatsheet.typ | 6 +- docs/typ/guide.typ | 46 +++++- docs/typ/reference.typ | 28 ++-- src/Output.zig | 31 ++-- src/Query.zig | 176 +++++++++++++++------ src/builtins.zig | 41 ++--- src/config.zig | 7 +- src/fs.zig | 285 +---------------------------------- src/look.zig | 83 ++-------- src/ninep/ctl.zig | 50 +++--- src/normal.zig | 28 ++-- src/tagline.zig | 1 + src/tutor.txt | 16 +- test/output.zig | 9 ++ test/pdf.zig | 4 +- test/snapshots/builtins.snap | 23 +++ test/snapshots/dump.golden | 3 + test/snapshots/find.golden | 146 +++++++----------- test/snapshots/find.snap | 126 +++++----------- test/snapshots/fsearch.golden | 111 +++++++------- test/snapshots/fsearch.snap | 63 +++----- test/snapshots/grep.golden | 44 +++--- test/snapshots/grep.snap | 91 +++-------- test/snapshots/lookrange.golden | 47 +++--- test/snapshots/lookrange.snap | 22 ++- test/snapshots/lsp-client.golden | 23 +-- test/snapshots/lsp-client.snap | 11 +- test/snapshots/lspdebug.snap | 7 +- test/snapshots/lsprelpath.golden | 170 ++++++++++++--------- test/snapshots/lsprelpath.snap | 35 ++--- test/snapshots/msg.golden | 4 +- test/snapshots/msg.snap | 2 +- test/snapshots/stepgrain.golden | 123 ++++++++------- test/snapshots/stepgrain.snap | 59 ++------ test/snapshots/tagbottom.golden | 13 +- test/snapshots/tagbottomshort.golden | 38 ++--- test/snapshots/topbarexec.golden | 22 ++- 40 files changed, 858 insertions(+), 1148 deletions(-) (limited to 'src/Query.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 8155685f..fa06c9a6 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -134,14 +134,14 @@ language-backend queries, and the shell pipe. | `Space` (normal, body) | starts the pardes LEADER: a key path runs the same builtin words used by tags and the topbar. The main groups are `f` files, `h` docs, `c` columns, `t` toggles/effects, `a` panel animations, `s` session, `j` jumps, `l` language, and `w` directional focus; `SPC ?` lists every path and ` ?` lists one group in `+Help`. Neither `Exit` (quits the editor, acme's Exit) nor `Kill` (stops the commands pardes typed into terminals, acme's Kill) has a leader path: both are the topbar's and the root `ctl`'s. The pending path appears on the active pane's transient body/message row. Esc or an unmapped key abandons it. Paths, Help rows, and dispatch are all generated from the builtin registry at comptime; the leader applies only to a BODY in normal mode because tags and tty programs own their input | pardes-specific; helix spends Space on pickers/LSP (section C), while pardes uses acme-style executable words | | `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the same as `"+y`, `"+p`, `"+P`, `"+R`: register `+` (and `*`) IS the desktop's clipboard, the only register that reaches it. `SPC y` writes `+` alone, as helix's does, not the default register too. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. The clipboard holds one text, so N values go out joined by newlines, as helix sends them. On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | | a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tty shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | -| `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the pattern is typed on a line of its own on the pane's notice band, Enter fills the buffer, and its rows are ordinary look targets. Enter also goes to the first row using `Pardes.lookFirstHit`, so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | kept as-is; not in the corpus (helix `/` is regex search). Find and Grep answer with other files and deliberately do not jump. `LookNext` / `LookPrev` select subsequent result rows | pardes-specific | -| `n` / `N` | next / previous regex match in the current text, using the last search register; counts repeat and ends wrap | only the primary selection is replaced; in select mode each match is added and becomes primary. Named registers work. `*` sets the pattern from selections with word boundaries, `Alt-*` without. The former Look ring is `LookNext` / `LookPrev`, `SPC j n` / `SPC j p`. The change is bookmarked `pardes-nN-helix`; its predecessor is `pardes-nN-before-helix`. PDFs retain their location-result navigation | helix-verified | +| `/` (a text) | a query pane under the pane (`src/Query.zig`): a `+Search` whose line 1 is the query, typed into; helix's regex with smart case, every match tinted and ticked on the rail as you type (the pane's places, `src/Places.zig`), the first after the cursor selected (helix's incremental preview). `Ctrl-n`/`Ctrl-p` step while typing; Enter lands, fills `/` and keeps the rows as text; Esc while typing restores the text and closes the pane. Line 1's first word names the source (`/`, `Find`, `Grep`, `Recent`, `Panes`, `Symbols`, `All`, `Refs`, `Def`, `Impl`, `Diagnostics`), helix's pickers as one pane. A terminal's and a PDF's `/` keep the notice-band prompt and its `+Search` | helix's `/` semantics (regex, smart case, preview); the pane is pardes' | pardes-specific | +| `n` / `N` | next / previous match of the text's places when a query pane fed them (a `/`, a list's places in this text: refs, diagnostics, a Grep's hits), round the ends without a message; else the last search register's regex in the current text, as before; counts repeat | only the primary selection is replaced; in select mode each match is added and becomes primary. Named registers work. `*` sets the pattern from selections with word boundaries (`Alt-*` without) and seeds the text's query pane with it, the keyboard staying. The former Look ring is `LookNext` / `LookPrev`, `SPC j n` / `SPC j p`. PDFs retain their location-result navigation | helix-verified | | insert: printable text | file: real edit; terminal: typed run splice | | helix-verified (file) | | insert: `Enter` | newline; keeps the current full indent levels and adds one 4-space logical tab when the text before the cursor ends in `(`, `[`, `{`, or `)` (including `})`) | plain lines match `insert_newline`; delimiter heuristic is pardes-specific | helix-verified (plain) / pardes-specific (delimiter) | | insert: `Backspace` (+ `Shift-Backspace`) | delete prev char, joins lines at col 0; in a line's leading blanks, back to the previous 4-column indent stop (a whole unit when on one; a tab still goes alone) | matches `delete_char_backward` and its dedent; `Ctrl-h` alias in B | helix-verified | | insert: `Up` `Down` `Left` `Right` | move cursor | matches helix's "not recommended" insert arrows | helix-verified | -| `gd` `gD` `gy` `gi` `gr` | LSP definition / declaration / type-definition / implementation / references. One answer jumps straight there; several fill `+Search`, where `LookNext` / `LookPrev` walk and Enter opens | Ctrl+left-click is the mouse spelling of `gd`; language support depends on the configured backend | out of corpus | +| `gd` `gD` `gy` `gi` `gr` | LSP definition / declaration / type-definition / implementation / references. One answer jumps straight there; several (definition, implementation, references) fill the text's query pane, line 1 `Def`/`Impl`/`Refs`, their places in the text tinted and stepped by `n`/`N`; the others fill `+Search`, where `LookNext` / `LookPrev` walk and Enter opens | Ctrl+left-click is the mouse spelling of `gd`; language support depends on the configured backend | out of corpus | | `]d` `[d` / `]D` `[D` | step the diagnostics list / go to its last or first; if no list is up, asking the backend for one is part of the press | | out of corpus | | `=` | `format_selections` — writes a `- old` / `+ new` diff into `+Lsp` | deliberate divergence: the seam returns ROWS, not edits, so this SHOWS the formatting instead of applying it. Not in the corpus, so there is no waiver to name — the query leaves the core as an effect the headless harness has no shell to perform | out of corpus | | `Ctrl-o` / `Ctrl-i` | jumplist back / forward (also Mouse4 / Mouse5 in SDL, macOS and web); successful navigation clears selections in both panes and places the cursor at the saved location; raw tty forwards both to the child — the `Back` / `Forward` builtins, also on `SPC j o` / `SPC j i`, with `SPC j l` rendering the stack as a buffer; a closed file's entry stays, marked `(closed)`, and a jump to it opens the file again at its place | helix binds both keys (`jump_backward` / `jump_forward`) but to a POSITION jumplist; pardes' stack is over panes and focus, so the keys agree and the semantics do not. `Ctrl-i` and Tab are the same byte under the legacy encoding; there Tab keeps meaning execute, and the pair only separates where the host speaks the kitty keyboard protocol | pardes-specific | @@ -353,7 +353,7 @@ text. | Key(s) | Helix behavior | Reason | | --- | --- | --- | -| `?` | reverse search prompt | pardes keeps its own `/` plain substring search into an output buffer. `*`, `Alt-*` and search-repeat `n`/`N` are implemented and verified above | +| `?` | reverse search prompt | pardes' `/` is a query pane (above); `N` steps backward. `*`, `Alt-*` and search-repeat `n`/`N` are implemented and verified above | | `Space` mode: `f F e . b j g G ' w c C Alt-c / ?` | pickers, global search, palette | pickers and the command palette do not exist here — but the KEY is taken: pardes' own leader runs the acme builtins (section A). Two halves of helix's space mode DO exist and are in section A: the clipboard menu (`y Y p P R`, helix's letters on helix's leader) and the LSP menu, moved one prefix deeper to `SPC l k/r/a/h/s/S/d/D` because `d`, `k`, `s` and `h` were already pardes' most-pressed keys | | Popup `Ctrl-u`/`Ctrl-d`, Completion menu, Signature help tables | LSP popups | LSP | | Picker table (all rows), Prompt table (all rows) | picker / prompt internals | pickers — pardes' tag line is its own one-line editor | diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index c238955c..88c9d864 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -51,7 +51,7 @@ {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, {"name": "Get", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Get: the pane's file read again, its unsaved edits refused once as Del refuses them."}, {"name": "Grain", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off, 0-3", "doc": "The page takes a fine, still grain, like paper: a level, 0 (off) through 3."}, - {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches file CONTENTS under every pane's directory at once."}, + {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches the LINES of those files, on the disk engine's worker."}, {"name": "GripWidth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The grip and scrollbar width, as a percent of the theme's rail."}, {"name": "Help", "leader": "SPC ?", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the help: every key and every builtin."}, {"name": "Hover", "leader": "SPC l k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Ask the language server about the symbol under the cursor."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 791eef63..01ae6bc5 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -45,7 +45,7 @@ {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, {"name": "Get", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Get: the pane's file read again, its unsaved edits refused once as Del refuses them."}, - {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches file CONTENTS under every pane's directory at once."}, + {"name": "Grep", "leader": "SPC f g", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Find's sibling: Find matches file NAMES under this pane's directory, Grep matches the LINES of those files, on the disk engine's worker."}, {"name": "Help", "leader": "SPC ?", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the help: every key and every builtin."}, {"name": "Hover", "leader": "SPC l k", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Ask the language server about the symbol under the cursor."}, {"name": "InactiveDim", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off."}, diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index 7b140a04..76f4b866 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -59,7 +59,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla [#keys("i", "a", "I", "A", "o", "O")], [insert; #key("Esc") back to normal], [#keys("s", "S")], [regex: a cursor per match, split], [#keys("C", ",")], [cursor on next line; keep primary], - [#keys("/", "n", "N")], [search, next, previous], + [#keys("/", "n", "N")], [search (a query pane), next, previous], [#keys("m i", "m m")], [textobject, matching bracket], [#key("|")], [pipe each selection through the shell], [#keys("g d", "g r")], [definition, references (language server)], @@ -87,6 +87,8 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla key("SPC f f"), word("Find"), key("SPC f g"), word("Grep"), key("SPC f r"), word("Recent"), + key("SPC b b"), word("Panes"), + key("SPC s s"), [declarations], key("SPC f c"), word("Config"), key("SPC d"), word("Del"), key("SPC n t"), word("Tty"), @@ -119,7 +121,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla `git diff` output is a diff: #btn("B3") on a file line, an `@@` or a line's `+`/`-` jumps there. #doc("tags", section: "reviewing-diffs") == Finding things -- #word("Find") `name`, #word("Grep") `text` (literal): a `+Search` listing. #word("Recent"): files lately. #word("Help"), #word("Tutor"). +- A query pane under the pane: line 1 the query, its first word the source: `/pat`, `Find name` (fuzzy), `Grep text` (literal), `Recent`, `Panes`, `Symbols`, `All`. #keys("Ctrl-n", "Ctrl-p") step, #key("Enter") lands and keeps the rows, #key("Esc") puts things back. #word("Help"), #word("Tutor"). == Sessions `pardes --detach=work`; `--attach=work` or #word("Attach") `work`; #word("Detach") leaves it running. #doc("detached") diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index e60b4231..65c7334d 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -20,9 +20,9 @@ [the session's directory], [where pardes started, or the directory `pardes DIR` named; workspace and column tags run there], [active column], [where the next new pane goes (below)], [command pane], [a terminal that runs one command line and shows its output], - [`+` names], [panes pardes makes, named in their directory: `+New` a scratch (text with no file yet), `+Search` a listing of places, `+Pager` paged text, `+Errors` output, `+Unsaved` the panes holding unsaved text], + [`+` names], [panes pardes makes, named in their directory: `+New` a scratch (text with no file yet), `+Search` a query pane or a listing of places, `+Pager` paged text, `+Errors` output, `+Unsaved` the panes holding unsaved text], [serial], [a pane's number, never reused: the `3` in `@p3:12` and in 9P paths], - [message row], [the line where pardes says what happened, and asks: answer a prompt (a search, #word("Save")'s path) with #key("Enter"), cancel it with #key("Esc")], + [message row], [the line where pardes says what happened, and asks: answer a prompt (#key("s")'s regex, #word("Save")'s path) with #key("Enter"), cancel it with #key("Esc")], ) = Modes @@ -166,11 +166,45 @@ on the cheatsheet. A relative path is found in the directory of the pane the #word("Look") came from, then of each pane on the jump list, most recent first. += Search + +#key("/") opens a query pane under the pane: a `+Search` whose first line +is the query, typed into, and whose rows are what it finds, made again at +each key. It takes its rows from the pane it searches and from no other, +is born #word("SearchRows") rows tall and never resizes itself; nothing +found is a count of `0` in its tag, not an exit. + #pairs( - [#key("/") `TODO` #key("Enter")], [a `+Search` of the lines holding `TODO`, the cursor on the first; #keys("n", "N") select the next or previous match], - [#word("Find") `conf`], [a `+Search` of the files below the pane's directory with `conf` in their names], - [#word("Grep") `TODO`], [a `+Search` of the lines holding `TODO`, literally, under every pane's directory], + [#key("/") `vw`], [every match in the text tinted and ticked on its scroll rail, the first after the cursor selected; the rows under line 1 are the lines holding it, a line number in the gutter, each under the declaration it is in], + [#keys("Ctrl-n", "Ctrl-p")], [the next or previous match, typing; the text follows it], + [#key("Enter")], [the keyboard on the match, the pattern in `/`, the rows kept as text (#word("Save") keeps them as a file)], + [#keys("n", "N")], [the next or previous match in the text, round the end without a word], + [#key("Esc")], [typing: the text as it was, the query pane closed], + [#key("*")], [the selection as line 1, the keyboard staying in the text], ) + +Line 1's first word names what it searches, and editing the word changes it: + +#pairs( + [`/pat`], [the pane's own text: a regex, any case unless it has a capital (#key("/"))], + [`Find name`], [the files below the pane's directory, by a fuzzy match of their names (#key("SPC f f"), #word("Find"))], + [`Grep text`], [the lines of those files holding `text`, literally (#key("SPC f g"), #word("Grep")); past 2000 lines #word("More") goes on], + [`Recent name`], [the files opened lately (#key("SPC f r"), #word("Recent"))], + [`Panes name`], [the open panes (#key("SPC b b"), #word("Panes"))], + [`Symbols name`], [the text's declarations (#key("SPC s s"))], + [`All pat`], [every open pane's text, its rows under each pane (#key("SPC /"))], + [`Refs`, `Def`, `Impl`, `Diagnostics`], [the language server's lists; their places in the text tinted as a `/`'s are, `]d` stepping the diagnostics], +) + +A row in a file no pane shows is shown in a `+Preview` under the query +pane, following #keys("Ctrl-n", "Ctrl-p") and #btn("B1"), never the +pointer; #key("Enter") makes the preview that file's pane where it stands. +#btn("B3") on a row's line number looks at the row; #btn("B2") on line 1 +runs it again. The next search from the same pane reuses its query pane, +its kept rows back on #key("Esc") (#word("SearchPane") `new`: a pane each; +#word("SearchPlace") `column`: in a finder column at the right). A PDF's +and a terminal's #key("/") still ask on the message row and list a +`+Search`. #clip("search") = Unsaved panes @@ -281,7 +315,7 @@ refusals and `--nested` are in the reference. [#key("w") #key("d")], [select a word, delete it: motions select, edits act on the selection], [#key("x"), #key("v"), #key(";")], [select the line; extend; collapse to the cursor], [#key("s")], [a cursor per regex match; every edit acts at each], - [#key("/"), #keys("n", "N")], [substring search; repeat the search in the current text, wrapping at the ends], + [#key("/"), #keys("n", "N")], [search the text in a query pane (#link()[Search]); step its matches, round the ends], [#keys("SPC j n", "SPC j p")], [#word("LookNext") / #word("LookPrev"): select locations across panes; #key("Enter") opens one], [#key("g l")], [line end], [`12G`], [line 12; a bare #key("G") does nothing], diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index c14ad659..386b9f0f 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -909,7 +909,8 @@ at 200, ending in `…`. Control characters become spaces. pane from the root). - #file("/recent"): up to 200 files, PDFs and images, most recent first, `open ` or `closed `; kept in `$XDG_STATE_HOME/pardes/recent`. - #word("Recent") shows them in a pane, an open one at its dot now and a + #word("Recent") lists them in a query pane (line 1 `Recent`, the rest + narrowing them by a fuzzy match), an open one at its dot now and a closed one at its last (a PDF's is its page); a #word("Look") of a row reopens it there. - #file("/status"): `pid`, `version`, `panes`. @@ -972,15 +973,22 @@ one a #file("exec") open still holds is never reused. In a command pane, #key("n = Find and Grep -#word("Find") matches file names, #word("Grep") the text of lines, both literally and -ignoring ASCII case. #word("Grep") reads whole files and stops at 512 -hits, #word("Find") at 512 names. The walk stops at 20000 files or 100000 entries, -16 deep, and passes over `.git`, `.jj`, `target`, `node_modules`, -`.venv`, `__pycache__`, `.zig-cache` and `zig-out`. A cap hit, or a -directory it could not open, is said at the end: `cut at 512 hits`, `walk cut at N entries`, `N -directories skipped: permission denied`. A search that finds nothing and -skipped nothing fails, `Grep: text not found`, and leaves the `+Search` as -it was. +Both fill the asking pane's query pane (#doc("guide", section: "search")), +line 1 `Find name` or `Grep text`, and run on a worker thread, never on +the loop that draws: `rg` when it is on `PATH` (`rg --files` and `rg --json +--fixed-strings --smart-case`, so `.gitignore` is honoured and hidden files +are passed over), else pardes's own walk, sorted, 16 deep, passing over +dot-directories, `.git`, `.jj`, `target`, `node_modules`, `.venv`, +`__pycache__`, `.zig-cache` and `zig-out`. #word("Find") lists the files once +and matches their names fuzzily at each key (the best first, 200 shown); +#word("Grep") matches the text of lines literally, any case unless the text +has a capital, once the typing pauses (80 ms), and stops at 2000 lines: +#word("More") (in the query pane's tag) goes on for 2000 more. A directory the +walk could not open is said under the rows: `N directories skipped: +permission denied`. A new query cancels the last; rows of a query no +longer asked never land. Written to #file("exec") (a script) the search runs +to its end before the write is answered, and one that finds nothing fails, +`Grep: text not found`, `Find: name not found`, its query pane's count `0`. = On screen diff --git a/src/Output.zig b/src/Output.zig index 1e62b04a..01e3e0f1 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -857,15 +857,6 @@ pub fn dropUnsaved(p: *Pardes, gone: *const Pane) void { } } -/// Recent: the one +Recent, filled again when it is there (as Find and -/// Grep's +Search is), else opened below the asking pane. -pub fn openRecent(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try recentText(p, &out.writer, true); - try refillOrOpen(p, id, .{ .cmd = .Recent }, try out.toOwnedSlice()); -} - /// The one stepped output from `from`, filled again with `content` when it /// is there (Recent, Jumplist), or opened when it is not. fn refillOrOpen(p: *Pardes, id: usize, from: Origin, content: []u8) !void { @@ -971,6 +962,28 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { } if (show_calls_help) try w.writeAll(calls_help); if (prefix.len == 0) try w.writeAll(language_footer); + // The paths that run a builtin with a word (config.leader_args), and how + // a query pane is driven: under SPC f, b, s and in the whole listing. + const search_group = for (config.leader_args) |la| { + if (std.mem.startsWith(u8, la.path, prefix)) break true; + } else std.mem.eql(u8, prefix, "f"); + if (prefix.len == 0 or search_group) { + try w.writeAll("\nsearch: a query pane under the text,\nits line 1 the query, its first word\nthe source (/ Find Grep Recent Panes\nSymbols All Refs Def Impl Diagnostics)\n"); + for (config.leader_args) |la| { + if (!std.mem.startsWith(u8, la.path, prefix)) continue; + var keys: [16]u8 = @splat(' '); + for (la.path, 0..) |c, i| keys[2 * i] = c; + try w.print("{s} {s} {s}\n", .{ keys[0..8], @tagName(la.cmd), la.arg }); + } + if (prefix.len == 0) try w.writeAll( + "/ * the text (* seeds it)\n" ++ + "C-n C-p Up Down step, typing on line 1\n" ++ + "n N step the text's places\n" ++ + "Enter land there, keep the rows\n" ++ + "Esc put every view back\n" ++ + "More a Grep past 2000 lines\n", + ); + } return out.toOwnedSlice(); } diff --git a/src/Query.zig b/src/Query.zig index 48378a18..3a75a7f5 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -153,8 +153,10 @@ window: struct { lo: usize = 0, hi: usize = 0 } = .{}, /// made every third, the frame's time going to the finding. waited: u8 = 0, names: Names = .{}, -/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`). +/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`), and +/// the current one's index among them. found: std.ArrayList(Found) = .empty, +grep_at: usize = 0, found_bytes: std.ArrayList(u8) = .empty, grep_gen: u32 = 0, /// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave @@ -256,6 +258,10 @@ pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: boo File.setContent(p, f, new); q.reset(p); if (rp.collapsed) layout.toggleCollapse(p, id); + // A source that previews gets its +Preview now, at the key that + // asked, not under the typing later. + if (previews(source) and previewOf(p, id) == null) + _ = makePreview(p, id, @max(pardes.BOX_H, rp.tag_rows) + p.settings.search_rows, layout.groupRoot(p, id)); } else { if (existing) |old| { // SearchPane new: the last one stays where it is, a result of @@ -297,8 +303,20 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize const body: u16 = 1 + p.settings.search_rows; const tag = @max(pardes.BOX_H, np.tag_rows); const with_preview = previews(source); - // The preview, made right after, takes its own rows from the owner. - const want = tag + body; + // The preview, made right after, takes its own rows from the owner: + // when the owner has not the rows for both, they share what it has, so + // the group is whole from the first key and nothing moves later. + var want: u16 = tag + body; + var preview_rows: u16 = tag + p.settings.search_rows; + if (with_preview) { + layout.compute(p); + const spare = p.rects[owner_id].h -| layout.minRows(p, owner_id); + if (spare < want + preview_rows) { + const both = want + preview_rows; + want = @max(tag + 2, @as(u16, @intCast(@as(u32, spare) * want / both))); + preview_rows = spare -| want; + } + } if (p.settings.search_place == .column) { // The finder column (phase 6): until it exists, under the owner. if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); @@ -307,7 +325,7 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize // new pane is, the one place a search moves another pane. exec.placeNew(p, owner_id, owner_id, free, .doc); } - if (with_preview) _ = makePreview(p, free); + if (with_preview) _ = makePreview(p, free, preview_rows, owner_id); return free; } @@ -495,9 +513,14 @@ fn produce(p: *Pardes, id: usize, tick: bool) void { q.found.clearRetainingCapacity(); q.found_bytes.clearRetainingCapacity(); q.grep_gen +%= 1; + q.grep_at = 0; q.current = null; // On the disk engine's worker, once the typing pauses. - if (a.pat.len > 0) Stream.query(p, rp.serial, .grep, a.pat, dir, .typed) else if (p.stream.target == rp.serial) { + // A script's (a 9P write): run to its end before it answers. + if (a.pat.len > 0) { + Stream.query(p, rp.serial, .grep, a.pat, dir, if (p.fs.serving) .now else .typed); + if (p.fs.serving) Stream.step(p); + } else if (p.stream.target == rp.serial) { _ = p.stream.stop(); } feedGrepPlaces(p, q, rp.serial, a.pat); @@ -548,7 +571,10 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz switch (source) { // The files under the directory, listed once on the disk engine's // worker (rg --files, else the walk); each keystroke scores them. - .find => Stream.query(p, rp.serial, .files, "", dir, .now), + .find => { + Stream.query(p, rp.serial, .files, "", dir, .now); + if (p.fs.serving) Stream.step(p); + }, .recent => { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); @@ -828,7 +854,9 @@ fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { // Grouped once a parse of the text exists: asked of the worker now. if (ownerDecls(p, &owner.file.?, false) == null) Stream.parseFor(p, oid); const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); - const from = if (full) 0 else at -| live_rows / 2; + // While typed, a window of rows from just before the current place, so + // it sits under line 1. + const from = if (full) 0 else at -| 2; q.window = .{ .lo = from, .hi = from }; if (set.started and set.from == rp.serial) { if (from > 0) { @@ -856,7 +884,9 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void { const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; const set = &owner.places; q.total = if (set.from == rp.serial) set.hits.items.len else 0; - q.more = q.more or (set.from == rp.serial and !set.complete()); + // still counting: the places not all found yet (the rows' own cut is + // said in a row of theirs) + q.more = set.from == rp.serial and !set.complete(); q.k = if (set.current) |c| c + 1 else 0; if (set.from != rp.serial) q.k = 0; q.current = null; @@ -995,6 +1025,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { } } if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); setRows(p, rp, &out, &rows); const f = &rp.file.?; f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; @@ -1004,7 +1035,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { q.current = if (shown > 0) 0 else null; countCurrent(q); showCurrent(rp); - showTarget(p, id); + if (q.current == null) blankPreview(p, id) else showTarget(p, id); } /// A Grep keeps this many lines: the rest wait (the disk engine's `More`). @@ -1016,14 +1047,14 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { const rp = p.panes[id].?; const q = rp.query.?; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; - const at: usize = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].hit else 0) else 0; + const at: usize = @min(q.grep_at, q.found.items.len -| 1); q.items.clearRetainingCapacity(); var out: std.ArrayList(u8) = .empty; defer out.deinit(p.gpa); var rows: std.ArrayList(locations.Row) = .empty; var last_path: []const u8 = ""; var pathbuf: [4096 + 8]u8 = undefined; - const lo = if (full) 0 else at -| live_rows / 2; + const lo = if (full) 0 else at -| 2; const hi = if (full) q.found.items.len else @min(q.found.items.len, lo + live_rows); if (lo > 0) { var hb: [64]u8 = undefined; @@ -1048,12 +1079,23 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} lines after these", .{q.found.items.len - hi}) catch " ..."); } if (p.stream.target == rp.serial and p.stream.state == .capped) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: More in the tag goes on"); + try skippedRow(p, q, rp, &out, &rows); setRows(p, rp, &out, &rows); q.total = q.found.items.len; q.more = p.stream.busyFor(rp.serial); q.current = current orelse firstHit(q); countGrepCurrent(q); showCurrent(rp); + if (q.current == null) blankPreview(p, id); +} + +/// What the disk walk passed over, said under the rows: a search that +/// found nothing where it could not look says so, never just nothing. +fn skippedRow(p: *Pardes, q: *Query, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) !void { + const n = p.stream.skipped; + if (p.stream.target != rp.serial or n == 0) return; + var hb: [96]u8 = undefined; + try noteRow(p, q, out, rows, std.fmt.bufPrint(&hb, " {d} director{s} skipped: permission denied", .{ n, if (n == 1) "y" else "ies" }) catch " directories skipped"); } /// `k` for a Grep: the current row's line among all the lines sent. @@ -1128,7 +1170,9 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v const line = lineOne(rp.file.?.content); const a = parse(line) orelse return; makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); - toLineOne(p, qid); + // A list to pick from, typed into; diagnostics are a jump (]d): the + // keyboard stays on the place in the text. + if (source != .diagnostics) toLineOne(p, qid) else p.active = owner_id; } fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { @@ -1141,8 +1185,10 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { var rows: std.ArrayList(locations.Row) = .empty; const owner_id = p.paneBySerial(q.owner); const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; - var feed: std.ArrayList(Places.Hit) = .empty; - defer feed.deinit(p.gpa); + // Each open file's places in the list, its tints and n/N: the owner's + // and any other pane's the rows land in. + var feeds: [pardes.MAX_PANES]std.ArrayList(Places.Hit) = @splat(.empty); + defer for (&feeds) |*f| f.deinit(p.gpa); // In order: by path, then place, as a list of places reads. var sorted: std.ArrayList([]const u8) = .empty; defer sorted.deinit(p.gpa); @@ -1174,27 +1220,28 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { } const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); const col0 = t.at.col -| 1; - try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); - // The row's text: the line in the owner when it is the owner's, - // else as the server said it. + // The row's text: the line as an open pane has it, when one shows + // the file, else as the server said it. var code: []const u8 = rest; - var col = col0; - var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; - if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { - const owner_f = &p.panes[oid].?.file.?; - if (t.at.line <= File.nlines(p.gpa, owner_f)) { - const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); - const nx = File.lineStart(p.gpa, owner_f, t.at.line); - const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; - code = owner_f.content[ls..le]; - col = @min(col0, code.len); - end = @min(@max(end, col + 1), code.len); - feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; - } - } else { - col = 0; - end = 0; - }; + var col = @min(col0, rest.len); + var end = @min(if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1, rest.len); + var shown_in: u32 = 0; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + const tf = &tp.file.?; + if (tf.output != null or !std.mem.eql(u8, tf.path, path) or t.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, t.at.line - 1); + const nx = File.lineStart(p.gpa, tf, t.at.line); + const le = if (nx > ls and tf.content[nx - 1] == '\n') nx - 1 else nx; + code = tf.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feeds[i].append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + shown_in = tp.serial; + break; + } + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1, .serial = shown_in }); try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); n += 1; } @@ -1203,12 +1250,14 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { q.total = n; q.more = false; q.current = firstHit(q); + for (p.panes, 0..) |slot, i| if (slot) |tp| { + if (feeds[i].items.len > 0) tp.places.feed(p, tp, rp.serial, feeds[i].items, null) else if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; if (owner_id) |oid| { const owner = p.panes[oid].?; // Current: the first place after where it was asked (the answer // may come after the cursor moved), shown in the owner. const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); - owner.places.feed(p, owner, rp.serial, feed.items, null); const hits = owner.places.hits.items; var next: ?usize = null; for (hits, 0..) |h, i| if (h.start > asked_at) { @@ -1261,6 +1310,13 @@ fn showCurrent(rp: *Pane) void { }; const r: i32 = @intCast(c + 1); rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + // Typed into, line 1 stays in view whatever the current row: what you + // type is never scrolled away (the live rows start just before the + // current one, so it sits under line 1). Frozen, the row is scrolled to. + if (!q.frozen) { + if (rp.scroll() != 0) rp.scrollBy(-rp.scroll()); + return; + } const off = rp.scroll(); const shown = off + @as(i32, rp.rows) - 1; if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); @@ -1296,6 +1352,7 @@ fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { const q = rp.query.?; q.current = i; const it = q.items.items[i]; + if (q.source == .grep and it.kind == .hit) q.grep_at = it.hit; const rows = rp.file.?.location_rows; if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { const tp = p.panes[tid].?; @@ -1325,6 +1382,17 @@ pub fn step(p: *Pardes, id: usize, delta: i32) void { return; } }; + // A Grep: by its lines, the window made again when the next is past it. + if (q.source == .grep and q.found.items.len > 0) { + const n = q.found.items.len; + q.grep_at = if (delta > 0) (q.grep_at + 1) % n else (q.grep_at + n - 1) % n; + const in_window = for (q.items.items) |it| { + if (it.kind == .hit and it.hit == q.grep_at) break true; + } else false; + if (!in_window) makeGrepRows(p, id, q.frozen) catch {}; + for (q.items.items, 0..) |it, i| if (it.kind == .hit and it.hit == q.grep_at) return setCurrent(p, id, i, true); + return; + } const items = q.items.items; if (items.len == 0) return; var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); @@ -1335,6 +1403,26 @@ pub fn step(p: *Pardes, id: usize, delta: i32) void { setCurrent(p, id, i, true); } +/// Nothing current (a query that matches nothing): the +Preview shows +/// nothing, rather than a file the query no longer names. +fn blankPreview(p: *Pardes, qid: usize) void { + const pid = previewOf(p, qid) orelse return; + const pane = p.panes[pid].?; + const f = &pane.file.?; + if (f.content.len == 0) return; + const dir = std.fs.path.dirname(p.panes[qid].?.file.?.path) orelse "/"; + const path = std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ dir, config.preview_buffer }) catch return; + const empty = p.gpa.alloc(u8, 0) catch { + p.gpa.free(path); + return; + }; + p.gpa.free(f.path); + f.path = path; + File.setContent(p, f, empty); + f.saved_revision = f.revision; + f.scroll = 0; +} + /// Where the current row points, shown with the keyboard left where it is: /// a place in an open pane's text selected there (its places' current), /// in view; a file an open pane shows, its line there; any other file in @@ -1399,8 +1487,11 @@ pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { return null; } -/// A +Preview made under query pane `qid`, out of its rows alone. -fn makePreview(p: *Pardes, qid: usize) ?usize { +/// A +Preview made under query pane `qid`, `rows` tall, out of `giver`'s +/// rows: the text that asked, at the key that asked; the query pane itself +/// when its source word was edited to one that previews while typing (its +/// line 1 stays where it is). +fn makePreview(p: *Pardes, qid: usize, rows: u16, giver: usize) ?usize { const rp = p.panes[qid].?; const free = p.freeSlot() orelse return null; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; @@ -1410,10 +1501,7 @@ fn makePreview(p: *Pardes, qid: usize) ?usize { return null; }; layout.compute(p); - const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; - // Out of the group's root, the text that asked: the query pane keeps - // the rows it was typed into with (made later, for a reused pane). - if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + if (!layout.attachFrom(p, qid, free, rows, giver)) { p.removePane(free, qid) catch {}; return null; } @@ -1425,7 +1513,7 @@ fn makePreview(p: *Pardes, qid: usize) ?usize { /// file open in a pane would be shown there instead), the place centred /// and selected. Made when the pane has none and its owner has the rows. fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { - const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const id = previewOf(p, qid) orelse makePreview(p, qid, p.rects[qid].h / 2, qid) orelse return; const pane = p.panes[id].?; const f = &pane.file.?; if (!std.mem.eql(u8, f.path, path)) { @@ -1706,8 +1794,8 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { land(p, id, null); return true; } - const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); - const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + const down = hit(k, config.query_next); + const up = hit(k, config.query_prev); if (down or up) { step(p, id, if (down) 1 else -1); return true; diff --git a/src/builtins.zig b/src/builtins.zig index c8909e66..cda962de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1712,38 +1712,42 @@ const e_search_miss_grep = "Grep: text not found"; /// List the files below this pane's directory whose names hold its argument, in a +Search. pub const Find = struct { pub const takes_arg = true; + // A script's Find names what to find (bare, it is a key's prompt). pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true }; pub fn run(c: Ctx) void { + // A query pane under this pane, line 1 `Find ` and the word: bare + // (SPC f f) typed into; with a word (B2, a script) listed, the + // keyboard left where it was, a script told of a miss. const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) { - const rows = look.runSearch(c.p, c.id, pat, .find, .top, false) catch |err| return c.p.reportError(c.id, "Find", err); - if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); - return; - } - // Bare (SPC f f): the query pane, line 1 `Find `, typed into. - panes.Query.open(c.p, c.id, .find, "", true); + panes.Query.open(c.p, c.id, .find, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_find); } }; /// Find's sibling: Find matches file NAMES under this pane's directory, Grep -/// matches file CONTENTS under every pane's directory at once. +/// matches the LINES of those files, on the disk engine's worker. pub const Grep = struct { pub const takes_arg = true; pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) { - const rows = look.runSearch(c.p, c.id, pat, .grep, .top, false) catch |err| return c.p.reportError(c.id, "Grep", err); - if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); - return; - } - // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. - panes.Query.open(c.p, c.id, .grep, "", true); + panes.Query.open(c.p, c.id, .grep, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_grep); } }; +/// A script's Find or Grep (a 9P write runs it to its end before it +/// answers) that found nothing fails as one: the query pane stays, its +/// count 0, and the write hears `not found`. +fn missed(c: Ctx, text: []const u8) void { + if (!c.p.fs.serving) return; + const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return; + const q = c.p.panes[qid].?.query.?; + if (q.total == 0) c.p.reportFailure(c.id, text); +} + /// Search in a query pane under this pane, line 1 the argument (`Panes`, /// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. pub const Search = struct { @@ -1898,11 +1902,10 @@ pub const Last = struct { pub const Recent = struct { pub const scope: Scope = .session; pub const takes_arg = true; - pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - // From a pane: the query pane under it, line 1 `Recent `, typed - // into; from a header, which no pane owns, the +Recent list. - if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // The query pane under the pane the keyboard is in, line 1 + // `Recent `, typed into; what follows the word narrows the files. + if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Recent: open a pane to search from"); panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 25c9dc5a..fff99ad2 100644 --- a/src/config.zig +++ b/src/config.zig @@ -365,6 +365,11 @@ pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; pub const search_next: []const Chord = &.{.{ .cp = 'n' }}; pub const search_prev: []const Chord = &.{.{ .cp = 'N' }}; +/// Typing on a query pane's line 1 (Query.zig): the next and the previous +/// hit current, the text following (helix's prompt walks its history with +/// these; a query has none). Tab stays the exec chord. +pub const query_next: []const Chord = &.{ .{ .cp = 'n', .ctrl = true }, .{ .cp = Key.down } }; +pub const query_prev: []const Chord = &.{ .{ .cp = 'p', .ctrl = true }, .{ .cp = Key.up } }; pub const search_selection: []const Chord = &.{.{ .cp = '*', .alt = true }}; pub const search_selection_word: []const Chord = &.{.{ .cp = '*' }}; pub const pipe_selection: []const Chord = &.{.{ .cp = '|' }}; @@ -526,8 +531,6 @@ pub const comment_tokens: []const struct { exts: []const []const u8, token: []co }; pub const search_marker = " /"; -pub const find_marker = " Find /"; -pub const grep_marker = " Grep /"; pub const rename_marker = " Rename /"; pub const symbol_marker = " WsSymbols /"; pub const save_marker = " Save "; diff --git a/src/fs.zig b/src/fs.zig index cb813262..08379697 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1115,297 +1115,16 @@ pub const WalkNotes = struct { } }; const find_max_depth = 16; -const find_max_steps = 100_000; -/// One root's Find or Grep rows at most: its hits, each a path and a line. -pub const search_root_output_bytes = find_max_hits * (4096 + 320); pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; -/// A directory the walk may not open or read is passed over and counted in -/// `notes.skipped`, its siblings' hits kept: one locked directory is not -/// every search's failure. A cap the walk hit is noted too. -pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { - var hits: [find_max_hits][]const u8 = undefined; - var hits_len: usize = 0; - if (platform_has_fs) { - pardes.turn.yield(); - defer pardes.turn.back(); - const io = std.Io.Threaded.global_single_threaded.io(); - var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer root.close(io); - var w = try root.walkSelectively(arena); - defer w.deinit(); - var steps: usize = 0; - walk: while (steps < find_max_steps and hits_len < hits.len) { - steps += 1; // an unreadable dir burns a step too, so it cannot spin - const e = (w.next(io) catch { - notes.skipped += 1; - continue; - }) orelse break; - if (std.ascii.findIgnoreCase(e.basename, pat) != null) { - hits[hits_len] = try arena.dupe(u8, e.path); - hits_len += 1; - } - if (e.kind != .directory or e.depth() >= find_max_depth) continue; - for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.enter(io, e) catch { - notes.skipped += 1; - }; - } - if (hits_len >= hits.len) notes.hits_cut = true; - if (steps >= find_max_steps) notes.walk_cut = find_max_steps; - } else { - for (sources) |s| { - if (hits_len >= hits.len) break; - if (std.ascii.findIgnoreCase(std.fs.path.basename(s.path), pat) != null) { - hits[hits_len] = s.path; - hits_len += 1; - } - } - } - std.mem.sort([]const u8, hits[0..hits_len], {}, struct { - fn lt(_: void, a: []const u8, b: []const u8) bool { - return std.mem.lessThan(u8, a, b); - } - }.lt); - var written: usize = 0; - for (hits[0..hits_len]) |h| { - if (h.len + 1 > out.len - written) break; - @memcpy(out[written..][0..h.len], h); - written += h.len; - out[written] = '\n'; - written += 1; - } - return written; -} - -const grep_max_bytes = 256 * 1024; +// Find and Grep walk on the disk engine's worker now (Stream.zig); what is +// left here is what their notes and skips were. const grep_max_files = 20_000; -const GrepResult = struct { bytes: usize, hits: usize }; - -/// `text` starts at line `first_line` + 1 of its file. -fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize, first_line: usize) GrepResult { - var result: GrepResult = .{ .bytes = 0, .hits = 0 }; - var line: usize = first_line; - var it = std.mem.splitScalar(u8, text, '\n'); - while (it.next()) |raw| { - line += 1; - if (result.hits >= budget) break; - const at = std.ascii.findIgnoreCase(raw, pat) orelse continue; - const ln = std.mem.trimEnd(u8, raw, " \t\r"); - var cut = @min(ln.len, 200); - while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; - const row = std.fmt.bufPrint(out[result.bytes..], "{s}:{d}:{d}{c}{d} {s}\n", .{ - path, line, at + 1, config.range_sep, at + pat.len, ln[0..cut], - }) catch break; - result.bytes += row.len; - result.hits += 1; - } - return result; -} - -pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { - var hits: usize = 0; - var written: usize = 0; - if (!platform_has_fs) { - for (sources) |s| { - if (hits >= find_max_hits or written == out.len) break; - const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits, 0); - hits += result.hits; - written += result.bytes; - } - return written; - } - const root_path = std.mem.trimEnd(u8, dir, "/"); - const home = std.mem.trimEnd(u8, base, "/"); - const files = try arena.alloc([]const u8, grep_max_files); - var files_len: usize = 0; - // A walk and thousands of reads: the turn goes out for all of it. - pardes.turn.yield(); - defer pardes.turn.back(); - { - const io = std.Io.Threaded.global_single_threaded.io(); - var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer root.close(io); - var w = try root.walkSelectively(arena); - defer w.deinit(); - var steps: usize = 0; - walk: while (steps < find_max_steps and files_len < files.len) { - steps += 1; - const e = (w.next(io) catch { - notes.skipped += 1; - continue; - }) orelse break; - if (e.kind == .directory) { - if (e.depth() >= find_max_depth) continue; - for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.enter(io, e) catch { - notes.skipped += 1; - }; - continue; - } - if (e.kind != .file) continue; - files[files_len] = try std.fmt.allocPrint(arena, "{s}/{s}", .{ root_path, e.path }); - files_len += 1; - } - if (files_len >= files.len) notes.walk_cut = grep_max_files else if (steps >= find_max_steps) notes.walk_cut = find_max_steps; - } - std.mem.sort([]const u8, files[0..files_len], {}, struct { - fn lt(_: void, a: []const u8, b: []const u8) bool { - return std.mem.lessThan(u8, a, b); - } - }.lt); - const buf = try gpa.alloc(u8, grep_max_bytes); - defer gpa.free(buf); - for (files[0..files_len]) |path| { - if (hits >= find_max_hits or written == out.len) { - notes.hits_cut = true; - break; - } - var pathbuf: [4096]u8 = undefined; - const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; - const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); - if (fd < 0) continue; - defer _ = libc.close(fd); - // The whole file, a buffer at a time: each searched through its last - // whole line, the rest carried into the next. - const shown = lsp.rel(home, path); - var len: usize = 0; - var lines_before: usize = 0; - var first = true; - file: while (true) { - var eof = false; - while (len < buf.len) { - const n = libc.read(fd, buf[len..].ptr, buf.len - len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - break :file; - } - if (n == 0) { - eof = true; - break; - } - len += @intCast(n); - } - if (first and std.mem.indexOfScalar(u8, buf[0..@min(len, 1024)], 0) != null) break; - first = false; - // A line longer than the buffer is searched in buffer-sized parts. - const end = if (eof) len else if (std.mem.lastIndexOfScalar(u8, buf[0..len], '\n')) |nl| nl + 1 else len; - const result = grepText(shown, buf[0..end], pat, out[written..], find_max_hits - hits, lines_before); - hits += result.hits; - written += result.bytes; - if (eof or hits >= find_max_hits or written == out.len) break; - lines_before += std.mem.count(u8, buf[0..end], "\n"); - std.mem.copyForwards(u8, buf[0 .. len - end], buf[end..len]); - len -= end; - } - if (hits >= find_max_hits) notes.hits_cut = true; - } - return written; -} - -test "grep skips a file it cannot read instead of abandoning the search" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a-locked.txt", .data = "needle here\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b-open.txt", .data = "needle here\n" }); - var locked_buf: [std.fs.max_path_bytes]u8 = undefined; - const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/a-locked.txt", .{dir}, 0); - if (libc.chmod(locked, 0) != 0) return; - const probe = libc.open(locked, .{ .ACCMODE = .RDONLY }); - if (probe >= 0) { - _ = libc.close(probe); - _ = libc.chmod(locked, 0o644); - return error.SkipZigTest; - } - - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 64 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - _ = libc.chmod(locked, 0o644); // so `tmp.cleanup` can remove it - - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "b-open.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "a-locked.txt") == null); -} - -test "a directory the walk may not open is skipped and counted: Grep and Find keep every other hit" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - try tmp.dir.createDirPath(std.testing.io, "locked"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "locked/needle-in.txt", .data = "needle\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "needle-out.txt", .data = "needle\n" }); - var locked_buf: [std.fs.max_path_bytes]u8 = undefined; - const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/locked", .{dir}, 0); - if (libc.chmod(locked, 0) != 0) return; - defer _ = libc.chmod(locked, 0o755); // so `tmp.cleanup` can remove it - if (isDir(locked)) return error.SkipZigTest; // root reads it anyway - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 64 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt:1:") != null); - try std.testing.expectEqual(@as(usize, 1), notes.skipped); - notes = .{}; - n = try find(arena.allocator(), dir, "needle", out, ¬es); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt") != null); - try std.testing.expectEqual(@as(usize, 1), notes.skipped); -} - -test "Grep reads a long file to its end, and says when its hits were cut" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - // A match past the first buffer of a long file, on its own line number. - const long = try gpa.alloc(u8, grep_max_bytes + 64); - defer gpa.free(long); - @memset(long, 'x'); - for (0..long.len / 64) |i| long[i * 64] = '\n'; - @memcpy(long[long.len - 8 ..][0..7], "needle\n"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "long.txt", .data = long }); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 256 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - var want_buf: [64]u8 = undefined; - const want = try std.fmt.bufPrint(&want_buf, "long.txt:{d}:", .{std.mem.count(u8, long, "\n")}); - try std.testing.expect(std.mem.startsWith(u8, out[0..n], want)); - // More hits than the cap. - var many: std.ArrayList(u8) = .empty; - defer many.deinit(gpa); - for (0..find_max_hits + 10) |_| try many.appendSlice(gpa, "needle\n"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "many.txt", .data = many.items }); - notes = .{}; - n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expect(notes.hits_cut); - var said: [256]u8 = undefined; - const lines = said[0..notes.write(&said)]; - try std.testing.expectEqualStrings("cut at 512 hits\n", lines); - try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); -} - fn isDir(path: [*:0]const u8) bool { const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }); if (fd < 0) return false; diff --git a/src/look.zig b/src/look.zig index eed3dbd9..cd8df4fc 100644 --- a/src/look.zig +++ b/src/look.zig @@ -532,7 +532,6 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow }; } -const Search = enum { text, find, grep }; const SearchStart = enum { top, cursor }; @@ -550,20 +549,13 @@ pub fn submitSearch(p: *Pardes, id: usize) void { const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; if (std.mem.startsWith(u8, armed, config.rename_marker)) return p.lspRequest(id, .rename, armed[slash + 1 ..]); if (std.mem.startsWith(u8, armed, config.symbol_marker)) return p.lspRequest(id, .workspace_symbols, armed[slash + 1 ..]); - const kind: Search = if (std.mem.startsWith(u8, armed, config.find_marker)) - .find - else if (std.mem.startsWith(u8, armed, config.grep_marker)) - .grep - else - .text; - _ = runSearch(p, id, armed[slash + 1 ..], kind, .top, true) catch |err| return p.reportError(id, "search", err); - if (kind == .text) { - var pattern: std.ArrayList(u8) = .empty; - normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; - p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); - p.registers.last_search = '/'; - lookFirstHit(p, id); - } + // A PDF's `/` and a terminal's: a text's is its query pane (Query.zig). + _ = runSearch(p, id, armed[slash + 1 ..], .top, true) catch |err| return p.reportError(id, "search", err); + var pattern: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; + p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); + p.registers.last_search = '/'; + lookFirstHit(p, id); } fn lookFirstHit(p: *Pardes, id: usize) void { @@ -589,7 +581,7 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// of rows: past it, the rows stop and say where. pub const search_text_output_bytes = 16 << 20; -pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { +pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; // Blanks at either end are the pattern's (a look of an indented line); // a builtin's argument comes trimmed already. @@ -607,49 +599,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start var nrows: usize = 0; var anchor: ?usize = null; var notes: filesystem.WalkNotes = .{}; - if (kind == .grep) { - var roots: [MAX_PANES][]const u8 = undefined; - var nroots: usize = 0; - for (p.panes) |slot| { - const pp = slot orelse continue; - // A pane of the served tree (/virtual/, /n//) has no - // directory on this host to walk, and one that named `/` would - // swallow every other root: passed over. - const d = filesystem.localPath(Pardes.paneDir(pp)) orelse continue; - if (filesystem.isVirtual(if (pp.file) |f| f.path else d)) continue; - var covered = false; - var k: usize = 0; - while (k < nroots) { - if (pathUnder(d, roots[k])) { - covered = true; - break; - } - if (pathUnder(roots[k], d)) { // this one swallows a root already kept - nroots -= 1; - roots[k] = roots[nroots]; - continue; - } - k += 1; - } - if (covered) continue; - roots[nroots] = d; - nroots += 1; - } - out = try @import("memory.zig").unfilled(arena, @max(1, nroots) * filesystem.search_root_output_bytes); - // A pane's directory that is not there (a scratch named into one - // not made yet, a peer's) has nothing to grep: passed over, not the - // search's failure. - for (roots[0..nroots]) |r| - out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..], ¬es) catch |err| switch (err) { - error.FileNotFound, error.NotDir, error.AccessDenied => continue, - else => return err, - }; - nrows = std.mem.count(u8, out[0..out_len], "\n"); - } else if (kind == .find) { - out = try @import("memory.zig").unfilled(arena, filesystem.search_root_output_bytes); - out_len = try filesystem.find(arena, dir, pat, out, ¬es); - nrows = std.mem.count(u8, out[0..out_len], "\n"); - } else if (pane.hasPdf()) { + if (pane.hasPdf()) { out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); if (comptime pdf_enabled) { const found = try panes.Pdf.searchRows( @@ -700,19 +650,10 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const noted = notes.write(out[out_len..]); out_len += noted; nrows += std.mem.count(u8, out[out_len - noted .. out_len], "\n"); - // A Find or Grep that finds nothing leaves its directory's +Search as - // it was: the failure says why, and the last search's rows are still - // that search's (its tag names it). + // A word looked for that is nowhere opens nothing. if (!open_empty and nrows == 0) return 0; const content = try p.gpa.dupe(u8, out[0..out_len]); - // the buffer records WHICH search filled it, pattern and all: Find and - // Grep are builtins (words you can execute), the bare `/` is a key - const from: panes.Output.Origin = switch (kind) { - .text => .search, - .find => .{ .cmd = .Find }, - .grep => .{ .cmd = .Grep }, - }; - try panes.Output.fillResults(p, id, dir, from, pat, content, anchor); + try panes.Output.fillResults(p, id, dir, .search, pat, content, anchor); return nrows; } @@ -1466,7 +1407,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; - const rows = runSearch(p, id, text, .text, .cursor, false) catch |err| { + const rows = runSearch(p, id, text, .cursor, false) catch |err| { p.reportError(id, "search", err); return; }; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 45336a1e..635e03a6 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -3017,7 +3017,7 @@ test "a builtin that needs its argument, written bare to an exec, is EINVAL as t } } -test "Grep with no hit says grep: no match and opens nothing, a missing pane directory passed over" { +test "a script's Grep and Find fill the pane's one query pane, a row a line under its file; a miss says not found and opens nothing" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); var tmp = testing.tmpDir(.{}); @@ -3028,22 +3028,26 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&line, "{s}/a.txt\n", .{dir})); - // A hit opens its +Search, a row a line: exec reads it back. Find and - // Grep share it, a directory's one +Search, each run replacing it. + // A hit fills the pane's query pane, line 1 the command, its rows under + // the file they are in: exec reads it back. Find and Grep share it, the + // pane's one query pane, each run replacing it. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Grep bravo\n").reply.status); const grepped = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - try testing.expectEqual(@as(usize, 2), std.mem.count(u8, grepped.file.?.content, "other.txt:")); - try testing.expect(std.mem.indexOf(u8, grepped.file.?.content, "other.txt:2") != null); - try testing.expect(std.mem.indexOf(u8, grepped.file.?.content, "other.txt:3") != null); + const rows = grepped.file.?.content; + try testing.expect(std.mem.startsWith(u8, rows, "Grep bravo\n")); + try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "2 bravo here\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "3 three bravo\n") != null); + try testing.expectEqual(@as(usize, 2), grepped.query.?.total); try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); const found = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - try testing.expect(std.mem.indexOf(u8, found.file.?.content, "other.txt") != null); try testing.expectEqual(grepped.serial, found.serial); + try testing.expect(std.mem.indexOf(u8, found.file.?.content, "\nother.txt\n") != null); try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") == null); - // The same Find again reads back the +Search, not the pane it ran in. + // The same Find again reads back the query pane, not the pane it ran in. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes); - // A Grep run from the +Search itself fills that one, never a second. + // A Grep run from the query pane itself fills that one, never a second. try testing.expectEqual(Status.ok, wr(p, Node.of(found.serial, .exec), "Grep bravo\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes); var searches: usize = 0; @@ -3052,23 +3056,19 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir }; try testing.expectEqual(@as(usize, 1), searches); try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); - // A second pane in a directory that is not there. - const other = try th.newPane(p); - _ = wr(p, Node.of(other, .name), "/tmp/pardes-no-such-dir-zz/b.txt\n"); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); + // A miss: said to the script, the query pane's count 0, nothing opened. const missed = wr(p, Node.of(serialOf(p), .exec), "Grep zzqqnomatchzz\n"); try testing.expectEqual(E.NOENT, missed.errno()); try testing.expectEqualStrings("Grep: text not found", missed.reply.ename); + try testing.expectEqual(@as(usize, 0), found.query.?.total); const unfound = wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n"); try testing.expectEqual(E.NOENT, unfound.errno()); try testing.expectEqualStrings("Find: name not found", unfound.reply.ename); var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); - // The +Search a miss would have filled keeps the last search's rows: - // the miss is said, and its tag names what they are of. - try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); } test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { @@ -4911,7 +4911,7 @@ test "a Rename the server answered for this file alone, with other open files sa try testing.expect(th.logHas(p, "Rename: previewed, not applied: the server renamed in this file only, and 1 other open file(s) say the name")); } -test "Find ends with what it skipped, and a Find or Grep that finds nothing leaves the +Search as it was" { +test "Find says what it skipped under its names, and a script's Find that finds nothing is told so" { if (comptime !pardes.hosted) return; const gpa = testing.allocator; var tmp = testing.tmpDir(.{}); @@ -4928,18 +4928,18 @@ test "Find ends with what it skipped, and a Find or Grep that finds nothing leav const path = try std.fmt.bufPrint(&path_buf, "{s}/zz-needle.txt", .{dir}); const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); - try testing.expect(p.executeBuiltinLine(0, "Find needle")); - const search = p.panes[p.panes[0].?.search_pane.?].?; + // the walk's own skips are what is said (rg would pass over in silence) + p.stream.engine = .walk; + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find needle\n").reply.status); + const search = p.panes[pardes.panes.Query.ofOwner(p, p.panes[0].?.serial).?].?; const listed = search.file.?.content; try testing.expect(std.mem.endsWith(u8, listed, "1 directory skipped: permission denied\n")); - try testing.expect(std.mem.startsWith(u8, listed, "zz-needle.txt\n")); - // Nothing found where it looked, and nothing passed over: the miss is - // said, and the +Search keeps the last search's rows. + try testing.expect(std.mem.startsWith(u8, listed, "Find needle\nzz-needle.txt\n")); + // Nothing found: the miss is said, the query pane's count 0. _ = std.c.chmod(locked, 0o755); - const before = try gpa.dupe(u8, listed); - defer gpa.free(before); - try testing.expect(p.executeBuiltinLine(0, "Find nosuchname")); - try testing.expectEqualStrings(before, search.file.?.content); + const missed = wr(p, Node.of(serialOf(p), .exec), "Find nosuchname\n"); + try testing.expectEqual(E.NOENT, missed.errno()); + try testing.expectEqual(@as(usize, 0), search.query.?.total); try testing.expect(th.logHas(p, "Find: name not found")); } diff --git a/src/normal.zig b/src/normal.zig index ebace536..f5bdb9dc 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -757,22 +757,18 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .add_newline => |newline| return edit.addNewline(p, t, newline.direction == .forward, newline.count), .diagnostic => |diagnostic| { const fwd = diagnostic.direction == .forward; - if (!diagnostic.endpoint) { - if (panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics }) and - look.searchStep(p, p.active, if (fwd) 1 else -1)) return; - return p.lspRequest(p.active, .diagnostics, ""); - } - if (!panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics })) - return p.lspRequest(p.active, .diagnostics, ""); - if (!fwd) { - pane.search_row = null; - _ = look.searchStep(p, p.active, 1); - return; - } - const rp = p.panes[pane.search_pane orelse return] orelse return; - const rf = rp.file orelse return; - pane.search_row = std.mem.count(u8, rf.content, "\n"); - _ = look.searchStep(p, p.active, -1); + // Once a Diagnostics query fed them, the diagnostics are this + // text's places: ]d and [d step them as n and N do, ]D and [D + // go to the last and the first. Until then, asked for. + const set = &pane.places; + const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid| + (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false) + else + false; + if (!fed) return p.lspRequest(p.active, .diagnostics, ""); + if (!diagnostic.endpoint) return set.step(p, pane, fwd, 1, false); + if (set.hits.items.len == 0) return; + set.goTo(pane, if (fwd) set.hits.items.len - 1 else 0, false); }, .move => |move| switch (move.motion) { .left => { diff --git a/src/tagline.zig b/src/tagline.zig index 3c8dd3e1..c057772d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -184,6 +184,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; if (pane.query) |q| return if (q.frozen) query_frozen_tail else if (q.capped) query_capped_tail else query_live_tail; + if (pane.file) |file| if (file.output) |out| if (out.from == .preview) return query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; diff --git a/src/tutor.txt b/src/tutor.txt index 083a5028..188a485d 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -101,8 +101,10 @@ 1. `Look` :20 here: the cursor goes to line 20 of this pane. 2. Drag across :/^=.*UNSAVED/ with B3 held: `Look` takes exactly what you swept, a regex here, and goes to Part 7's heading. - 3. Press /, type keys, press Enter: a +Search lists the lines with - keys and the cursor goes to the first. n and N select search matches. + 3. Press / and type keys: a +Search opens under this pane, its first + line the query; each match lights up and is listed as you type, and + Ctrl-n steps. Enter puts the cursor on it and keeps the list; n and N + step them. Esc while typing puts everything back. -> Guide: Look @@ -259,9 +261,9 @@ typed ] p, [ p step by paragraph; ] d, [ d by diagnostic ] space a blank line below; [ space above | filter every selection through the shell - / case-insensitive SUBSTRING search, one hit a line; the - regex lives on s and S - n / N next/previous search match (Helix); v adds matches + / search in a query pane under the text: a regex, any + case unless it has a capital; line 1 is the query + n / N next/previous match, round the end; v adds matches SPC j n/p `LookNext`/`LookPrev`: select locations; Enter opens Ctrl-c comment or uncomment the lines @@ -344,11 +346,11 @@ typed ; collapses first bare G does nothing; ge is the START of the last line s / S regex cursors; m i/a textobjects; m s/r/d surround - / is a case-insensitive SUBSTRING search, not a regex + / opens a query pane: line 1 the query, Enter lands SPC is the leader (SPC ? is `Help`) vs HELIX selection is LINE-first (x), v for characters; / is a - substring search; n/N repeat it in the current text. + pane: Find, Grep, Recent are its line 1's first word. vs VIM no verb+noun: the motion already selected, so wd is what dw was; Esc goes back a pane; bare G does nothing. vs BOTH a terminal is just a pane, and the session can outlive diff --git a/test/output.zig b/test/output.zig index 8ba2f357..8eb389c8 100644 --- a/test/output.zig +++ b/test/output.zig @@ -219,6 +219,15 @@ test "references fill the asking text's query pane: sorted under their files, th try std.testing.expectEqual(@as(?usize, 2), source.places.current); try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); try std.testing.expectEqual(@as(usize, 6), results.query.?.total); + // Ctrl-n on line 1, Enter: the keyboard on that ref in the text + try std.testing.expectEqual(qid, p.active); + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(?usize, 3), source.places.current); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 4), source.body.cur_row); + p.update(.{ .key = .{ .cp = 'N' } }); + try std.testing.expectEqual(@as(?usize, 2), source.places.current); // n in the owner steps them, round the end without a word p.active = 0; p.update(.{ .key = .{ .cp = 'n' } }); diff --git a/test/pdf.zig b/test/pdf.zig index ea23f90a..d4efdfaf 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1053,7 +1053,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expect(pane.pdf.?.document_scroll_y > before_height_scroll); const revision_before_search = active_raster.revision; - _ = try pardes.look.runSearch(p, 0, "Pardes", .text, .top, true); + _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true); try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query); try std.testing.expectEqual(revision_before_search, active_raster.revision); const results_id = pane.search_pane orelse return error.MissingPdfSearchResults; @@ -1915,7 +1915,7 @@ test "PDF n/N addresses and reveals distinct MuPDF hits on one page" { p.locations_config.context = 2; p.locations_config.tscontext = true; - _ = try pardes.look.runSearch(p, 0, "Pardes", .text, .top, true); + _ = try pardes.look.runSearch(p, 0, "Pardes", .top, true); const results_id = pane.search_pane orelse return error.MissingPdfSearchResults; const results = p.panes[results_id].?.file.?; var found: [3]bool = @splat(false); diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index 73509c24..cf367c5a 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -37,6 +37,29 @@ wheel up 110 50 wheel up 110 50 wheel up 110 50 wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 +wheel up 110 50 wait 10000 Look enter, right-click wait 10000 Exec tab, middle-click wait 10000 Filter diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 571bacbc..72bb85a7 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -37,6 +37,7 @@ .collapsed = false, .serial = 1, .tag_tail = null, + .attached_to = null, .terminal = .{ .cwd = "/tmp/pardes-snap/dump/cwd", .shell = "", @@ -62,6 +63,7 @@ .collapsed = false, .serial = 2, .tag_tail = null, + .attached_to = null, .terminal = .{ .cwd = "/tmp/pardes-snap/dump/cwd", .shell = "", @@ -87,6 +89,7 @@ .collapsed = false, .serial = 3, .tag_tail = null, + .attached_to = null, .terminal = .{ .cwd = "/tmp/pardes-snap/dump/cwd", .shell = "", diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 47480b83..e5c11193 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -2,91 +2,61 @@ | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del -| 1 Find SPC f -== snap armed grid=120x41 cursor=119,4 -|3: 1 Find Find -|4: Find / -== snap typing grid=120x41 cursor=119,3 -|3: 1 Find Find /zqm -|4: -== snap results grid=120x41 cursor=7,3 -|3: 1 Find -|5: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del -|6: 1 sub/ZQMARK-beta.txt -|7: 2 sub/nest/zqmark-gamma.txt -|8: 3 zqmark-alpha.txt -|9: 4 -== snap first grid=120x41 cursor=7,10 -|9: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del -|10: 1 beta body -== style first grid=120x41 -|0: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-119 #becfc4,#314738, -|2: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-36 #d3b0d9,#1d2824, 37-119 #b2c3b8,#1d2824, -|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-119 d,#0d1410, -|5: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-35 #d3b0d9,#1d2824, 36-119 #b2c3b8,#1d2824, -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|8: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|9: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-47 #dfbce5,#314738, 48-119 #becfc4,#314738, -|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-119 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-119 d,#0d1410, -|12: 0-0 d,#608269, 1-119 d,#0d1410, -|13: 0-0 d,#608269, 1-119 d,#0d1410, -|14: 0-0 d,#608269, 1-119 d,#0d1410, -|15: 0-0 d,#608269, 1-119 d,#0d1410, -|16: 0-0 d,#608269, 1-119 d,#0d1410, -|17: 0-0 d,#608269, 1-119 d,#0d1410, -|18: 0-0 d,#608269, 1-119 d,#0d1410, -|19: 0-0 d,#608269, 1-119 d,#0d1410, -|20: 0-0 d,#608269, 1-119 d,#0d1410, -|21: 0-0 d,#608269, 1-119 d,#0d1410, -|22: 0-0 d,#608269, 1-119 d,#0d1410, -|23: 0-0 d,#608269, 1-119 d,#0d1410, -|24: 0-0 d,#608269, 1-119 d,#0d1410, -|25: 0-0 d,#608269, 1-119 d,#0d1410, -|26: 0-0 d,#608269, 1-119 d,#0d1410, -|27: 0-0 d,#608269, 1-119 d,#0d1410, -|28: 0-0 d,#608269, 1-119 d,#0d1410, -|29: 0-0 d,#608269, 1-119 d,#0d1410, -|30: 0-0 d,#608269, 1-119 d,#0d1410, -|31: 0-0 d,#608269, 1-119 d,#0d1410, -|32: 0-0 d,#608269, 1-119 d,#0d1410, -|33: 0-0 d,#608269, 1-119 d,#0d1410, -|34: 0-0 d,#608269, 1-119 d,#0d1410, -|35: 0-0 d,#608269, 1-119 d,#0d1410, -|36: 0-0 d,#608269, 1-119 d,#0d1410, -|37: 0-0 d,#608269, 1-119 d,#0d1410, -|38: 0-0 d,#608269, 1-119 d,#0d1410, -|39: 0-0 d,#608269, 1-119 d,#0d1410, -|40: 0-0 d,#608269, 1-119 d,#0d1410, -== snap second grid=120x41 cursor=7,13 -|12: /tmp/pardes-snap/find/cwd/sub/nest/zqmark-gamma.txt Save Tty Collapse Del -|13: 1 gamma body -== snap third grid=120x41 cursor=7,16 -|15: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Save Tty Collapse Del -|16: 1 alpha body -== snap back grid=120x41 cursor=7,13 -== snap word grid=120x41 cursor=7,13 -|3: 1 Find Find -|4: Find / -== snap cancel grid=120x41 cursor=7,7 -|3: 1 Find Find / -|4: -|13: 1 gamma body Last -== snap nomatch grid=120x41 cursor=7,3 -|3: 1 Find -|6: 1 -|7: -|8: -|13: 1 gamma body -== snap refit grid=120x41 cursor=7,3 -|6: 1 sub/ZQMARK-beta.txt -|7: 2 sub/nest/zqmark-gamma.txt -|8: 3 zqmark-alpha.txt -== snap topbar grid=120x41 cursor=12,16 -|6: 1 zqmark-alpha.txt -|7: 2 -|8: -|16: 1 alpha body Find +| 1 Find zqm SPC f +== snap armed grid=120x41 cursor=7,23 +|3: 1 Find zqm Find +|22: ^ +Search 1/5 Del +|23: Find +|24: here.txt +|25: other.txt +|26: sub/ZQMARK-beta.txt +|27: sub/nest/zqmark-gamma.txt +|28: zqmark-alpha.txt +|32: /tmp/pardes-snap/find/cwd/+Preview Del +|33: 1 +== snap typing grid=120x41 cursor=10,23 +|3: 1 Find zqm +|22: ^ +Search 1/3 Del +|23: Find zqm +|24: zqmark-alpha.txt +|25: sub/ZQMARK-beta.txt +|26: sub/nest/zqmark-gamma.txt +|27: +|28: +|32: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Del +|33: 1 alpha body +== snap next grid=120x41 cursor=10,23 +|22: ^ +Search 2/3 Del +|32: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Del +|33: 1 beta body +== snap promoted grid=120x41 cursor=7,33 +|22: +Search 2/3 Save Unattach Del +|32: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del +== snap nomatch grid=120x41 cursor=11,14 +|13: ^ +Search 0 Del +|14: Find zzqq +|22: +|23: /tmp/pardes-snap/find/cwd/+Preview Del +|24: 1 +|25: +|26: +== snap cancel grid=120x41 cursor=7,3 +|13: +|14: +|22: +Search 2/3 Save Unattach Del +|23: Find zqm +|24: zqmark-alpha.txt +|25: sub/ZQMARK-beta.txt +|26: sub/nest/zqmark-gamma.txt +== snap topbar grid=120x41 cursor=14,3 +|3: 1 Find zqm Find +|13: +Search 1/3 Del +|14: Find zqm +|15: zqmark-alpha.txt +|16: sub/ZQMARK-beta.txt +|17: sub/nest/zqmark-gamma.txt +|22: +|23: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Del +|24: 1 alpha body +|25: +|26: diff --git a/test/snapshots/find.snap b/test/snapshots/find.snap index b2e36973..17470040 100644 --- a/test/snapshots/find.snap +++ b/test/snapshots/find.snap @@ -1,19 +1,18 @@ -# The Find builtin (SPC f f) = `fd`, in-core: it arms the SAME tag input `/` -# does, but Enter walks the pane's DIRECTORY instead of its text and writes one -# matching path per row into a "+Search" OUTPUT BUFFER. Every row is therefore -# an ordinary look target, which is the whole point: n/N SELECT the next/prev -# one with no code of their own, and the look chord — Enter, the same one that -# opens a path anywhere else — is what OPENS it. Focus then follows the file -# that opened, but the look was made FROM the results buffer, so the next n -# resumes stepping that same list. Where each pane lands is acme's placement -# (docs/typ/guide.typ, where new panes go): under the text of the pane with the -# most blank rows. The walk skips .git, matches the NAME -# case-insensitively, and sorts (readdir order is not stable). `SPC f s` is -# Save, which moved out of `w` to make this group. +# SPC f f: a query pane under the pane (Query.zig), line 1 `Find `, typed +# into. The files below the pane's directory are listed once, on the disk +# engine's worker (rg --files when it is on PATH, else the sorted walk: both +# pass over .git), and each key scores them fuzzily (pick's scorer), the best +# first, the matched letters tinted. The current one is shown in the +# +Preview under the query pane, born with it so nothing moves later; +# Ctrl-n / Ctrl-p step it, never the pointer. Enter makes the preview the +# file's pane where it stands. Esc while typing closes the query pane and +# gives its rows back. A query that matches nothing is a count of 0, not an +# exit. B2 on `Find` with a selection asks with that word, the keyboard +# staying in the text. dirmk sub dirmk sub/nest dirmk .git -file here.txt Find +file here.txt Find zqm file zqmark-alpha.txt alpha body file sub/ZQMARK-beta.txt beta body file sub/nest/zqmark-gamma.txt gamma body @@ -22,108 +21,51 @@ file .git/zqmark-hidden.txt hidden body start 41 120 here.txt wait 8000 here.txt stable 700 20000 -# SPC f is a GROUP now (Find + New + Save): the indicator stays on the tag +# SPC f is a group (Find, New, Save, Recent, Grep): the indicator waits key space key f stable 400 5000 snap group -# ... and the second f arms the input, marker visible in the tag +# the second f opens the query pane: every file listed, line 1 `Find ` key f -stable 400 5000 +wait 10000 zqmark-alpha.txt +stable 700 15000 snap armed text zqm -stable 400 5000 -snap typing -# Enter walks: three hits, sorted, .git's copy skipped, other.txt not matched -key enter -wait 10000 zqmark-alpha.txt stable 700 15000 -snap results -# n SELECTS row 1 and Enter looks it — a path, so the file OPENS, under the -# list's text, and each file after it under the one before. -key space j n -key enter +snap typing +# the next one current, its text in the preview +key c-n wait 10000 beta body stable 700 15000 -snap first -snapstyle first -key space j n -key enter -wait 10000 gamma body -stable 700 15000 -snap second -key space j n -key enter -wait 10000 alpha body -stable 700 15000 -snap third -# N walks back up one row; Enter looks it, and the file is already open, so -# the look just focuses it -key space j p +snap next +# Enter: the preview is that file's pane now, where it stood key enter stable 700 15000 -snap back -# executing the WORD Find (middle-click in a body) arms the same input — the -# enum IS the dispatch — and Esc abandons it. The input is its own line, so an -# abandoned one leaves nothing behind in the tag -press middle 8 4 -release middle 8 4 -stable 700 10000 -snap word -key esc -settle 100 -stable 400 5000 -snap cancel -# every search is asked from a PANE, and both a look and now a step leave you -# somewhere else — so click back into here.txt first. That is not bookkeeping: -# a search never refills the buffer it was asked FROM (fillResults skips it), -# so `owned by here.txt` is the whole premise of the two steps below. +snap promoted +# a second Find from here.txt reuses its query pane; nothing found is 0 press left 8 4 release left 8 4 stable 400 5000 -# a no-match walk opens an empty list of its own, under the last file's text. key space key f key f text zzqq -key enter -stable 700 10000 -# n does not stop on the empty list, because the walk is a RING across panes -# rather than one buffer's rows: with nothing look-able here it carries on -# into the list that DOES have some — the zqm one — and resumes it one row -# past where the N above left it. Nothing opens; only the selection moved. -key space j n -stable 400 5000 +stable 700 15000 snap nomatch -# ... and asking for `zqm` AGAIN re-arms the list it ALREADY filled instead of -# stacking an identical twin under the empty one — even though the step above -# left the cursor sitting in the zqm list, so the reuse is by what a buffer -# HOLDS (this search, this pattern, this directory), not by which one anything -# happens to point at. Asked from here.txt again (the click, as above), and -# the LIST it rewrites is therefore the `nomatch` frame unchanged, down to the -# byte — only the cursor comes back with it. -press left 8 4 -release left 8 4 -stable 400 5000 -key space -key f -key f -text zqm -key enter -wait 10000 zqmark-alpha.txt +# Esc: the kept rows of the last query are back +key esc +settle 100 stable 700 15000 -snap refit -# Find is a TOPBAR word too: the same -# builtin the leader path runs, reached with the mouse. Chorded — a selection -# held when it runs IS the argument — so dragging over `alpha` and clicking -# Find walks for that name with nothing typed and no input armed. Row 17 is -# `alpha body`: the three found files stack in the order the looks above -# OPENED them, which is beta, gamma, alpha down the column. -press left 8 17 -drag left 13 17 -release left 13 17 +snap cancel +# B2 on Find with `zqm` selected in here.txt: the query pane under it, the +# keyboard still in here.txt +press left 13 4 +drag left 15 4 +release left 15 4 stable 400 5000 press middle @Find 1 release middle @Find 1 +wait 10000 Find zqm stable 700 15000 snap topbar diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index 62c37c25..5de12bab 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -19,78 +19,69 @@ | /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls | g.txt -== snap typing grid=180x31 cursor=89,7 -|7: 1 l1 /MARK -== snap results grid=180x31 cursor=10,8 -|7: 1 l1 -|21: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse LocationsConfig Del -|22: 1 g.txt:2:1-4 -|23: 2 MARK a -|24: 3 g.txt:6:1-4 -|25: 4 MARK b -|26: 5 g.txt:10:1-4 -|27: 6 MARK c -|28: 7 -== style results grid=180x31 +== snap slash grid=180x31 cursor=3,10 +|9: ^ +Search 0 Del +|10: / +|11: +|12: +|13: +|14: +|15: +|16: +== snap typing grid=180x31 cursor=7,10 +|9: ^ +Search 1/3 Del +|10: /MARK +|11: 2 MARK a +|12: 6 MARK b +|13: 10 MARK c +== style typing grid=180x31 |0: 0-1 d,#1d2824, 2-179 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-89 #becfc4,#314738, 90-91 #becfc4,#887455, 92-179 #b2c3b8,#1d2824, |2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-91 #b2c3b8,#496656, 92-120 #b2c3b8,#1d2824, 121-129 #d3b0d9,#1d2824, 130-179 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|6: 0-1 d,#add38a, 2-30 #becfc4,#314738, 31-36 #dfbce5,#314738, 37-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|15: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|16: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|6: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-36 #d3b0d9,#1d2824, 37-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, +|7: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|8: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|9: 0-1 #000000,#add38a, 2-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|15: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|16: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |17: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|21: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-38 #d3b0d9,#1d2824, 39-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, -|22: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, -|23: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, -|25: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|26: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, -|27: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|28: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, +|21: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|22: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|23: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|24: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|25: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|26: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|27: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, +|28: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |29: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |30: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -== snap second grid=180x31 cursor=10,12 -== snap third grid=180x31 cursor=10,12 +== snap ctrln grid=180x31 cursor=7,10 |7: 5 l5 |8: 6 MARK b -|9: 7 l7 -|10: 8 l8 -|11: 9 l9 -|12: 10 MARK c -|13: 11 l11 -|14: 12 l12 -|15: -|16: -== snap back grid=180x31 cursor=10,12 -|7: 1 l1 -|8: 2 MARK a -|9: 3 l3 -|10: 4 l4 -|11: 5 l5 -|12: 6 MARK b -|13: 7 l7 -|14: 8 l8 -|15: 9 l9 -|16: 10 MARK c -== snap cancel grid=180x31 cursor=10,12 -== snap nomatch grid=180x31 cursor=7,26 -|11: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse LocationsConfig Del -|12: 1 +|9: ^ +Search 2/3 Del +== snap landed grid=180x31 cursor=10,8 +|9: +Search 2/3 Save Unattach Del +== snap n grid=180x31 cursor=10,8 +|7: 9 l9 +|8: 10 MARK c +== snap N grid=180x31 cursor=10,7 +|7: 6 MARK b +|8: 7 l7 +== snap cancel grid=180x31 cursor=10,7 +== snap nomatch grid=180x31 cursor=7,10 +|9: ^ +Search 0 Del +|10: /zzqq +|11: +|12: |13: -|14: -|15: -|16: diff --git a/test/snapshots/fsearch.snap b/test/snapshots/fsearch.snap index 431e7126..fbb9baeb 100644 --- a/test/snapshots/fsearch.snap +++ b/test/snapshots/fsearch.snap @@ -1,13 +1,13 @@ -# `/` file search: the pattern types into the tag (persistent, no popup); -# Enter searches the buffer in-core and writes `path:LINE:COL-ENDCOL text` into -# a +Search OUTPUT BUFFER (a file pane with no file behind it — no Save in its -# tag) — AND GOES TO THE FIRST HIT, which is the step `n` is and the look Enter -# is, run for you in that buffer. From there n/N SELECT the next/prev row and -# open nothing, and Enter — the look chord — is what scrolls the file pane to -# the hit AND SELECTS IT: the row names the match's whole span, not just where -# it starts. Esc abandons the input; a no-match search opens an EMPTY buffer -# (every search gets its own, stacked under the pane) with nothing in it for n -# to stop on, and goes nowhere. +# `/` in a file: its query pane under it (Query.zig), line 1 `/` and the +# pattern, typed into; nothing on the notice band. Each key searches the +# file again (a regex, any case unless it has a capital): every match is +# tinted and ticked on the scroll rail, the first at or after the cursor +# selected and in view, and the rows under line 1 are the lines holding a +# match, a line number in the gutter. Ctrl-n steps while typing; Enter puts +# the keyboard on the match, the pattern in `/`, and keeps the rows as text; +# n / N then step the matches in the file, round the end without a word. A +# later `/` reuses the pane; Esc while typing brings the kept rows back. A +# pattern that matches nothing is a count of 0, not an exit. file g.txt l1\nMARK a\nl3\nl4\nl5\nMARK b\nl7\nl8\nl9\nMARK c\nl11\nl12 # Builtins announce themselves by default, and an announcement is a band at # the top of the body -- which moves every row this script clicks. What the @@ -30,51 +30,32 @@ release right 6 9 wait 10000 MARK a stable 700 15000 snap opened -# / starts the search input in the tag; the pattern is visible while typing key / stable 400 5000 +snap slash text MARK stable 400 5000 snap typing +snapstyle typing +key c-n +stable 400 5000 +snap ctrln key enter -# Locations stack the target under its line now, so the two halves are -# two rows: wait for both rather than for one joined line. -wait 10000 g.txt:2:1-4 -wait 10000 MARK a stable 700 10000 -# ...and the submit already looked result 1: the file scrolled to line 2 and -# the four cells the pattern matched there came up selected — the styles below -# are what prove the second half of that. No `n` was pressed to get here. -snap results -snapstyle results -# n/N walk on from there, one row of the list per press, Enter looking what -# the step selected -key space j n -key enter -stable 700 15000 -snap second -key space j n -key enter -stable 700 15000 -snap third -# N walks back up to result 2 (line 6), Enter looks it -key space j p -key enter -stable 700 15000 -snap back -# Esc abandons the input: the tag tail is restored +snap landed +text n +stable 400 5000 +snap n +text N +stable 400 5000 +snap N key / text zz key esc settle 100 stable 400 5000 snap cancel -# a no-match search: nothing in the empty list for n to stop on, so the ring -# carries it back into the list that has rows and it resumes there key / text zzqq -key enter stable 700 10000 -key space j n -stable 400 5000 snap nomatch diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 957096c3..6dbe19fa 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -19,22 +19,28 @@ | /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del | ls | a.txt noise.txt sub -== snap typing grid=180x31 cursor=89,7 -|7: 1 hello TARGET one Grep /TARGET -== snap results grid=180x31 cursor=7,7 -|7: 1 hello TARGET one -|21: /tmp/pardes-snap/grep/cwd/+Search Save Tty Collapse LocationsConfig Del -|22: 1 a.txt:1:7-12 hello TARGET one -|23: 2 a.txt:3:6-11 last TARGET line -|24: 3 sub/b.txt:2:1-6 TARGET inside sub -|25: 4 -== snap first grid=180x31 cursor=18,7 -== snap opened-hit grid=180x31 cursor=12,12 -|10: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del -|11: 1 deep -|12: 2 TARGET inside sub -== snap nomatch grid=180x31 cursor=2,4 -|25: /tmp/pardes-snap/grep/cwd/sub/+Search Save Tty Collapse LocationsConfig Del -|26: 1 -== snap chordsel grid=180x31 cursor=19,7 -== snap chord grid=180x31 cursor=19,7 +== snap typing grid=180x31 cursor=13,10 +|9: ^ +Search 1/3 Del +|10: Grep TARGET +|11: a.txt +|12: 1 hello TARGET one +|13: /tmp/pardes-snap/grep/cwd/+Preview Del +|14: 1 +== snap second grid=180x31 cursor=13,10 +|7: 2 nothing here +|8: 3 last TARGET line +|9: ^ +Search 2/3 Del +== snap preview grid=180x31 cursor=13,10 +|9: ^ +Search 3/3 Del +|13: /tmp/pardes-snap/grep/cwd/sub/b.txt Del +|14: 1 deep +|15: 2 TARGET inside sub +== snap opened-hit grid=180x31 cursor=12,15 +|9: +Search 3/3 Save Unattach Del +|13: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del +== snap nomatch grid=180x31 cursor=11,15 +|14: ^ +Search 0 Del +|15: Grep zzqq +== snap esc grid=180x31 cursor=12,15 +|14: 1 deep +|15: 2 TARGET inside sub diff --git a/test/snapshots/grep.snap b/test/snapshots/grep.snap index b3ce2947..16e61d20 100644 --- a/test/snapshots/grep.snap +++ b/test/snapshots/grep.snap @@ -1,31 +1,20 @@ -# The Grep builtin (topbar word, `SPC f g`): `grep -R`, in-core. It arms the -# SAME tag input `/` and Find use, but the walk reads file CONTENTS under every -# pane's directory at once — minus any directory another pane's already -# contains, so a tree two panes sit in is searched ONCE and every hit appears -# once. A row is `path:LINE:COL-ENDCOL text` — the match's whole span, so -# looking it SELECTS the hit — with the path RELATIVE to the directory -# of the pane that asked — the same directory its results buffer is named in, -# so the short name resolves; only a hit from outside that tree stays absolute. -# n/N SELECT the next/prev row like any other result list and open nothing — -# one press per row, the location at its head, never the matched text after it; -# Enter looks what they leave selected, and a row pointing into a file nothing -# has open yet opens it. +# The Grep builtin (topbar word, `SPC f g`): the query pane under the pane +# that asked, line 1 `Grep ` and the text, the lines of the files below its +# directory holding it (literally, any case unless it has a capital), on the +# disk engine's worker once the typing pauses: rg --json when it is on PATH, +# else the sorted walk. The rows sit under their file's name, a line number +# in the gutter. A hit in a file an open pane shows is shown there; one in a +# file nothing shows, in the +Preview under the query pane, which Enter makes +# the file's pane. A query that matches nothing is a count of 0, and Esc +# while typing brings the kept rows back. dirmk sub file a.txt hello TARGET one\nnothing here\nlast TARGET line file sub/b.txt deep\nTARGET inside sub file noise.txt nothing to see -# Builtins announce themselves by default, and an announcement is a band at -# the top of the body -- which moves every row this script clicks. What the -# verbs do is what is under test, not the announcement. config Verbose off -# The stacked layout spends two rows on each hit, which puts the third one -# below the fold of this results pane; the claim here is which hits there are. -config LocationsConfig layout:inline start 31 180 -n 3 wait 8000 a.txt stable 700 20000 -# open a.txt: a SECOND pane, whose directory the shell's cwd already covers — -# its root is dropped, which is what keeps the hits below un-duplicated press left 5 9 release left 5 9 stable 400 5000 @@ -39,70 +28,34 @@ release right 6 9 wait 10000 hello TARGET stable 700 15000 snap opened -# middle-click Grep on the topbar: the input -# arms on the ACTIVE pane's tag, exactly where `/` would have typed +# middle-click Grep on the topbar: the query pane under a.txt, typed into press middle @Grep 1 release middle @Grep 1 stable 400 5000 text TARGET -stable 400 5000 -snap typing -# Enter walks: two hits in a.txt, one in sub/b.txt, sorted by path — and the -# file that holds none of them contributes no row. -key enter -wait 10000 sub/b.txt:2:1 +# three lines (the pane is short: its count says how many) +wait 10000 +Search 1/3 stable 700 15000 -snap results -# n selects the first row and Enter looks it: absolute path, line 1, columns -# 7..12 (`TARGET`), and those six cells come up selected -key space j n -key enter +snap typing +# a.txt's hits are shown in a.txt; sub/b.txt's in the preview +key c-n stable 700 15000 -snap first -# ...and stepping on into sub/b.txt, then looking it, opens the file nothing -# had open -key space j n -key enter +snap second +key c-n +wait 10000 deep stable 700 15000 -key space j n +snap preview key enter -wait 10000 TARGET inside sub stable 700 15000 snap opened-hit -# a pattern nothing holds: an empty list of its own, with nothing in it for n -# to stop on — so the ring carries that step out of it and on round. It lands -# in the SHELL, whose `ls` row is free text and steps word by word: the TARGET -# list is standing on its last row, and a row-grained walk has nothing left in -# it to offer. The look above is why these read the way they do: it left the -# cursor in sub/b.txt, so the empty list is named in sub/ rather than cwd/, and -# it left the hit SELECTED there (a ranged result row is one a look selects). -# Armed from the LEADER, not the topbar word, because of that selection: a -# topbar execute chords whatever is selected into its argument, so a -# middle-click here would run `Grep TARGET` and never ask for a pattern at -# all. The leader path runs the builtin with no argument, which is what this -# step is about; the chord itself is the last two snaps below. key space key f key g stable 400 5000 text zzqq -key enter stable 700 10000 -key space j n -stable 400 5000 snap nomatch -# the acme chord: a builtin executed with a SELECTION held takes it as the -# argument, so dragging over `TARGET` in a.txt and then clicking Grep runs the -# walk on that word at once — no tag input, nothing typed. TARGET already has -# a list open from above, so this refills THAT one; only the zzqq list below is -# a second buffer, because only it is a different search. -press left @TARGET 8 -drag left @TARGET+6 8 -release left @TARGET+6 8 +key esc +settle 100 stable 400 5000 -snap chordsel -press middle @Grep 1 -release middle @Grep 1 -wait 10000 sub/b.txt:2:1 -stable 700 15000 -snap chord +snap esc diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 4a286faa..86a4b0ac 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -68,28 +68,31 @@ |12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#3c614a, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-149 #f5f7ee,#0d1410, -== snap hit1 grid=150x31 cursor=15,14 -|17: /tmp/pardes-snap/lookrange/cwd/+Search Save Tty Collapse LocationsConfig Del -|18: 1 r.txt:7:4-9 -|19: 2 gg NEEDLE gg -|20: 3 r.txt:8:6-11 -|21: 4 hhhh NEEDLE -|22: 5 +== snap hit1 grid=150x31 cursor=17,15 +|21: +Search 2/2 Save Unattach Del +|22: /NEEDLE +|23: 7 gg NEEDLE gg +|24: 8 hhhh NEEDLE == style hit1 grid=150x31 -|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-40 #d3b0d9,#1d2824, 41-149 #b2c3b8,#1d2824, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #f7e4a5,#5e4923, 16-16 #f7e4a5,#0d1410, 17-149 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|21: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-149 #f7e4a5,#0d1410, -|22: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -== snap hit2 grid=150x31 cursor=17,15 -== style hit2 grid=150x31 -|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, -== snap back grid=150x31 cursor=15,14 -== style back grid=150x31 +|16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|18: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|21: 0-1 d,#496656, 2-149 #b2c3b8,#1d2824, +|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#3c614a, 6-149 #f5f7ee,#3c614a, +== snap hit2 grid=150x31 cursor=15,14 +== style hit2 grid=150x31 |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #e5eee5,#352e19, 18-149 #e5eee5,#0d1410, +|16: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|18: 0-0 d,#5e4923, 1-149 d,#0d1410, +|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, +== snap back grid=150x31 cursor=17,15 +== style back grid=150x31 +|14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, +|16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|18: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, diff --git a/test/snapshots/lookrange.snap b/test/snapshots/lookrange.snap index eb1db60a..5133e911 100644 --- a/test/snapshots/lookrange.snap +++ b/test/snapshots/lookrange.snap @@ -51,28 +51,24 @@ release right 12 7 stable 700 15000 snap stale snapstyle stale -# --- and now the first consumer. The look above left r.txt focused, so `/` -# arms on it: the rows it writes carry the match's span, and the submit goes -# straight to the first of them — with the word itself selected, which is the -# whole reason the row spells a range and not a position. +# --- and `/`: its query pane under r.txt, line 1 the pattern, the lines +# holding it as rows (a line number in the gutter, the match tinted); Enter +# puts the keyboard on the match after the cursor, the word itself selected. key / text NEEDLE -key enter -# Locations stack the target under its line now: two rows, two waits. -wait 10000 r.txt:7:4-9 wait 10000 gg NEEDLE gg stable 700 15000 +key enter +stable 700 15000 snap hit1 snapstyle hit1 -# n selects the next row, and the Enter after it goes to that hit -key space j n -key enter +# n: the next match in the text, selected +text n stable 700 15000 snap hit2 snapstyle hit2 -# N walks back onto the first hit; Enter looks it, still selected -key space j p -key enter +# N walks back onto the first, still selected +text N stable 700 15000 snap back snapstyle back diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index c9fad7b7..18ccd775 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -15,15 +15,16 @@ | 3 a + b | 4 } | 5 -== snap gr-list grid=100x25 cursor=21,6 +== snap gr-list grid=100x25 cursor=7,14 |3: 1 mod lib; -|15: /tmp/pardes-snap/lsp-client/cwd/+Search Save Tty Collapse LocationsConfig Del -|16: 1 lib.rs:2:8-10 -|17: 2 pub fn add(a: i32, b: i32) -> i32 { -|18: 3 main.rs:4:13-15 -|19: 4 let x = add(1, 2); -|20: 5 main.rs:5:13-15 -|21: 6 let y = add(3, 4); -|22: 7 -== snap gr-opened grid=100x25 cursor=21,7 -== snap gr-back grid=100x25 cursor=21,6 +|13: ^ +Search 1/3 Del +|14: Refs +|15: lib.rs +|16: 2 pub fn add(a: i32, b: i32) -> i32 { +|17: main.rs +|18: 4 let x = add(1, 2); +|19: /tmp/pardes-snap/lsp-client/cwd/+Preview Del +|20: 1 +== snap gr-opened grid=100x25 cursor=21,6 +|13: +Search 2/3 Save Unattach Del +== snap gr-back grid=100x25 cursor=21,7 diff --git a/test/snapshots/lsp-client.snap b/test/snapshots/lsp-client.snap index db94525e..d9827a2a 100644 --- a/test/snapshots/lsp-client.snap +++ b/test/snapshots/lsp-client.snap @@ -6,7 +6,8 @@ # gd on a cross-file Location -> a look: lib.rs opens with `add` selected, # and the message row still carries the server's settled state # ("lsp lspmock: ready") because nothing has cleared it yet. -# gr -> sorted rows, selecting the next occurrence; n/N continue there. +# gr -> the text's query pane, line 1 `Refs`, rows under their files, +# the next occurrence current; n/N step the places in the text. file main.rs mod lib;\n\nfn main() {\n let x = add(1, 2);\n let y = add(3, 4);\n let _ = x + y;\n}\n file lib.rs // mock fixture\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n start 25 100 main.rs @@ -26,12 +27,12 @@ key r wait 10000 add(3, 4) stable 700 15000 snap gr-list -# step from the selected middle row to the last hit, then return -key space j n +# Ctrl-n on line 1 steps to the next hit, Enter lands there; N in the text +# goes back to the one before, round the places in main.rs +key c-n key enter stable 700 15000 snap gr-opened -key space j p -key enter +text N stable 700 15000 snap gr-back diff --git a/test/snapshots/lspdebug.snap b/test/snapshots/lspdebug.snap index ec8d136d..22fa097b 100644 --- a/test/snapshots/lspdebug.snap +++ b/test/snapshots/lspdebug.snap @@ -39,11 +39,8 @@ text client queries key enter wait 10000 client queries wait 10000 definition -# the report sits between the source and the results, so Del asks where its -# rows go: k, back to the source above -key space d -key k -key space w j enter +# Enter left the keyboard in the report, on the match; its query pane is +# attached to it, so one Del closes both, their rows back to the source key space d stable 700 15000 snap report-closed diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index d961d6bd..59a3c5d0 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,4 +1,4 @@ -== snap absrow grid=100x35 cursor=21,16 +== snap absrow grid=100x35 cursor=7,17 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse TreeContext Def Refs Del @@ -9,56 +9,70 @@ | 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse LocationsConfig Del -| 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:1:11-15 -| 2 pub const Shade = enum { -| 3 parent.zig:3:22-26 -| 4 pub fn pick(s: shade.Shade) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse TreeContext Def Refs Del -| 1 pub const Shade = enum { -| 2 verdigris, -| 3 cinnabar, -| 4 }; -| 5 -== snap abslook grid=100x35 cursor=32,5 +| 8 +| +| +| +| +| +|^ +Search 2/2 Del +| Refs +| /tmp/pardes-snap/lsprelpath/cwd/shade.zig +| 1 pub const Shade = enum { +| parent.zig +| 3 pub fn pick(s: shade.Shade) u8 { +| +| +| +| +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Preview Del +| 1 +== snap abslook grid=100x35 cursor=21,27 |3: 1 const shade = @import("../shade.zig"); +|16: +Search 1/2 Save Unattach Del +|26: /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse TreeContext Def Refs Del +|27: 1 pub const Shade = enum { +|28: 2 verdigris, +|29: 3 cinnabar, +|30: 4 }; +|31: 5 == style abslook grid=100x35 |0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-48 #dfbce5,#314738, 49-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-48 #d3b0d9,#1d2824, 49-99 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-27 #c9a7ed,#0d1410, 28-28 #e5eee5,#0d1410, 29-42 #b8d88a,#0d1410, 43-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f5f7ee,#3c614a, 33-99 #e5eee5,#0d1410, -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f5f7ee,#3c614a, 33-99 #e5eee5,#0d1410, +|6: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-45 #d3b0d9,#1d2824, 46-99 #b2c3b8,#1d2824, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f7e4a5,#5e4923, 22-22 #f7e4a5,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f7e4a5,#5e4923, 33-99 #e5eee5,#0d1410, -|15: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-43 #d3b0d9,#1d2824, 44-99 #b2c3b8,#1d2824, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, -|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|21: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-20 #e5eee5,#0d1410, 21-25 #f7e4a5,#5e4923, 26-26 #f7e4a5,#0d1410, 27-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-31 #e5eee5,#0d1410, 32-36 #f7e4a5,#5e4923, 37-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, |24: 0-0 d,#608269, 1-99 d,#0d1410, |25: 0-0 d,#608269, 1-99 d,#0d1410, -|26: 0-0 d,#608269, 1-99 d,#0d1410, -|27: 0-0 d,#608269, 1-99 d,#0d1410, -|28: 0-0 d,#608269, 1-99 d,#0d1410, -|29: 0-0 d,#608269, 1-99 d,#0d1410, -|30: 0-0 d,#608269, 1-99 d,#0d1410, -|31: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-1 d,#add38a, 2-33 #becfc4,#314738, 34-43 #dfbce5,#314738, 44-99 #becfc4,#314738, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|31: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap subrow grid=100x35 cursor=20,16 +== snap subrow grid=100x35 cursor=7,17 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse TreeContext Def Refs Del @@ -69,53 +83,67 @@ | 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse LocationsConfig Del -| 1 inner/tint.zig:1:11-14 -| 2 pub const Tint = enum { -| 3 subdir.zig:3:20-23 -| 4 pub fn hue(t: tint.Tint) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse TreeContext Def Refs Del -| 1 pub const Tint = enum { -| 2 ochre, -| 3 indigo, -| 4 }; -| 5 -== snap sublook grid=100x35 cursor=29,5 +| 8 +| +| +| +| +| +|^ +Search 2/2 Del +| Refs +| inner/tint.zig +| 1 pub const Tint = enum { +| subdir.zig +| 3 pub fn hue(t: tint.Tint) u8 { +| +| +| +| +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Preview Del +| 1 +== snap sublook grid=100x35 cursor=20,27 |3: 1 const tint = @import("inner/tint.zig"); +|16: +Search 1/2 Save Unattach Del +|26: /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse TreeContext Def Refs Del +|27: 1 pub const Tint = enum { +|28: 2 ochre, +|29: 3 indigo, +|30: 4 }; +|31: 5 == style sublook grid=100x35 |0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-48 #dfbce5,#314738, 49-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-48 #d3b0d9,#1d2824, 49-99 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-26 #c9a7ed,#0d1410, 27-27 #e5eee5,#0d1410, 28-43 #b8d88a,#0d1410, 44-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f5f7ee,#3c614a, 30-99 #e5eee5,#0d1410, -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f5f7ee,#3c614a, 30-99 #e5eee5,#0d1410, +|6: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-24 #c9a7ed,#0d1410, 25-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-45 #d3b0d9,#1d2824, 46-99 #b2c3b8,#1d2824, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f7e4a5,#5e4923, 21-21 #f7e4a5,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f7e4a5,#5e4923, 30-99 #e5eee5,#0d1410, -|15: 0-1 d,#496656, 2-43 #b2c3b8,#1d2824, 44-52 #d3b0d9,#1d2824, 53-99 #b2c3b8,#1d2824, -|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, -|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, -|21: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-20 #e5eee5,#0d1410, 21-24 #f7e4a5,#5e4923, 25-25 #f7e4a5,#0d1410, 26-99 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-29 #e5eee5,#0d1410, 30-33 #f7e4a5,#5e4923, 34-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, |24: 0-0 d,#608269, 1-99 d,#0d1410, |25: 0-0 d,#608269, 1-99 d,#0d1410, -|26: 0-0 d,#608269, 1-99 d,#0d1410, -|27: 0-0 d,#608269, 1-99 d,#0d1410, -|28: 0-0 d,#608269, 1-99 d,#0d1410, -|29: 0-0 d,#608269, 1-99 d,#0d1410, -|30: 0-0 d,#608269, 1-99 d,#0d1410, -|31: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-1 d,#add38a, 2-43 #becfc4,#314738, 44-52 #dfbce5,#314738, 53-99 #becfc4,#314738, +|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, +|30: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, +|31: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap clicked grid=100x35 cursor=15,12 +== snap clicked grid=100x35 cursor=29,5 diff --git a/test/snapshots/lsprelpath.snap b/test/snapshots/lsprelpath.snap index a83abf46..8420e134 100644 --- a/test/snapshots/lsprelpath.snap +++ b/test/snapshots/lsprelpath.snap @@ -8,7 +8,8 @@ # short to be called. # # A row in the SAME directory shortens to a bare basename; the two that a -# prefix strip can actually get wrong are here, one app each, as `gr` rows: +# prefix strip can actually get wrong are here, one app each, as `gr` rows +# (the file headers of the asking text's query pane, line 1 `Refs`): # # PARENT the enum is one level UP from the asking file, so nothing is # stripped and the row carries `/tmp/.../cwd/shade.zig`. This is @@ -32,26 +33,25 @@ file sub/subdir.zig const tint = @import("inner/tint.zig");\n\npub fn hue(t: tin start 35 100 sub/parent.zig wait 8000 fn pick stable 700 20000 -# `gr` on `Shade` in the signature (file line 3, click row 6): its -# declaration's row is in the parent directory. press left 31 6 release left 31 6 stable 400 5000 key g key r -wait 15000 cwd/shade.zig:1: +# the query pane under parent.zig, line 1 `Refs`, the rows under each file: +# shade.zig's spelled whole, its directory being above +wait 15000 cwd/shade.zig stable 700 15000 snap absrow -key esc -settle 100 -# An absolute row has to keep resolving — it is the spelling every row had -# before this, and the one every hit outside the tree still has. -key space j n +# the current row is parent.zig's own; the one before it is shade.zig's, +# shown in the +Preview, which Enter makes shade.zig's pane +key c-p +wait 10000 verdigris +stable 700 15000 key enter stable 700 15000 snap abslook snapstyle abslook -# ---- SUBDIRECTORY: under it, so the strip leaves `inner/tint.zig` ---- start 35 100 sub/subdir.zig wait 8000 fn hue stable 700 20000 @@ -60,23 +60,16 @@ release left 29 6 stable 400 5000 key g key r -wait 15000 inner/tint.zig:1: +wait 15000 inner/tint.zig stable 700 15000 snap subrow -key esc -settle 100 -key space j n +key c-p +wait 10000 ochre +stable 700 15000 key enter stable 700 15000 snap sublook snapstyle sublook -# The mouse spelling, on the OTHER row (grid row 12, 1-based click row 13). A -# right click expands to the file-ish word under the cursor -# (config.wordBounds), which has to take `inner/tint.zig:3:5-10` WHOLE — the -# separator inside a stripped path is a file char, so the scan runs back over -# `inner/` and stops on the space of the line-number prefix. A look focuses -# what it opens, so the header's cursor is the assertion: the end of `indigo` -# on line 3 of tint.zig. press right 12 13 release right 12 13 stable 700 15000 diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index 24018546..950c4d67 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -37,10 +37,10 @@ |8: |9: == snap prompt grid=70x17 cursor=69,3 -|3: 1 EXTERNAL /EXT +|3: 1 EXTERNAL Select /EXT == snap prompt-wins grid=70x17 cursor=69,4 |3: 1 AGAIN --:--:-- reloaded /tmp/pardes-snap/msg/cwd/a.txt -|4: 2 /EXT +|4: 2 Select /EXT == snap esc grid=70x17 cursor=7,4 |3: 1 AGAIN |4: 2 diff --git a/test/snapshots/msg.snap b/test/snapshots/msg.snap index 5252508a..64a77bb2 100644 --- a/test/snapshots/msg.snap +++ b/test/snapshots/msg.snap @@ -58,7 +58,7 @@ snap reloaded # its builtins instead of losing them to a long pattern. Note the tag row above # ends at `Del`: the marker and the pattern are no longer on it at all. (The # `/` keystroke also cleared the reload message, which is the rule above.) -key / +key s text EXT stable 700 15000 snap prompt diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index 3101b920..43445ed4 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -1,43 +1,55 @@ -== snap results grid=150x31 cursor=7,3 +== snap results grid=150x31 cursor=13,13 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del | 1 hello ZQMARK one | 2 see also sub/b.txt for ZQMARK two -| /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse LocationsConfig Del -| 1 a.txt:1:7-12 -| 2 hello ZQMARK one -| 3 a.txt:2:24-29 -| 4 see also sub/b.txt for ZQMARK two -| 5 sub/b.txt:1:1-6 -| 6 ZQMARK inside sub -| 7 -== snap step-row1 grid=150x31 cursor=7,6 -== style step-row1 grid=150x31 +| +| +| +| +| +| +| +|^ +Search 1/3 Del +| Grep ZQMARK +| a.txt +| 1 hello ZQMARK one +| 2 see also sub/b.txt for ZQMARK two +| sub/b.txt +| 1 ZQMARK inside sub +| +| +| +| /tmp/pardes-snap/stepgrain/cwd/+Preview Del +| 1 +== snap step-row2 grid=150x31 cursor=13,13 +|12: ^ +Search 2/3 Del +== style step-row2 grid=150x31 |0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-149 #becfc4,#314738, |2: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-38 #d3b0d9,#1d2824, 39-149 #b2c3b8,#1d2824, -|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|5: 0-1 d,#add38a, 2-32 #becfc4,#314738, 33-40 #dfbce5,#314738, 41-149 #becfc4,#314738, -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #f5f7ee,#3c614a, 19-149 #f5f7ee,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-18 #f7e4a5,#5e4923, 19-19 #f7e4a5,#0d1410, 20-149 #e5eee5,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-29 #e5eee5,#0d1410, 30-35 #f7e4a5,#5e4923, 36-36 #f7e4a5,#0d1410, 37-149 #e5eee5,#0d1410, -|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#0d1410, 14-149 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|13: 0-0 d,#608269, 1-149 d,#0d1410, -|14: 0-0 d,#608269, 1-149 d,#0d1410, -|15: 0-0 d,#608269, 1-149 d,#0d1410, -|16: 0-0 d,#608269, 1-149 d,#0d1410, -|17: 0-0 d,#608269, 1-149 d,#0d1410, -|18: 0-0 d,#608269, 1-149 d,#0d1410, +|3: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-18 #e5eee5,#352e19, 19-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-29 #e5eee5,#0d1410, 30-35 #f5f7ee,#3c614a, 36-36 #f5f7ee,#0d1410, 37-149 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-149 d,#0d1410, +|6: 0-0 d,#608269, 1-149 d,#0d1410, +|7: 0-0 d,#e5eee5, 1-149 d,#0d1410, +|8: 0-0 d,#608269, 1-149 d,#0d1410, +|9: 0-0 d,#608269, 1-149 d,#0d1410, +|10: 0-0 d,#608269, 1-149 d,#0d1410, +|11: 0-0 d,#608269, 1-149 d,#0d1410, +|12: 0-1 #000000,#add38a, 2-149 #becfc4,#314738, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #e5eee5,#0d1410, 17-22 #f7e4a5,#5e4923, 23-23 #f7e4a5,#0d1410, 24-149 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-33 #e5eee5,#0d1410, 34-39 #f7e4a5,#5e4923, 40-40 #f7e4a5,#0d1410, 41-149 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #f7e4a5,#5e4923, 17-17 #f7e4a5,#0d1410, 18-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-149 d,#0d1410, |20: 0-0 d,#608269, 1-149 d,#0d1410, |21: 0-0 d,#608269, 1-149 d,#0d1410, -|22: 0-0 d,#608269, 1-149 d,#0d1410, -|23: 0-0 d,#608269, 1-149 d,#0d1410, +|22: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-149 #b2c3b8,#1d2824, +|23: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, |24: 0-0 d,#608269, 1-149 d,#0d1410, |25: 0-0 d,#608269, 1-149 d,#0d1410, |26: 0-0 d,#608269, 1-149 d,#0d1410, @@ -45,29 +57,32 @@ |28: 0-0 d,#608269, 1-149 d,#0d1410, |29: 0-0 d,#608269, 1-149 d,#0d1410, |30: 0-0 d,#608269, 1-149 d,#0d1410, -== snap step-row2 grid=150x31 cursor=7,8 -== style step-row2 grid=150x31 -|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 #f5f7ee,#0d1410, -== snap step-row3 grid=150x31 cursor=7,10 -== snap step-wrap grid=150x31 cursor=7,6 -== snap blank-in-path grid=150x31 cursor=7,6 -|5: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del -|6: 1 two words.txt -|7: 2 -|8: -|9: -|10: -|11: -|12: +== snap step-row3 grid=150x31 cursor=13,13 +|12: ^ +Search 3/3 Del +|22: /tmp/pardes-snap/stepgrain/cwd/sub/b.txt Del +|23: 1 ZQMARK inside sub +== snap step-wrap grid=150x31 cursor=13,13 +|12: ^ +Search 1/3 Del +== snap blank-in-path grid=150x31 cursor=12,13 +|12: ^ +Search 1/1 Del +|13: Find words +|14: two words.txt +|15: +|16: +|17: +|18: +|22: /tmp/pardes-snap/stepgrain/cwd/two words.txt Del +|23: 1 == style blank-in-path grid=150x31 -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-19 #f5f7ee,#3c614a, 20-149 #f5f7ee,#0d1410, -|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, -|8: 0-0 d,#608269, 1-149 d,#0d1410, -|9: 0-0 d,#608269, 1-149 d,#0d1410, -|10: 0-0 d,#608269, 1-149 d,#0d1410, -|11: 0-0 d,#608269, 1-149 d,#0d1410, -|12: 0-0 d,#608269, 1-149 d,#0d1410, -== snap blank-opened grid=150x31 cursor=7,9 -|8: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del -|9: 1 +|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-149 d,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #e5eee5,#0d1410, 6-10 #f7e4a5,#5e4923,b 11-149 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-149 d,#0d1410, +|16: 0-0 d,#608269, 1-149 d,#0d1410, +|17: 0-0 d,#608269, 1-149 d,#0d1410, +|18: 0-0 d,#608269, 1-149 d,#0d1410, +|22: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-46 #d3b0d9,#1d2824, 47-149 #b2c3b8,#1d2824, +== snap blank-opened grid=150x31 cursor=7,23 +|12: +Search 1/1 Save Unattach Del +|22: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del diff --git a/test/snapshots/stepgrain.snap b/test/snapshots/stepgrain.snap index 0f555ff8..e807981c 100644 --- a/test/snapshots/stepgrain.snap +++ b/test/snapshots/stepgrain.snap @@ -1,22 +1,11 @@ -# WHAT ONE PRESS OF `n` TAKES, and why that is not one answer. A pane's rows -# decide it (output_pane.Grain, read in Pardes.lookSpanIn): +# ONE PRESS, ONE ROW. A query pane's rows are one a line with a hit, the +# hit's line under a gutter number, and Ctrl-n / Ctrl-p (typing on line 1) +# step them a row at a time, round the end: row 2 below matched on a line +# that mentions `sub/b.txt`, and the step does not stop on that word, as the +# old word-grained walk did; the fourth press wraps back to row 1. # -# free text — a terminal, a file, a PDF — is stepped WORD by word, several -# stops to a line, because a line of it may name several places at once (the -# `ls` row in ttylook.snap hops big.txt -> plain.txt -> sub); -# -# a RESULTS BUFFER is stepped ROW by row, on the location at the head of the -# row, because a row there IS one location and the words after it are the -# MATCHED TEXT — the same hit, spelled out. That text is full of look-able -# words, and stopping on them was stopping on the same result twice. -# -# This script is the second rule. Row 2 below matched on a line that mentions -# `sub/b.txt`, so the old word-grained walk stopped there before it ever -# reached row 3; now `n` presses and rows correspond one to one, and the fourth -# press wraps the ring back to row 1. -# -# LARGEST from the head, so a path with a BLANK in it is one span rather than -# the word in front of it: `two words.txt` selects whole and opens. +# A path with a BLANK in it is one name: `two words.txt` is found whole by +# Find and Enter opens exactly it. dirmk sub file a.txt hello ZQMARK one\nsee also sub/b.txt for ZQMARK two file sub/b.txt ZQMARK inside sub @@ -24,52 +13,36 @@ run touch 'two words.txt' start 31 150 a.txt wait 8000 hello ZQMARK stable 700 20000 -# Grep from the leader: three hits, sorted by path, the empty file contributing -# none. Row 2 is the one whose TEXT holds a path. +# Grep from the leader: three hits, under their files, the empty file +# contributing none. Row 2 is the one whose TEXT holds a path. key space key f key g stable 400 5000 text ZQMARK -key enter -wait 10000 sub/b.txt:1:1 +wait 10000 ZQMARK inside sub stable 700 15000 snap results -# one press, one row: the head of row 1... -key space j n -stable 400 5000 -snap step-row1 -snapstyle step-row1 -# ...the head of row 2, and NOT the `sub/b.txt` sitting in its matched text — -# the cursor column is the assertion -key space j n +key c-n stable 400 5000 snap step-row2 snapstyle step-row2 -# ...row 3, and then the ring comes round to row 1 again -key space j n +key c-n stable 400 5000 snap step-row3 -key space j n +key c-n stable 400 5000 snap step-wrap -# Back into the file, so the Find below is asked from a pane that is not a -# results buffer (fillResults never refills the buffer it was asked from). -press left 8 4 -release left 8 4 +key esc +settle 100 stable 400 5000 -# A path with a blank in it: the row is one span from its first cell, because -# the walk asks about the LONGEST run of the row first and the filesystem is -# what vouches for it. Enter then opens exactly what is selected. +# Find `words`: the name with a blank in it, whole key space key f key f text words -key enter wait 10000 two words.txt stable 700 15000 -key space j n -stable 400 5000 snap blank-in-path snapstyle blank-in-path key enter diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index ef1bab3a..cf690a40 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -150,10 +150,19 @@ |8: 8 hhh |9: 9 iii |10: 10 jjj -== snap search-prompt grid=100x31 cursor=99,12 -|12: 1 ZZONE /ZZ +== snap search-prompt grid=100x31 cursor=5,21 +|20: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del +|21: /ZZ +|22: 1 ZZONE +|23: 2 ZZTWO +|30: ^ +Search 1/2 Del == snap leader grid=100x31 cursor=9,13 |12: 1 ZZONE SPC +|20: +|21: +|22: +|23: +|30: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del == snap cut-down grid=100x31 cursor=7,5 |2: 1 aaa |3: 2 bbb diff --git a/test/snapshots/tagbottomshort.golden b/test/snapshots/tagbottomshort.golden index 00d8cad0..1979cc60 100644 --- a/test/snapshots/tagbottomshort.golden +++ b/test/snapshots/tagbottomshort.golden @@ -1,41 +1,41 @@ -== snap roomy grid=80x11 cursor=79,2 +== snap roomy grid=80x11 cursor=5,5 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ +| 1 one | 2 two -| 3 three -| 4 four -| 5 five -| 6 six +| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +| /ZZ | | -| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap two-body grid=80x5 cursor=79,2 +| +| +|^ +Search 0 Del +== snap two-body grid=80x5 cursor=5,3 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ -| 2 two | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap one-body grid=80x4 cursor=79,2 +| /ZZ +|^ +Search 0 Del +== snap one-body grid=80x4 cursor=79,3 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +|^ +Search 0 Del == snap tag-only grid=80x2 cursor=79,1 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap regrown grid=80x11 cursor=79,2 +== snap regrown grid=80x11 cursor=5,5 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| 1 one /ZZ +| 1 one | 2 two -| 3 three -| 4 four -| 5 five -| 6 six +| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +| /ZZ | | -| /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del +| +| +|^ +Search 0 Del == snap leader-one-body grid=80x4 cursor=7,2 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol diff --git a/test/snapshots/topbarexec.golden b/test/snapshots/topbarexec.golden index 5b7d2234..63ed382c 100644 --- a/test/snapshots/topbarexec.golden +++ b/test/snapshots/topbarexec.golden @@ -26,14 +26,20 @@ |8: │pinch 1.0000 │ |9: │tscroll 0.0000 │ |10: ╰────────────────────────────────────╯ -== snap arg-still-spliced grid=90x21 cursor=14,5 +== snap arg-still-spliced grid=90x21 cursor=14,4 |1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |2: /tmp/pardes-snap/topbarexec/cwd Tty+bash Sa /tmp/pardes-snap/topbarexec/cwd Tty+bash Sa |3: ve Mode Filter Collapse Del ve Mode Filter Collapse Del -|4: ls Find ls -|5: zmarkfile.txt zmarkfile.txt -|6: -|7: /tmp/pardes-snap/topbarexec/cwd/+Search Sav -|8: e Tty Collapse Del -|9: 1 zmarkfile.txt -|10: 2 +|4: zmarkfile.txt Find ls +|5: zmarkfile.txt +|6: +Search 1/1 Del +|7: Find zmarkfile.txt +|8: zmarkfile.txt +|9: /tmp/pardes-snap/topbarexec/cwd/zmarkfile.t +|10: xt Del +|11: 1 hay ZQNEEDLE stack +|12: +|13: /tmp/pardes-snap/topbarexec/cwd Tty+bash Sa +|14: ve Mode Filter Collapse Del +|15: ls +|16: zmarkfile.txt -- cgit v1.3 From 9299281492d63e549ab274034efb59ab4e9d96f6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:11:11 -0300 Subject: Search converge 6/6: SearchPlace column, the finder column at the right edge holding the query panes; n/N in a frozen query pane; the design doc --- docs/search-proto-converge.md | 183 ++++++++++++++++++++++++++++++++ src/Finder.zig | 240 ++++++++++++++++++++++++++++++++++++++++++ src/Query.zig | 27 ++++- src/exec.zig | 15 ++- src/layout.zig | 40 +++++-- src/pardes.zig | 18 +++- 6 files changed, 503 insertions(+), 20 deletions(-) create mode 100644 docs/search-proto-converge.md create mode 100644 src/Finder.zig (limited to 'src/Query.zig') diff --git a/docs/search-proto-converge.md b/docs/search-proto-converge.md new file mode 100644 index 00000000..4c7b7006 --- /dev/null +++ b/docs/search-proto-converge.md @@ -0,0 +1,183 @@ +# Search, converged: the query pane + +The design the twelve prototypes added up to (CONVERGE.md), built as the +product in six changes. One pane kind does all searching: the **query +pane**, a `+Search` attached under the pane that asked (its *owner*), whose +body's line 1 is the query, typed into, and whose rows below are made live +from a source. The owner shows the set in its own text (its **places**: +tints, rail ticks, the current one selected), and a row that points at a +file no pane shows is shown in a **+Preview** attached under the query +pane. Everything on screen is text in a pane: B1/B2/B3 and the chords work +on all of it, nothing is drawn over anything, and the notice band keeps +only the prompts that are not search. + +## The pieces, and where they came from + +| piece | file | lifted from | +|---|---|---| +| attached panes: a group under its owner, rows from the owner alone, moving/folding/closing with it, seam drag, Dump/Restore, `Unattach` | `src/layout.zig` "Attached panes", `Pane.attached_to` | attached | +| places: every match tinted, rail ticks (B1 on a tick goes there), current selected and in view, smart-case regex, view-first sliced scan, silent wrap | `src/Places.zig`, `Pane.places` | incsearch (MatchSet) | +| the query pane: line 1, its first word the source, live rows, preview, Enter/Esc/Del, reuse, settings | `src/Query.zig`, `Pane.query` | queryline, pick, live, preview, everywhere | +| fuzzy names (files, recent, panes, declarations) | `src/Names.zig` | pick (its scorer, whole) | +| the disk engine: Grep and Find's listing on a worker, rg or the walk, generations, debounce, cap + `More`; and the declarations parse | `src/Stream.zig`, `Pardes.stream` | stream | +| the finder column (`SearchPlace column`) | `src/Finder.zig`, `Pardes.finder` | column | + +## Semantics + +**Line 1's first word names the source**; editing it changes the source. + +| line 1 | searches | keys | +|---|---|---| +| `/pat` | the owner's text, a regex, any case unless a capital | `/`, `*` (keyboard stays) | +| `Find name` | the files below the pane's directory, fuzzy | `SPC f f`, `Find` | +| `Grep text` | their lines, literally, smart case | `SPC f g`, `Grep` | +| `Recent name` | the files opened lately, fuzzy | `SPC f r`, `Recent` | +| `Panes name` | the open panes, fuzzy | `SPC b b`, `Panes` | +| `Symbols name` | the owner's declarations, fuzzy | `SPC s s` | +| `All pat` | every open pane's text, rows under `@pN name (count)` | `SPC /` | +| `Refs`, `Def`, `Impl`, `Diagnostics` | the language server's lists | `gr`, `gd`, `gi`, `]d`, ... | + +`Search ` is the builtin under the three argument paths +(`config.leader_args`, pick's table). + +**Rows look like Callstack's**: a gutter line number, the hit's line with +the match tinted (every match on a line tinted, one row a line), under the +declaration it is in (once a parse exists, see below), under the file +(Grep, the LSP lists), under `@pN name (count)` in serial order (All). +B3 on a row's line number looks at its address; B3 on its code is a word +Look as anywhere; B2 on line 1 runs it again. The pane has no gutter of its +own, and its rows are read-only while live (queryline's clampEdit). + +**Keys** on line 1, typing: Ctrl-n / Ctrl-p (and Down / Up, `config.query_next` +/ `query_prev`) step the current row; Enter lands; Esc cancels. Tab stays the +exec chord. In the pane's normal mode (live or frozen): n / N step its rows, +Enter on a row lands on it. In the owner: n / N step its places, round the +end without a word; with no places (or after an `s` changed the register) +they are helix's register search as before. `]d` / `[d` step the +diagnostics' places once a Diagnostics query fed them. + +**The current row shows its target**, the keyboard staying on line 1: a +place in an open pane's text is selected there and scrolled into view +(remembered for Esc); a file an open pane shows, its line there; any other +file in the +Preview. Never the pointer. + +**Enter** puts the keyboard on the current hit in its pane (the +Preview +promoted in place: same slot, serial, rect, an unattached file pane from +then on), fills `/`, and freezes the rows into ordinary text (tag ` Save +Unattach Del`). A `/` freezes its whole list (every place found first, 2000 +rows at most), a Grep every line it has. **Esc** while typing puts every +view back, clears the places it fed and closes the pane, its rows back to +the owner; a reused pane's frozen rows and their places come back instead. +**Del** closes it; closing the owner closes its group. + +**Nothing moves while you type.** The pane is born at tag + 1 + `SearchRows` +(8) rows out of the owner's rows alone, with its +Preview when the source +can preview (the owner's spare rows split between the two if it is short); +it never resizes, closes or rewrites line 1 by itself, and while typed line +1 never scrolls away (the live rows start two places before the current +one, so it sits under line 1). Zero hits is `0` in the tag. A preview made +later (line 1's word edited to a source that previews) takes rows from the +query pane's own bottom, so line 1 stays put; a reused pane gets its +preview at the key that asked. + +**Settings**: `SearchPlace attached|column`, `SearchPane reuse|new`, +`SearchRows N` (1-100). + +## Storyboards + +Text: `/` in the 1.2 MB stress file (playground `src/layout.zig` x23), +cursor on line 15000. + +| step | the screen | +|---|---| +| `/` | A `+Search` opens under layout.zig, taking 10 of its rows; line 1 reads `/`, the caret after it in insert mode; tag `^ +Search 0 Del`. Nothing else moves. | +| keystroke 1, `p` | Every `p` in the view tinted at once, the rest found a 4 ms slice a frame (the tag `1/38479+` until done); rail ticks fill in; the first `p` at or after the cursor selected in layout.zig (scrolled only if off screen). Rows: the lines holding `p`, each ` 15003 code`, from two before the current one, the current marked as the visited row, a note row above saying how many places come before them. | +| keystroke 2, `a` | `pa`: tints, ticks and rows narrow (`1/10189`); the current is again the first at or after where `/` was pressed, not after the last preview. The pane is the same size, line 1 where it was. | +| Ctrl-n / Ctrl-p | The next / previous `pa` current, selected in layout.zig; `2/10189`. | +| Enter | The keyboard on that `pa`, `pa` in `/`, the rows frozen (the whole list, 2000 rows), tag `+Search 2/10189 Save Unattach Del`; tints and ticks stay while the pane lives. Ctrl-o goes back to where `/` was pressed. | +| `n` | The next `pa` in layout.zig, `3/10189`, its row marked in the +Search. | +| `N` | Back to `2/10189`; from the first, round to the last with no message. | +| Esc (typing) | layout.zig's selection and scroll exactly as at `/`, tints and ticks gone, the +Search closed, its rows back to layout.zig. | + +Files: `SPC f f` from the playground's README.md, whose directory is the +playground's root (the snapshot `find.snap` runs the same steps). + +| step | the screen | +|---|---| +| `SPC f f` | The query pane under the pane with its +Preview under it, both out of that pane's rows; line 1 `Find `; the 15 files below the directory listed at once (rg `--files` on the worker; dot-files like `.fill-section.py` and .gitignore'd ones passed over), the first current; tag `1/15`. | +| keystroke 1, `l` | The names scored fuzzily (pick's scorer: segment starts, basename, camel humps), best first, the matched letters tinted: `src/layout.zig`, `src/locations.zig`, `open-all.sh`, `notes/helix-keys.md`, ...; the best current, its head in the +Preview; tag `1/7`. | +| keystroke 2, `a` | `la`: `src/layout.zig`, `src/locations.zig`; tag `1/2`, layout.zig's head in the preview. Nothing moves. | +| Ctrl-n / Ctrl-p | `src/locations.zig` current, its head in the preview. | +| Enter | The preview becomes `src/locations.zig`'s pane where it stands (same rect and serial); the list frozen above it. | +| `n` / `N` | In the query pane: the next / previous name current, shown in a new preview under it (or in its pane when open). In the opened file: helix's register search (a list of names has no places in a text). | +| Esc (typing) | The query pane and its preview closed, their rows back to the pane that asked; nothing opened. | + +Grep is Find's twin with rows under each file's name, run once the typing +pauses (80 ms), stopping at 2000 lines with `More` in the tag; hits in an +open file are that pane's places (n/N there). + +## Numbers + +Debug build (what the playground runs), 160x50, each step `update` + a full +render, machine load ~3. Unit tests `zz query timings` / `zz stream +timings` / `places: a big file...` (run with QUERY_TIMES / PLACES_TIMES). + +| what | cost | +|---|---| +| a cursor move and its frame, no search (baseline) | 0.70 ms | +| `/` opens | 1.05 ms | +| a keystroke of `/pane.v` (38 479 -> 276 places) | 3.0-3.5 ms | +| the ticks after it (7-11 of them, scan slice + rows every third) | worst 6.8-7.3 ms | +| an edit in the owner with the frozen pane open (insert `x` + a tick) | 8.3 ms mean, 10.9 worst | +| the same edit with no search | 7.5 ms | +| places' share of an edit on 1.9 MB (one-splice shift) | 0.44 ms | +| the declarations parse of the 1.2 MB file, on the worker | 474 ms, off the loop; worst frame meanwhile 7.5 ms | +| a keystroke once the rows are grouped under declarations | 4.4 ms | +| Grep race test: 2 engines x 12 rounds, a rogue thread pushing the stale generation | every round only B's lines land | + +So the search costs a keystroke ~2.5 ms over a plain frame and an edit +~0.8 ms, in Debug. Three fixes the numbers forced: `Text.primaryRange` +counted lines from the top for a selection's anchor on every call (18% of +a run; now through the line index, which also took the editor's own +insert-mode key on this file from 11.5 to 7.1 ms); live rows are a window +of 100 (the Debug SafeAllocator's stack capture per allocation was 30% at +1000 rows); the keystroke scans only the view. + +## What differs from CONVERGE, and why + +- **Declaration grouping is the worker's.** A tree-sitter parse of the + stress file is 4.8 s in Debug and the owner's "existing tree" exists only + with TreeContext on. The parse runs on the disk engine's worker with a + parser of its own (`syntax.declarationsApart`, cancellable through + tree-sitter's progress callback) and lands in the pane's + `context_declarations` (what sticky headers read); rows stay ungrouped + until then (live's trick). Without workers (tests) only texts under 64 KB + are parsed, on the loop. +- **Places shift on an edit** instead of being found again view-first: + `File.State.splice` records each edit's span, and the places before it + stay, those after move, only the touched lines are searched again. +- **Grep is literal** (smart case): rg's regex dialect is not mvzr's sam + rules (stream's call). `/` and All are regex. +- **All** follows the open panes (selection and scroll, put back on Esc) + rather than previewing a pane that is on screen anyway. +- **Terminals keep the band `/`**, as PDFs do: a terminal's text is no + `File`, and places need one. +- **A list's places feed every open file its rows land in**, not only the + owner (Refs in main.rs, asked from lib.rs: n/N in main.rs step them). +- **The live rows are a window**: 100 rows from two before the current + place; the whole list on Enter. +- A dumped query pane restores as a plain +Search, and a dumped finder + column as a plain column. + +## Rough + +- LookNext / LookPrev do not step query rows (their addresses are in row + metadata, not text). +- Grep rows carry no syntax colours; `/` rows are coloured where the + owner's highlights cover them (zeros elsewhere, so no fragment parse per + refill). +- Rail ticks are not carried over the detached wire (a detached frontend + shows tints, not ticks). +- In a window too short for the group (4 rows), only the query pane's tag + shows. +- The finder column keeps 8 query panes; older ones close. diff --git a/src/Finder.zig b/src/Finder.zig new file mode 100644 index 00000000..a2b8f89f --- /dev/null +++ b/src/Finder.zig @@ -0,0 +1,240 @@ +//! The finder column: where query panes go with `SearchPlace column`, the +//! alternative to attaching them under the pane that asked (lifted from +//! the column prototype, cut to its placement). A column with a role at +//! the right edge: the first search opens it and the other columns give it +//! its share once, each in proportion to its weight; after that no pane +//! outside it moves for a search. Its width is a share of the window, not a +//! column weight (layout.compute), so it opens and closes without rounding +//! anyone's width off. Its panes are a recency stack: the newest query pane +//! on top and open, the older ones folded to their tags. A pane opened +//! from a row goes to the column of the pane the query searches, never in +//! here. Its last pane gone, the column goes and every other is as wide as +//! before it came. The role is the column's serial. +const Finder = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const layout = @import("layout.zig"); +const config = @import("config.zig"); +const panes = @import("panes.zig"); +const Pardes = pardes.Pardes; + +/// The finder column's serial (layout.columnSerial); 0 while there is none. +serial: u32 = 0, +/// Its width, in thousandths of the window's: kept while it is closed, so +/// it comes back as wide as it went. +share: u16 = 300, + +/// More query panes than this and the oldest closes: each folded one keeps +/// a tag row. ponytail: a fixed count; size it from the column's rows. +pub const max_results = 8; + +const tag_text = "Finder Delcol"; + +/// The finder column's index, while it is there. +pub fn column(f: *const Finder, p: *const Pardes) ?usize { + if (f.serial == 0) return null; + return layout.columnBySerial(p, f.serial); +} + +/// Its width in cells: its share, leaving every other column MINW; the +/// whole window when it is the only column. +pub fn width(f: *const Finder, p: *const Pardes) u16 { + if (p.ncol <= 1) return p.screen_w; + const others: u32 = @as(u32, config.MINW) * @as(u32, @intCast(p.ncol - 1)); + const most: u32 = @as(u32, p.screen_w) -| others; + const wanted: u32 = @as(u32, p.screen_w) * f.share / 1000; + return @intCast(@min(@max(wanted, config.MINW), @max(most, @min(config.MINW, p.screen_w)))); +} + +/// Query pane `id` goes on top of the finder column, opened at the right +/// edge if there is none; the older ones fold. False when the window has +/// no room for the column (the caller attaches it instead). +pub fn place(f: *Finder, p: *Pardes, id: usize) bool { + const pane = p.panes[id] orelse return false; + const c = f.column(p) orelse f.open(p) orelse return false; + layout.insert(p, c, 0, id); + pane.vweight = 1; + pane.collapsed = false; + f.fold(p, c, id); + // The oldest goes once there are too many: the bottom one, as the top + // is always the newest. + while (p.col_n[c] > max_results) { + const oldest = p.col_panes[c][p.col_n[c] - 1]; + p.removePane(oldest, null) catch break; + } + return true; +} + +/// A finder column at the right edge, empty, its tag its own: the other +/// columns give it its share, each in proportion to its weight. Null when +/// the window has no room for one more column, or narrower columns would +/// leave a pane under its tag and 2 rows. +fn open(f: *Finder, p: *Pardes) ?usize { + if (p.ncol >= pardes.MAX_COLS or p.ncol == 0) return null; + if (p.screen_w < @as(u32, config.MINW) * @as(u32, @intCast(p.ncol + 1))) return null; + const c = p.ncol; + p.col_n[c] = 0; + // Not used for its width (layout.compute), only kept positive for the + // code that halves and joins weights. + p.col_weight[c] = layout.column_weight_unit; + p.col_tags[c] = .{ .what = .column, .gpa = p.gpa }; + p.col_tags[c].own = p.gpa.dupe(u8, tag_text) catch null; + p.col_serial[c] = 0; + p.ncol += 1; + f.serial = layout.columnSerial(p, c); + // A narrower column wraps long tags onto more rows: shared out again, + // and where that cannot hold every minimum there is no finder, as + // Newcol is refused. + layout.compute(p); + for (0..p.ncol) |k| if (k != c and !layout.columnAtMinimums(p, k) and !layout.shareColumn(p, k)) { + layout.dropColumnUnannounced(p, c); + f.serial = 0; + layout.compute(p); + return null; + }; + layout.noteColumn(p, "newcol", f.serial); + return c; +} + +/// Fold every pane of finder column `c` but `top` (and what is attached +/// to it, its +Preview) to its tag. +fn fold(f: *const Finder, p: *Pardes, c: usize, top: usize) void { + _ = f; + layout.compute(p); + for (p.col_panes[c][0..p.col_n[c]]) |k| { + const pane = p.panes[k] orelse continue; + if (k == top or layout.groupRoot(p, k) == top) { + pane.collapsed = false; + pane.vweight = 1; + } else if (!pane.collapsed) { + // As Collapse folds it: its weight keeps its height for later. + pane.vweight = @floatFromInt(@max(1, p.rects[k].h)); + pane.collapsed = true; + } + } + layout.compute(p); +} + +/// Query pane `id`, asked again: back on top of the stack, open, the rest +/// folded. Nothing outside the finder column moves. +pub fn raise(f: *Finder, p: *Pardes, id: usize) void { + const c = f.column(p) orelse return; + const at = layout.findPane(p, id) orelse return; + if (at.col != c) return; + if (at.idx != 0) { + // the pane and what is attached to it (its +Preview) move together + const end = layout.groupEnd(p, c, at.idx); + var moved: [pardes.MAX_PANES]usize = undefined; + const n = end - at.idx; + @memcpy(moved[0..n], p.col_panes[c][at.idx..end]); + for (moved[0..n]) |k| layout.removePane(p, k); + for (moved[0..n], 0..) |k, i| layout.insert(p, c, i, k); + } + f.fold(p, c, id); +} + +/// The column a pane asked for from the finder goes in (a row looked at, a +/// command run there): the column of the pane its query searches, else +/// the nearest other. Null when nothing points at the finder. +pub fn away(f: *Finder, p: *Pardes, from: usize, kind: pardes.exec.NewPane) ?usize { + const fc = f.column(p) orelse return null; + const in_finder = if (layout.findPane(p, from)) |at| at.col == fc else false; + const to_last = (kind == .command or kind == .errors) and fc == p.ncol - 1; + if (!in_finder and p.exec_column != fc and !to_last) return null; + if (in_finder) { + const root = layout.groupRoot(p, from); + if (p.panes[root]) |qp| if (qp.query) |q| if (p.paneBySerial(q.owner)) |oid| if (layout.findPane(p, oid)) |at| + if (at.col != fc) return at.col; + } + if (fc > 0) return fc - 1; + if (fc + 1 < p.ncol) return fc + 1; + // The finder is the only column: a document asked from it gets one of + // its own, left of it. + return layout.insertColumn(p, fc, true); +} + +/// The finder column has lost its last pane: it goes, and every other +/// column is as wide as before it came. +pub fn emptied(f: *Finder, p: *Pardes, c: usize) bool { + if (f.column(p) != c or p.col_n[c] != 0) return false; + layout.dropColumn(p, c); + f.serial = 0; + return true; +} + +/// A drag of the border between the finder column and column `other` +/// beside it: the finder's share follows the edge, and `other` takes the +/// difference, every other column keeping its width. +pub fn dragWidth(f: *Finder, p: *Pardes, other: usize, finder_w: u64) void { + const fc = f.column(p) orelse return; + if (p.screen_w == 0) return; + const combined: u64 = p.col_w[fc] + p.col_w[other]; + if (combined < 2 * @as(u64, config.MINW)) return; + const fw = std.math.clamp(finder_w, config.MINW, combined - config.MINW); + f.share = @intCast(@max(1, @min(999, fw * 1000 / p.screen_w))); + var rest_weight: u128 = 0; + var rest_cells: u64 = 0; + for (0..p.ncol) |k| if (k != fc and k != other) { + rest_weight += p.col_weight[k]; + rest_cells += p.col_w[k]; + }; + if (rest_cells > 0) { + const other_cells = combined - fw; + const w = @as(u128, other_cells) * rest_weight / rest_cells; + p.col_weight[other] = @intCast(std.math.clamp(w, 1, layout.max_column_weight)); + } + layout.compute(p); +} + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +test "SearchPlace column: query panes stack in a finder column at the right edge, nothing else moves after it opens, and it goes with its last pane" { + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); + defer p.deinit(); + p.settings.search_place = .column; + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\n"); + p.newScratchBelow(0); + const other = p.active; + p.active = 0; + layout.compute(p); + const before = p.rects; + const width_before = p.col_w[0]; + typeKeys(p, "/"); + const fc = p.finder.column(p).?; + try std.testing.expectEqual(@as(usize, 1), fc); + const first = p.col_panes[fc][0]; + try std.testing.expect(p.panes[first].?.query != null); + // the first search narrows the column once; its panes keep their rows + try std.testing.expect(p.col_w[0] < width_before); + try std.testing.expectEqual(before[0].h, p.rects[0].h); + try std.testing.expectEqual(before[other].h, p.rects[other].h); + typeKeys(p, "alpha"); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(pane.places.started); + layout.compute(p); + const opened = p.rects; + // a second search, from the other pane: on top, the first folded + p.active = other; + typeKeys(p, "/"); + const second = p.col_panes[fc][0]; + try std.testing.expect(second != first); + try std.testing.expect(p.panes[first].?.collapsed); + layout.compute(p); + try std.testing.expectEqualDeep(opened[0], p.rects[0]); + try std.testing.expectEqualDeep(opened[other], p.rects[other]); + // Esc: the second closes, the first stays + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[second] == null); + try std.testing.expectEqual(fc, p.finder.column(p).?); + // the first's Del: the column goes, every other as wide as before it + pardes.exec.runBuiltin(p, .Del, first, "", null); + try std.testing.expect(p.finder.column(p) == null); + layout.compute(p); + try std.testing.expectEqual(width_before, p.col_w[0]); + try std.testing.expectEqualDeep(before[0], p.rects[0]); +} diff --git a/src/Query.zig b/src/Query.zig index 3a75a7f5..6374ce42 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -257,6 +257,7 @@ pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: boo const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return; File.setContent(p, f, new); q.reset(p); + if (p.finder.column(p)) |fc| if (layout.findPane(p, id)) |at| if (at.col == fc) p.finder.raise(p, id); if (rp.collapsed) layout.toggleCollapse(p, id); // A source that previews gets its +Preview now, at the key that // asked, not under the typing later. @@ -318,8 +319,11 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize } } if (p.settings.search_place == .column) { - // The finder column (phase 6): until it exists, under the owner. - if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + // On top of the finder column at the right edge (Finder.zig), the + // older query panes folded under it; its preview under it there. + if (!p.finder.place(p, free) and !layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + if (with_preview) _ = makePreview(p, free, p.rects[free].h / 2, free); + return free; } else if (!layout.attach(p, owner_id, free, want)) { // An owner too short to give a query pane its rows: placed as any // new pane is, the one place a search moves another pane. @@ -1727,8 +1731,11 @@ pub fn cancel(p: *Pardes, id: usize) void { if (owner_id) |oid| p.active = oid; return; } + // Attached, its rows go back to its owner; in the finder column, to its + // own column's. + const attached = layout.ownerOf(p, id) != null; if (owner_id) |oid| { - p.removePane(id, oid) catch {}; + p.removePane(id, if (attached) oid else null) catch {}; p.active = oid; if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); } else p.removePane(id, null) catch {}; @@ -1772,7 +1779,9 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { const q = rp.query orelse return false; if (rp.focus != .body) return false; const t = &rp.body; - if (q.frozen) return false; + // Normal mode, live or frozen: n and N step the rows (the current one + // shown where it points, the keyboard staying), Enter on a hit row lands + // on it, as Enter typing does. if (t.mode == .normal) { if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; if (k.cp == 'n' or k.cp == 'N') { @@ -1780,11 +1789,14 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { return true; } if (hit(k, config.look_key) and t.cur_row > 0) { - land(p, id, @intCast(t.cur_row - 1)); + const i: usize = @intCast(t.cur_row - 1); + if (i >= q.items.items.len or q.items.items[i].kind != .hit) return false; + land(p, id, i); return true; } return false; } + if (q.frozen) return false; if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false; if (hit(k, config.escape)) { cancel(p, id); @@ -2003,6 +2015,11 @@ test "a / query: Enter lands and freezes, the register filled, n and N step sile defer std.testing.allocator.free(frozen); // the rows: one a line (gamma alpha has one), a gutter number each try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); + // B3 on a row's line number is its address; on its code, no address + var abuf: [256]u8 = undefined; + const addr = rowAddress(qp, 1, 2, &abuf).?; + try std.testing.expect(std.mem.endsWith(u8, addr, ":1:1")); + try std.testing.expect(rowAddress(qp, 1, qp.file.?.location_rows[1].code_start + 1, &abuf) == null); // n and N in the owner step the same set, round the end silently const logged = p.messages.len; try std.testing.expectEqual(@as(?usize, 0), pane.places.current); diff --git a/src/exec.zig b/src/exec.zig index 2bc1a3e5..142dfef6 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -1197,6 +1197,14 @@ pub fn placeNew(p: *Pardes, from: usize, origin: ?usize, id: usize, kind: NewPan // No column left (the last one Delcol'd): a pane made from the workspace // tag opens one to go in. _ = layout.firstColumn(p); + // Anything asked from the finder column (a row looked at, a command + // there) goes where its query came from, never into the finder; and + // the rules that take the last column take the last that is not it. + const exec_column = p.exec_column; + defer p.exec_column = exec_column; + const away = p.finder.away(p, from, kind); + if (away) |c| p.exec_column = c; + const finder_column = p.finder.column(p); const asked = if (p.exec_column != null) null else origin; layout.compute(p); const before = p.rects; @@ -1206,9 +1214,10 @@ pub fn placeNew(p: *Pardes, from: usize, origin: ?usize, id: usize, kind: NewPan // (look.c:921-923, et->col). .scratch => layout.acmePlace(p, p.exec_column orelse columnOf(p, from), null, id), // +Errors, a command's output: the last column (util.c:94-98); - // a command run from a column's tag, that column. + // a command run from a column's tag, that column. The finder's + // is never the last column for them. .command => layout.acmePlace(p, p.exec_column orelse p.ncol - 1, null, id), - .errors => layout.acmePlace(p, p.ncol - 1, null, id), + .errors => layout.acmePlace(p, away orelse p.ncol - 1, null, id), // makenewwindow(nil) for 9P's new (acme.c:877), else (t). .fs => layout.acmePlace(p, acmeColumn(p, from), null, id), .shell, .doc => layout.acmePlace(p, acmeColumn(p, from), asked, id), @@ -1238,7 +1247,7 @@ pub fn placeNew(p: *Pardes, from: usize, origin: ?usize, id: usize, kind: NewPan var c = p.ncol; while (c > 0) { c -= 1; - if (c == f.col) continue; + if (c == f.col or c == finder_column) continue; for (p.col_panes[c][0..p.col_n[c]]) |k| p.rects[k] = before[k]; layout.snapColWeights(p, c); if (p.col_n[c] == 0) { diff --git a/src/layout.zig b/src/layout.zig index dac0aa7e..8739122c 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -166,6 +166,11 @@ pub fn columnDrop(p: *const Pardes, source: usize, x: u16, grab: u16) ColumnDrop pub fn setColumnPairWidth(p: *Pardes, left: usize, left_width: u64) void { if (left + 1 >= p.ncol) return; const combined: u64 = p.col_w[left] + p.col_w[left + 1]; + // The finder's edge sets its share (Finder.dragWidth). + if (p.finder.column(p)) |fc| { + if (fc == left + 1) return p.finder.dragWidth(p, left, combined -| left_width); + if (fc == left) return p.finder.dragWidth(p, left + 1, left_width); + } // Too narrow for both to keep MINW: any split would squeeze one away. if (combined < 2 * @as(u64, config.MINW)) return; const width = std.math.clamp(left_width, config.MINW, @max(@as(u64, config.MINW), combined -| config.MINW)); @@ -467,7 +472,12 @@ pub fn dropColumn(p: *Pardes, c: usize) void { pub fn dropColumnUnannounced(p: *Pardes, c: usize) void { std.debug.assert(p.col_n[c] == 0); tagline.exitHeader(p); - if (p.ncol > 1) p.col_weight[if (c > 0) c - 1 else c + 1] +|= p.col_weight[c]; + // The finder's width was its share, no weight: nobody gets one, so the + // others are as wide as before it came. A column whose weight would go + // to the finder gives it to the column on the finder's other side. + const finder = p.finder.column(p); + const heir: ?usize = if (p.ncol <= 1 or finder == c) null else if (c > 0 and finder != c - 1) c - 1 else if (c + 1 < p.ncol and finder != c + 1) c + 1 else if (c > 1) c - 2 else if (c + 2 < p.ncol) c + 2 else null; + if (heir) |h| p.col_weight[h] +|= p.col_weight[c]; p.col_tags[c].deinit(p.gpa); var j = c; while (j + 1 < p.ncol) : (j += 1) { @@ -1187,20 +1197,32 @@ pub fn compute(p: *Pardes) void { if (p.ncol == 0) return; keepGroups(p); for (0..p.ncol) |column| _ = columnSerial(p, column); + // The finder column is as wide as its share says (Finder.width), not + // by weight: the others share what it leaves by theirs, so it comes + // and goes and each of them keeps its proportion, none rounded off. + const finder = p.finder.column(p); + const finder_w: u16 = if (finder != null) p.finder.width(p) else 0; + const rest = p.screen_w -| finder_w; var wsum: u128 = 0; - for (0..p.ncol) |c| wsum += p.col_weight[c]; + var last_plain: usize = p.ncol; + for (0..p.ncol) |c| if (finder != c) { + wsum += p.col_weight[c]; + last_plain = c; + }; if (wsum == 0) wsum = 1; // Round cumulative boundaries so widths still sum to the available screen. var prefix: u128 = 0; + var offset: u16 = 0; for (0..p.ncol) |c| { - const last = c + 1 == p.ncol; - const x = columnBoundary(p.screen_w, prefix, wsum); - prefix += p.col_weight[c]; - const end: u16 = if (last) - p.screen_w - else - columnBoundary(p.screen_w, prefix, wsum); + const x = offset + columnBoundary(rest, prefix, wsum); + const end: u16 = if (finder == c) end: { + offset = finder_w; + break :end x + finder_w; + } else end: { + prefix += p.col_weight[c]; + break :end if (c == last_plain) offset + rest else offset + columnBoundary(rest, prefix, wsum); + }; const cw = end -| x; p.col_x[c] = x; p.col_w[c] = cw; diff --git a/src/pardes.zig b/src/pardes.zig index 3ccfee5f..6f30d6ca 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -26,6 +26,7 @@ pub const Registers = @import("Registers.zig"); pub const Macro = @import("Macro.zig"); pub const Pipe = @import("Pipe.zig"); pub const Stream = @import("Stream.zig"); +pub const Finder = @import("Finder.zig"); pub const colors = @import("colors.zig"); pub const Theme = colors.Theme; pub const themes = colors.themes; @@ -490,6 +491,7 @@ test { _ = @import("Query.zig"); _ = @import("Names.zig"); _ = @import("Stream.zig"); + _ = @import("Finder.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4386,6 +4388,9 @@ pub const Pardes = struct { col_tags: [MAX_COLS]Text = @splat(.{ .what = .column }), col_serial: [MAX_COLS]u32 = @splat(0), next_column_serial: u32 = 1, + /// The finder column, where query panes stack with SearchPlace column + /// (Finder.zig). + finder: Finder = .{}, global_tag: Text = .{ .what = .workspace }, // derived each sync rects: [MAX_PANES]Rect = @splat(.{}), @@ -5225,14 +5230,19 @@ pub const Pardes = struct { pub fn newColumn(p: *Pardes, from_id: usize) void { // An empty window (Delcol took the last column): its first column. if (layout.firstColumn(p)) |c| return tagline.enterHeader(p, c); - const col = p.keyboardColumn(from_id) orelse return; + const keyboard_col = p.keyboardColumn(from_id) orelse return; + // Asked from the finder: the new column goes left of it, so the + // finder stays at the edge as wide. + const in_finder = p.finder.column(p) == keyboard_col; + const before_finder = in_finder and keyboard_col == 0; + const col = if (in_finder and keyboard_col > 0) keyboard_col - 1 else keyboard_col; // A trial: laying it out gives it a serial (layout.compute), which a // refusal takes back. Every other column has its own already, so // the counter as it is now is the trial's to return to. for (0..p.ncol) |k| _ = layout.columnSerial(p, k); const unspent = p.next_column_serial; // Said, not silently nothing: "no space" is 9ns's word for ENOSPC. - const c = layout.insertColumnUnannounced(p, col, false) orelse { + const c = layout.insertColumnUnannounced(p, col, before_finder) orelse { var said: [96]u8 = undefined; return p.reportFailure(from_id, if (p.ncol >= MAX_COLS) std.fmt.bufPrint(&said, "Newcol: no space for a column: {d} max", .{MAX_COLS}) catch "Newcol: no space for a column" @@ -7224,9 +7234,11 @@ pub const Pardes = struct { const beside = if (emptied) |c| p.besideColumn(c, p.rects[id]) else null; layout.removePane(p, id); p.panes[id] = null; + // The finder's last pane takes the column with it. + const finder_gone = if (emptied) |c| p.finder.emptied(p, c) else false; if (p.active != id) return; p.active = gainer orelse beside orelse p.anyPane() orelse return p.quitEmpty(); - if (emptied) |c| if (!p.header_focus) tagline.enterHeader(p, c); + if (emptied) |c| if (!finder_gone and !p.header_focus) tagline.enterHeader(p, c); } /// Delcol: close column `col` and every pane in it. -- cgit v1.3 From f3b5bd10ceb4c4db7263739770d5e4bdb879ba75 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:16:32 -0300 Subject: Search converge 7/6: a script's Grep or Find that misses opens nothing, a dumped query pane restores as plain text; fs.py's Recent and canary to the query pane --- src/File.zig | 5 ++++- src/Query.zig | 18 ++++++++++++++++++ src/builtins.zig | 18 +++++++++++------- src/ninep/ctl.zig | 9 +++++++++ test/fs.py | 13 ++++++++----- 5 files changed, 50 insertions(+), 13 deletions(-) (limited to 'src/Query.zig') diff --git a/src/File.zig b/src/File.zig index f633cad0..24dc9318 100644 --- a/src/File.zig +++ b/src/File.zig @@ -244,7 +244,10 @@ pub fn dumpPane( .collapsed = pane.collapsed, .file = .{ .tree_context = file.tree_context, - .location_rows = try dumpLocationRows(arena, file.location_rows), + // A query pane's rows are its own (line 1 the query, gutter + // numbers), not location rows Restore reads: it comes back as + // plain text. + .location_rows = if (pane.query != null) &.{} else try dumpLocationRows(arena, file.location_rows), .path = file.path, .content_b64 = if (from_disk) "" else try dump.encodeBytes(arena, file.content), .dirty = dirty, diff --git a/src/Query.zig b/src/Query.zig index 6374ce42..a871b71e 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -1998,6 +1998,24 @@ test "a / query: keystroke by keystroke, the owner shows the set, rows from its try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); } +test "a dump holding a query pane, live or frozen, restores, the pane as plain text" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("alpha one\nbeta\nalphabet\n"); + typeKeys(p, "/alpha"); + for (0..2) |_| { + const qid = queryPane(p).?; + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?); + defer restored.deinit(); + const back = restored.panes[qid].?; + try std.testing.expect(back.query == null); + try std.testing.expectEqual(@as(usize, 0), back.file.?.location_rows.len); + try std.testing.expect(std.mem.startsWith(u8, back.file.?.content, "/alpha\n")); + p.update(.{ .key = .{ .cp = Key.enter } }); + } +} + test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); diff --git a/src/builtins.zig b/src/builtins.zig index cda962de..d2f215d7 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1720,8 +1720,9 @@ pub const Find = struct { // (SPC f f) typed into; with a word (B2, a script) listed, the // keyboard left where it was, a script told of a miss. const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const had = panes.Query.ofOwner(c.p, c.pane.serial) != null; panes.Query.open(c.p, c.id, .find, pat, pat.len == 0); - if (pat.len > 0) missed(c, e_search_miss_find); + if (pat.len > 0) missed(c, e_search_miss_find, had); } }; @@ -1733,19 +1734,22 @@ pub const Grep = struct { pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const had = panes.Query.ofOwner(c.p, c.pane.serial) != null; panes.Query.open(c.p, c.id, .grep, pat, pat.len == 0); - if (pat.len > 0) missed(c, e_search_miss_grep); + if (pat.len > 0) missed(c, e_search_miss_grep, had); } }; /// A script's Find or Grep (a 9P write runs it to its end before it -/// answers) that found nothing fails as one: the query pane stays, its -/// count 0, and the write hears `not found`. -fn missed(c: Ctx, text: []const u8) void { +/// answers) that found nothing fails as one, opening nothing: a query pane +/// it made goes as an Esc takes it, one it reused stays, its count 0; the +/// write hears `not found`. +fn missed(c: Ctx, text: []const u8, reused: bool) void { if (!c.p.fs.serving) return; const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return; - const q = c.p.panes[qid].?.query.?; - if (q.total == 0) c.p.reportFailure(c.id, text); + if (c.p.panes[qid].?.query.?.total != 0) return; + if (!reused) panes.Query.cancel(c.p, qid); + c.p.reportFailure(c.id, text); } /// Search in a query pane under this pane, line 1 the argument (`Panes`, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 635e03a6..258ea1ee 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -3069,6 +3069,15 @@ test "a script's Grep and Find fill the pane's one query pane, a row a line unde var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); + // With no query pane under it, a miss leaves none: the one it made goes. + _ = wr(p, Node.of(found.serial, .ctl), "Del\n"); + var closed: usize = 0; + for (p.panes) |slot| closed += @intFromBool(slot != null); + try testing.expectEqual(E.NOENT, wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n").errno()); + var left: usize = 0; + for (p.panes) |slot| left += @intFromBool(slot != null); + try testing.expectEqual(closed, left); + try testing.expect(panes.Query.ofOwner(p, serialOf(p)) == null); } test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { diff --git a/test/fs.py b/test/fs.py index 97af9e6b..841dd32a 100644 --- a/test/fs.py +++ b/test/fs.py @@ -715,10 +715,13 @@ def recent_survives_restart(binary): with session(binary, root, 'recent2') as (client, _): listed = client.read('/recent').decode() assert f'closed {kept}\n' in listed, listed - # Recent shows it, and a look at its row opens it again. + # Recent fills a query pane with it, its row relative to the + # pane's directory, and a look at the row opens it again. client.write('/pane/1/exec', b'Recent\n') rows = int(client.read('/pane/1/exec').split()[-1]) - row = next(r for r in client.read(f'/pane/{rows}/body').decode().splitlines() if r.startswith(f'{kept}:')) + body = client.read(f'/pane/{rows}/body').decode() + assert body.startswith('Recent '), body + row = next(r for r in body.splitlines() if r.startswith('kept.txt:')) client.write(f'/pane/{rows}/look', (row.split(' ')[0] + '\n').encode()) assert f'open {kept}\n' in client.read('/recent').decode() @@ -759,11 +762,11 @@ def workflow_canary(binary): assert client.read(f'/pane/{a}/body') == b'alpha one\nshared word\n' assert f'new {a} {root}/a.txt\n' in log() and f'new {b} {root}/b.txt\n' in log() - # Grep and Find: a hit opens its +Search, rows and all; a miss - # fails ENOENT, opening nothing. + # Grep and Find: a hit fills its query pane, line 1 the query and + # the lines under each file's name; a miss fails ENOENT. grep = made_by(a, b'Grep shared\n') rows = client.read(f'/pane/{grep}/body').decode() - assert 'a.txt:2' in rows and 'b.txt:2' in rows, rows + assert rows == 'Grep shared\na.txt\n 2 shared word\nb.txt\n 2 shared word\n', rows client.remove(f'/pane/{grep}') execute_refused(client, a, 'Grep zzqqnomatch', 'Grep: text not found') found = made_by(a, b'Find b.txt\n') -- cgit v1.3 From f3405aaef8db79094b2741a9caaeaa5328ab6288 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:47:11 -0300 Subject: Store 2/3: one bounded store every window shares (Store.zig): Recent as records read on use, the panes a session closes kept as one-pane dumps; Panes lists them (closed), Enter or a look at @pN brings one back beside the pane that took its rows An append-only log under $XDG_STATE_HOME/pardes/store, framed records with a CRC, flock on store.lock (never blocking a step), a stat on use, garbage passed over and compacted away by the next writer, compaction by rename, 100 MiB cap. dump.dumpPane/restorePane lifted out of dumpState/initDump; layout.giveBack; Options.recent_path is store_path. Host calls yield one at a time; /recent refreshes only when no step is out. Tests: two windows and a busy lock, the cap, garbage/torn/partial records, a closed pane's reopen with the layout invariant; fs.py: two live sessions over 9P. --- src/Query.zig | 57 ++- src/Store.zig | 1193 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/dump.zig | 216 +++++----- src/layout.zig | 26 ++ src/look.zig | 8 +- src/main.zig | 13 +- src/ninep/tree.zig | 4 + src/pardes.zig | 49 +-- src/recent.zig | 99 ++++- test/fs.py | 42 +- 10 files changed, 1541 insertions(+), 166 deletions(-) create mode 100644 src/Store.zig (limited to 'src/Query.zig') diff --git a/src/Query.zig b/src/Query.zig index a871b71e..98419c7b 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -580,6 +580,8 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz if (p.fs.serving) Stream.step(p); }, .recent => { + // Every window's files: what the others wrote since, read. + p.store.refresh(p); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); Output.recentText(p, &out.writer, true) catch {}; @@ -591,15 +593,29 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; } }, - .panes => for (p.panes) |slot| { - const other = slot orelse continue; - if (other == rp or other.query != null) continue; - var buf: [4096 + 32]u8 = undefined; - const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); - const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; - const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; - const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; - q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + .panes => { + for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + } + // Then the panes this session closed, the latest first, each + // `(closed)` and dimmer (makeNameRows): Enter brings one back + // where it was. Its name alone is matched, not the word. + var i = p.store.closed.items.len; + while (i > 0) : (i -= 1) { + const c = p.store.closed.items[i - 1]; + var buf: [4096 + 48]u8 = undefined; + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}" ++ closed_word, .{ c.serial, Names.relative(c.name, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const key_len = row.len - closed_word.len - key_at; + q.names.add(gpa, row, key_at, key_len, Names.baseOf(row[key_at..][0..key_len]), c.serial) catch break; + } }, .symbols => { const oid = owner_id orelse return; @@ -622,6 +638,9 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz } } +/// What a Panes row of a closed pane ends with. +const closed_word = " (closed)"; + /// The owner's declarations, from a parse that already exists: its sticky /// headers' (TreeContext) at this revision, or the locations cache's. None /// is made here, on the loop, unless `small` and the text is small: a @@ -1020,13 +1039,21 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { } try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); try writeRow(p, &out, &rows, row, meta); + // A closed pane's row is dimmer, the gutter's colour, between its + // marks (spans are walked in order, never overlapping). + const dim = q.source == .panes and p.paneBySerial(cand.ref) == null; + const dimmed: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.lineno } }; + var gap: usize = 0; var k: usize = 0; while (k < nmarks) { var e = k + 1; while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + if (dim and marks[k] > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + marks[k]), .style = dimmed }); try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + gap = marks[e - 1] + 1; k = e; } + if (dim and row.len > gap) try spans.append(p.gpa, .{ .start = @intCast(at + gap), .end = @intCast(at + row.len), .style = dimmed }); } if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); @@ -1636,9 +1663,15 @@ pub fn land(p: *Pardes, id: usize, row: ?usize) void { look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); return; }, - .panes => if (p.paneBySerial(it.ref)) |tid| { - p.active = tid; - if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + .panes => { + if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + } + // A pane this session closed: back where it was, from the + // pane that asked (the owner, not this one, which may go). + _ = p.store.reopen(p, it.ref, owner_id orelse id); return; }, else => {}, diff --git a/src/Store.zig b/src/Store.zig new file mode 100644 index 00000000..35033e04 --- /dev/null +++ b/src/Store.zig @@ -0,0 +1,1193 @@ +//! The store: the state every pardes window shares, one bounded file under +//! $XDG_STATE_HOME/pardes (Options.store_path), an append-only log of +//! framed records, `@ \n\n`: the files opened +//! lately (Recent, recent.zig) and the panes each session closed, each a +//! one-pane Dump, which Panes brings back where it was. docs/next-store.md +//! argues the format and the sharing; in short: +//! +//! - A writer takes `flock` on `store.lock` (never blocking a frame: busy, +//! its records wait for the next step), reads what others appended since +//! it last read, and appends its own with one write at the end. +//! - A reader takes no lock: on use, one stat of the path; longer, it reads +//! the tail; another inode (a compaction), all of it again. +//! - A record running past the end is being written: read next time. One +//! that is garbage is passed over to the next valid one, and the next +//! writer compacts. A missing, foreign or garbage file is an empty store: +//! pardes always starts. +//! - Compaction (under the lock): the live records, the closed panes of +//! sessions still running, into `store.new`, renamed over the store. The +//! file never passes `max_bytes`. +//! +//! With no path (no home, the web, a test that gives none) nothing is +//! kept past the session, and a closed pane's dump is held here instead. +const Store = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const dump = @import("dump.zig"); +const layout = @import("layout.zig"); +const exec = @import("exec.zig"); +const recent = @import("recent.zig"); +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; + +/// The file is never longer: an append that would pass it compacts first, +/// and a compaction keeps the newest live records within half of it. +pub const max_bytes: u64 = 100 << 20; +/// A closed pane's record is never longer: a terminal's that would be is +/// kept without its history, any other pane's is not kept. +pub const max_record: usize = 8 << 20; +/// A session keeps this many closed panes, the newest. +pub const max_closed = 64; +/// The first record's body, its version; then a generation, new at each +/// compaction, so an inode number used again is no other file read on. +const magic = "pardes-store 1"; +/// A header line `@k \n` is never longer. +const max_head = 32; +/// A closed pane's first line, its place and name, is never longer. +const max_meta = 4096 + 128; + +/// A pane closed in this session, as Panes lists it and brings it back. +pub const Closed = struct { + serial: u32, + /// The column it was in, by serial. + column: u32, + /// The pane its rows went to, by serial, and whether it was below it: + /// brought back, it takes them from that pane alone. + gainer: u32, + below: bool, + /// The pane it was attached to, by serial (0 none). + owner: u32, + rows: u16, + /// What its Panes row shows: its file, command or directory (gpa). + name: []u8, + /// Its record's offset in the file read as `inode`. + at: u64 = 0, + /// Its record's body while it is in no file (not written yet, or no + /// file to write it to); empty once written. + body: []u8 = &.{}, + /// Where its record is in `pending`, until that is written. + pending_at: ?usize = null, +}; + +/// The store file; null, nothing is kept past the session. +path: ?[]const u8 = null, +/// Its bound: `max_bytes`, less in a test. +cap: u64 = max_bytes, +/// This session's, on its closed panes' records. +session: u64 = 0, +pid: i32 = 0, +/// The file as read so far: its inode, generation and how far. +inode: std.Io.File.INode = 0, +gen: u64 = 0, +end: u64 = 0, +/// Its length when first read whole: a file past twice that (and 1 MiB) +/// is compacted. +base: u64 = 0, +/// A record that is not one was passed over: the next writer compacts. +garbage: bool = false, +/// Read once at start (or there was none): only then is anything written, +/// so a session never writes over a store it did not read. +loaded: bool = false, +/// Framed records waiting for the lock. +pending: std.ArrayList(u8) = .empty, +/// This session's closed panes, oldest first. +closed: std.ArrayList(Closed) = .empty, + +fn clockNs() i128 { + var ts: std.c.timespec = .{ .sec = 0, .nsec = 0 }; + _ = std.c.clock_gettime(.REALTIME, &ts); + return @as(i128, ts.sec) * std.time.ns_per_s + ts.nsec; +} + +fn ioOf() std.Io { + return std.Io.Threaded.global_single_threaded.io(); +} + +/// One host file call, `f(args)`, made out of the turn (pardes.turn): a +/// store under a mount of this session's own tree is answered by this +/// session. Only the call: while a step is out nothing may change the core, +/// so the store and Recent change between these, never inside one. +fn host(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { + pardes.turn.yield(); + defer pardes.turn.back(); + return @call(.auto, f, args); +} + +const cwd = std.Io.Dir.cwd; +const File = std.Io.File; +const Dir = std.Io.Dir; + +/// A new session's store at `path`: its id from the pid and the clock. +pub fn init(path: ?[]const u8) Store { + var s: Store = .{ .path = path }; + if (comptime pardes.hosted) { + s.pid = std.c.getpid(); + const now = clockNs(); + s.session = std.hash.Wyhash.hash(@intCast(s.pid), std.mem.asBytes(&now)); + } else s.session = 1; + return s; +} + +pub fn deinit(s: *Store, gpa: std.mem.Allocator) void { + for (s.closed.items) |c| freeClosed(gpa, c); + s.closed.deinit(gpa); + s.pending.deinit(gpa); +} + +fn freeClosed(gpa: std.mem.Allocator, c: Closed) void { + gpa.free(c.name); + gpa.free(c.body); +} + +/// A copy for the session a Restore makes: the same session (the same +/// process), its closed panes still its own. What is pending is the old +/// session's to write (its deinit does); the copies hold their bodies +/// until they are read back from the file. +pub fn clone(s: *const Store, gpa: std.mem.Allocator) Store { + var copy = s.*; + copy.pending = .empty; + copy.closed = .empty; + for (s.closed.items) |c| { + const name = gpa.dupe(u8, c.name) catch break; + const body = gpa.dupe(u8, c.body) catch { + gpa.free(name); + break; + }; + var kept = c; + kept.name = name; + kept.body = body; + kept.pending_at = null; + copy.closed.append(gpa, kept) catch { + freeClosed(gpa, kept); + break; + }; + } + return copy; +} + +// ---- reading ---- + +/// A window of the file, read ahead: records are parsed from it, and a +/// body that is skipped is never read. +const Reader = struct { + file: std.Io.File, + io: std.Io, + size: u64, + buf: []u8, + at: u64 = 0, + len: usize = 0, + + /// Bytes `[from, from + n)`, `n` at most the window; null past the end. + fn bytes(r: *Reader, from: u64, n: usize) ?[]const u8 { + if (n > r.buf.len or from + n > r.size) return null; + if (from < r.at or from + n > r.at + r.len) { + r.len = host(File.readPositionalAll, .{ r.file, r.io, r.buf, from }) catch return null; + r.at = from; + if (n > r.len) return null; + } + const o: usize = @intCast(from - r.at); + return r.buf[o..][0..n]; + } +}; + +const Rec = struct { + kind: u8, + at: u64, + body: u64, + len: usize, + crc: u32, + + fn end(rec: Rec) u64 { + return rec.body + rec.len + 1; + } +}; + +const Next = union(enum) { rec: Rec, partial, bad }; + +/// The record at `at`: whole, still being written (`partial`: its length +/// runs past the end), or not a record. +fn next(r: *Reader, at: u64) Next { + if (at >= r.size) return .partial; + const head = r.bytes(at, @intCast(@min(max_head, r.size - at))) orelse return .partial; + const nl = std.mem.indexOfScalar(u8, head, '\n') orelse return if (head.len < max_head) .partial else .bad; + const line = head[0..nl]; + if (line.len < 5 or line[0] != '@' or line[2] != ' ') return .bad; + var fields = std.mem.splitScalar(u8, line[3..], ' '); + const len = std.fmt.parseInt(usize, fields.next() orelse return .bad, 10) catch return .bad; + const crc_text = fields.next() orelse return .bad; + if (crc_text.len != 8 or fields.next() != null or len > max_record + max_meta) return .bad; + const crc = std.fmt.parseInt(u32, crc_text, 16) catch return .bad; + const rec: Rec = .{ .kind = line[1], .at = at, .body = at + nl + 1, .len = len, .crc = crc }; + if (rec.end() > r.size) return .partial; + const tail = r.bytes(rec.end() - 1, 1) orelse return .partial; + if (tail[0] != '\n') return .bad; + return .{ .rec = rec }; +} + +/// Whether `rec`'s body is the one its CRC says. +fn verify(r: *Reader, rec: Rec) bool { + var crc = std.hash.Crc32.init(); + var at = rec.body; + var left = rec.len; + while (left > 0) { + const n = @min(left, r.buf.len); + crc.update(r.bytes(at, n) orelse return false); + at += n; + left -= n; + } + return crc.final() == rec.crc; +} + +/// After garbage: the next `\n@` that starts a whole, valid record (or one +/// still being written), else the end. +fn resync(r: *Reader, from: u64) u64 { + var at = from; + while (at + 1 < r.size) : (at += 1) { + const b = r.bytes(at, 2) orelse return r.size; + if (b[0] != '\n' or b[1] != '@') continue; + switch (next(r, at + 1)) { + .rec => |rec| if (verify(r, rec)) return at + 1, + .partial => return at + 1, + .bad => {}, + } + } + return r.size; +} + +/// A closed pane's first line: ` +/// \t`. +const Meta = struct { + session: u64, + pid: i32, + serial: u32, + column: u32, + gainer: u32, + below: bool, + owner: u32, + rows: u16, + name: []const u8, + /// Where its dump starts in the body. + dump_at: usize, +}; + +fn parseMeta(body: []const u8) ?Meta { + const nl = std.mem.indexOfScalar(u8, body, '\n') orelse return null; + const tab = std.mem.indexOfScalar(u8, body[0..nl], '\t') orelse return null; + var f = std.mem.splitScalar(u8, body[0..tab], ' '); + var m: Meta = undefined; + m.session = std.fmt.parseInt(u64, f.next() orelse return null, 16) catch return null; + m.pid = std.fmt.parseInt(i32, f.next() orelse return null, 10) catch return null; + m.serial = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.column = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.gainer = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.below = (std.fmt.parseInt(u1, f.next() orelse return null, 10) catch return null) == 1; + m.owner = std.fmt.parseInt(u32, f.next() orelse return null, 10) catch return null; + m.rows = std.fmt.parseInt(u16, f.next() orelse return null, 10) catch return null; + if (f.next() != null) return null; + m.name = body[tab + 1 .. nl]; + m.dump_at = nl + 1; + return m; +} + +/// The store read at start; the old `recent` file beside it read into the +/// list once, when there is no store yet, so nobody's list is lost. +pub fn load(s: *Store, p: *Pardes) void { + const path = s.path orelse return; + if (comptime !pardes.hosted) return; + defer s.loaded = true; + const io = ioOf(); + const file = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch |err| { + if (err != error.FileNotFound) return; + const dir = std.fs.path.dirname(path) orelse return; + var buf: [4096 + 16]u8 = undefined; + const old = std.fmt.bufPrint(&buf, "{s}/recent", .{dir}) catch return; + const bytes = host(Dir.readFileAlloc, .{ cwd(), io, old, p.gpa, std.Io.Limit.limited(1 << 20) }) catch return; + defer p.gpa.free(bytes); + p.recent.read(p.recentGpa(), bytes); + return; + }; + defer host(File.close, .{ file, io }); + const st = host(File.stat, .{ file, io }) catch return; + s.readFile(p, file, st); +} + +/// On use: what other windows wrote since this one last read, read. One +/// stat when nothing changed. +pub fn refresh(s: *Store, p: *Pardes) void { + const path = s.path orelse return; + if (comptime !pardes.hosted) return; + if (!s.loaded) return; + const io = ioOf(); + const st = host(Dir.statFile, .{ cwd(), io, path, Dir.StatFileOptions{} }) catch return; + if (st.inode == s.inode and st.size == s.end) return; + const file = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch return; + defer host(File.close, .{ file, io }); + const fst = host(File.stat, .{ file, io }) catch return; + s.readFile(p, file, fst); +} + +/// `file` read on from where this session left it, or all of it again +/// when it is another file than the one read so far. +fn readFile(s: *Store, p: *Pardes, file: File, st: File.Stat) void { + const gpa = p.recentGpa(); + const buf = gpa.alloc(u8, 64 << 10) catch return; + defer gpa.free(buf); + var r: Reader = .{ .file = file, .io = ioOf(), .size = st.size, .buf = buf }; + var whole = st.inode != s.inode or st.size < s.end; + // The same inode number may be a new file (one compaction freed it, + // the next took it): its header's generation says. + if (!whole and s.end > 0) { + switch (next(&r, 0)) { + .rec => |rec| whole = rec.kind != 'h' or headerGen(&r, rec) != s.gen, + else => whole = true, + } + } + if (whole) { + s.inode = st.inode; + s.end = 0; + s.gen = 0; + s.base = st.size; + s.garbage = false; + // Its closed panes are read again from it, at their offsets there; + // the ones in no file yet stay. + var w: usize = 0; + for (s.closed.items) |c| { + if (c.body.len == 0) { + freeClosed(gpa, c); + continue; + } + s.closed.items[w] = c; + w += 1; + } + s.closed.shrinkRetainingCapacity(w); + } + if (st.size == s.end) return; + s.end = s.scan(p, &r, s.end); +} + +fn headerGen(r: *Reader, rec: Rec) ?u64 { + if (rec.len > 64) return null; + const b = r.bytes(rec.body, rec.len) orelse return null; + if (!std.mem.startsWith(u8, b, magic ++ " ")) return null; + return std.fmt.parseInt(u64, b[magic.len + 1 ..], 16) catch null; +} + +/// The records from `from` applied; where reading stopped (before a +/// record still being written, or the end). +fn scan(s: *Store, p: *Pardes, r: *Reader, from: u64) u64 { + var at = from; + while (at < r.size) { + switch (next(r, at)) { + .partial => return at, + .bad => { + s.garbage = true; + // A file that does not start as a store is none: empty. + if (at == 0) return r.size; + at = resync(r, at + 1); + }, + .rec => |rec| { + if (at == 0) { + s.gen = (if (rec.kind == 'h') headerGen(r, rec) else null) orelse { + s.garbage = true; + return r.size; + }; + } else if (!s.apply(p, r, rec)) s.garbage = true; + at = rec.end(); + }, + } + } + return at; +} + +/// One record read: noted in Recent, or a closed pane of this session's +/// listed or unlisted. False when it is not what its header says. +fn apply(s: *Store, p: *Pardes, r: *Reader, rec: Rec) bool { + const gpa = p.recentGpa(); + switch (rec.kind) { + 'r' => { + if (rec.len > 8192) return false; + const b = r.bytes(rec.body, rec.len) orelse return false; + if (std.hash.Crc32.hash(b) != rec.crc) return false; + const e = recent.List.parseLine(b) orelse return false; + p.recent.note(gpa, e.path, e.nums[0], e.nums[1], e.nums[2], e.nums[3]); + }, + 'c' => { + // Only its first line is read: a closed pane is this session's + // or none of its business, and its dump is read when it comes + // back (`reopen`, which checks the CRC). + const b = r.bytes(rec.body, @min(rec.len, max_meta)) orelse return false; + const m = parseMeta(b) orelse return false; + if (m.session != s.session) return true; + s.list(gpa, m, rec.at, &.{}); + }, + 'x' => { + if (rec.len > 64) return false; + const b = r.bytes(rec.body, rec.len) orelse return false; + if (std.hash.Crc32.hash(b) != rec.crc) return false; + const sp = std.mem.indexOfScalar(u8, b, ' ') orelse return false; + const session = std.fmt.parseInt(u64, b[0..sp], 16) catch return false; + const serial = std.fmt.parseInt(u32, b[sp + 1 ..], 10) catch return false; + if (session == s.session) s.unlist(gpa, serial); + }, + // A header in the middle is no record. + 'h' => return false, + // A kind a newer pardes writes: passed over. + else => {}, + } + return true; +} + +/// A closed pane listed: from the file (`body` empty, its record at `at`) +/// or not in one yet. In the order closed, the oldest going past +/// `max_closed`. +fn list(s: *Store, gpa: std.mem.Allocator, m: Meta, at: u64, body: []u8) void { + for (s.closed.items) |c| if (c.serial == m.serial) { + gpa.free(body); + return; + }; + const name = gpa.dupe(u8, m.name) catch { + gpa.free(body); + return; + }; + const c: Closed = .{ .serial = m.serial, .column = m.column, .gainer = m.gainer, .below = m.below, .owner = m.owner, .rows = m.rows, .name = name, .at = at, .body = body }; + if (s.closed.items.len >= max_closed) freeClosed(gpa, s.closed.orderedRemove(0)); + // One read from the file goes before those in none yet: they are newer. + var i = s.closed.items.len; + if (body.len == 0) while (i > 0 and s.closed.items[i - 1].body.len > 0) : (i -= 1) {}; + s.closed.insert(gpa, i, c) catch freeClosed(gpa, c); +} + +fn unlist(s: *Store, gpa: std.mem.Allocator, serial: u32) void { + for (s.closed.items, 0..) |c, i| if (c.serial == serial) { + freeClosed(gpa, s.closed.orderedRemove(i)); + return; + }; +} + +/// The closed pane with this serial, if this session has it. +pub fn closedBySerial(s: *const Store, serial: u32) ?*Closed { + for (s.closed.items) |*c| if (c.serial == serial) return c; + return null; +} + +// ---- writing ---- + +fn frame(gpa: std.mem.Allocator, out: *std.ArrayList(u8), kind: u8, parts: []const []const u8) !void { + var len: usize = 0; + var crc = std.hash.Crc32.init(); + for (parts) |part| { + len += part.len; + crc.update(part); + } + try out.print(gpa, "@{c} {d} {x:0>8}\n", .{ kind, len, crc.final() }); + for (parts) |part| try out.appendSlice(gpa, part); + try out.append(gpa, '\n'); +} + +/// Pane `id`, about to close, kept as a record: what it was (a one-pane +/// Dump) and where (its column, its rows, what it was attached to). Null +/// for a pane that is no pane of the user's: a query pane, a preview, one +/// made and refused in the same step (never announced), or one whose dump +/// fails or is too big. `close` finishes it once its rows have gone. +pub fn keep(s: *Store, p: *Pardes, id: usize) ?Kept { + _ = s; + const pane = p.panes[id] orelse return null; + if (pane.fs.unannounced or pane.query != null) return null; + if (pane.file) |f| if (f.output) |o| if (o.from == .preview) return null; + const gpa = p.recentGpa(); + const arena = p.scratch.allocator(); + var dp = dump.dumpPane(p, arena, pane) catch return null; + var zon = oneDump(p, arena, dp) catch return null; + // A terminal's history is what makes it big: kept without it, it comes + // back a fresh shell in its directory. + if (zon.len > max_record) if (dp.terminal) |*t| { + t.stream = ""; + t.stream_b64 = ""; + dp.body = ""; + zon = oneDump(p, arena, dp) catch return null; + }; + if (zon.len > max_record) return null; + const what: []const u8 = if (pane.file) |f| f.path else if (pane.pdfPath()) |pdf| pdf else if (pane.image) |iv| iv.path else if (pane.command) |c| c else pane.cwdSlice(); + var name = gpa.alloc(u8, @min(what.len, 4096)) catch return null; + // One line, a tab its end: a newline or a tab in it is a space. + for (what[0..name.len], 0..) |c, i| name[i] = if (c == '\n' or c == '\t') ' ' else c; + const owned = gpa.dupe(u8, zon) catch { + gpa.free(name); + return null; + }; + const at = layout.findPane(p, id); + const owner = layout.ownerOf(p, id); + return .{ + .serial = pane.serial, + .column = if (at) |f| layout.columnSerial(p, f.col) else 0, + .owner = if (owner) |o| p.panes[o].?.serial else 0, + .idx = if (at) |f| f.idx else 0, + .rows = p.rects[id].h, + .name = name, + .dump = owned, + }; +} + +pub const Kept = struct { + serial: u32, + column: u32, + owner: u32, + /// Its place in its column, to say which side of the gainer it was. + idx: usize, + rows: u16, + name: []u8, + dump: []u8, + + pub fn free(k: Kept, gpa: std.mem.Allocator) void { + gpa.free(k.name); + gpa.free(k.dump); + } +}; + +/// A Dump of the one pane `dp`, as a Restore would read it. +fn oneDump(p: *Pardes, arena: std.mem.Allocator, dp: dump.Pane) ![]const u8 { + const ids = [_]usize{0}; + const columns = [_]dump.Column{.{ .panes = &ids }}; + const one = [_]dump.Pane{dp}; + const state: dump.State = .{ .screen = .{ .cols = p.screen_w, .rows = p.screen_h }, .columns = &columns, .panes = &one }; + try dump.validate(state); + var out: std.Io.Writer.Allocating = .init(arena); + try std.zon.stringify.serialize(state, .{}, &out.writer); + return out.written(); +} + +/// The pane `k` kept is gone, its rows given to `gainer` (a slot, after +/// they moved; null none): listed, and its record framed for the store. +pub fn close(s: *Store, p: *Pardes, k: Kept, gainer: ?usize) void { + const gpa = p.recentGpa(); + var below = false; + var gainer_serial: u32 = 0; + if (gainer) |g| if (p.panes[g]) |gp| { + gainer_serial = gp.serial; + // It went from just below the gainer's place, or it was the first + // and the rows went down. + if (layout.findPane(p, g)) |f| below = f.idx < k.idx; + }; + var meta_buf: [max_meta]u8 = undefined; + const meta = std.fmt.bufPrint(&meta_buf, "{x:0>16} {d} {d} {d} {d} {d} {d} {d}\t{s}\n", .{ + s.session, s.pid, k.serial, k.column, gainer_serial, @intFromBool(below), k.owner, k.rows, k.name, + }) catch { + k.free(gpa); + return; + }; + const m = parseMeta(meta).?; + const body = std.mem.concat(gpa, u8, &.{ meta, k.dump }) catch { + k.free(gpa); + return; + }; + gpa.free(k.dump); + const pending_at = s.pending.items.len; + const framed = if (s.path != null) blk: { + frame(gpa, &s.pending, 'c', &.{body}) catch break :blk false; + break :blk true; + } else false; + s.list(gpa, m, 0, body); + gpa.free(k.name); + if (framed) if (s.closedBySerial(m.serial)) |c| { + c.pending_at = pending_at; + }; +} + +/// Written out when anything changed, at the end of a step and at the end +/// (`wait`: the lock is waited for there, never in a step). +pub fn flush(s: *Store, p: *Pardes, wait: bool) void { + const gpa = p.recentGpa(); + if (!p.recent.dirty and s.pending.items.len == 0) return; + const path = if (comptime pardes.hosted) s.path else null; + if (path == null or !s.loaded) { + if (path == null) { + for (p.recent.entries.items) |*e| e.changed = false; + p.recent.dirty = false; + s.pending.clearRetainingCapacity(); + for (s.closed.items) |*c| c.pending_at = null; + } + return; + } + const io = ioOf(); + var name_buf: [4096 + 16]u8 = undefined; + const lock_path = std.fmt.bufPrint(&name_buf, "{s}.lock", .{path.?}) catch return; + const lock = host(Dir.createFile, .{ cwd(), io, lock_path, Dir.CreateFileOptions{ .truncate = false } }) catch return; + // Closing it lets go of the lock. + defer host(File.close, .{ lock, io }); + if (wait) { + host(File.lock, .{ lock, io, File.Lock.exclusive }) catch return; + } else if (!(host(File.tryLock, .{ lock, io, File.Lock.exclusive }) catch return)) return; + const file = host(Dir.createFile, .{ cwd(), io, path.?, Dir.CreateFileOptions{ .read = true, .truncate = false } }) catch return; + defer host(File.close, .{ file, io }); + const st = host(File.stat, .{ file, io }) catch return; + // Others' records first, so this window's go after them here too. + s.readFile(p, file, st); + // Under the lock, a record still "being written" is one whose writer + // died: garbage. + if (s.end < st.size) s.garbage = true; + p.recent.changedFirst(); + var i = p.recent.entries.items.len; + var line_buf: [4096 + 64]u8 = undefined; + while (i > 0) : (i -= 1) { + const e = &p.recent.entries.items[i - 1]; + if (!e.changed) continue; + e.changed = false; + var w = std.Io.Writer.fixed(&line_buf); + recent.List.writeEntry(e.*, &w) catch continue; + const line = std.mem.trimEnd(u8, w.buffered(), "\n"); + if (line.len > 0) frame(gpa, &s.pending, 'r', &.{line}) catch {}; + } + p.recent.dirty = false; + if (s.garbage or st.size == 0 or st.size + s.pending.items.len > s.cap or st.size > 2 * s.base + (1 << 20)) { + s.compact(p, file, st, path.?); + return; + } + host(File.writePositionalAll, .{ file, io, s.pending.items, st.size }) catch { + // Out of disk: kept for no one, as the old list was. + s.dropPending(gpa); + return; + }; + for (s.closed.items) |*c| if (c.pending_at) |off| { + c.at = st.size + off; + c.pending_at = null; + gpa.free(c.body); + c.body = &.{}; + }; + s.end = st.size + s.pending.items.len; + s.pending.clearRetainingCapacity(); +} + +fn dropPending(s: *Store, gpa: std.mem.Allocator) void { + _ = gpa; + s.pending.clearRetainingCapacity(); + for (s.closed.items) |*c| c.pending_at = null; +} + +fn alive(pid: i32) bool { + if (pid <= 0) return false; + const rc = std.c.kill(pid, @enumFromInt(0)); + return rc == 0 or std.c.errno(rc) == .PERM; +} + +/// Under the lock: the live records into `.new`, this window's +/// pending ones after them, renamed over the store; then read again whole. +fn compact(s: *Store, p: *Pardes, file: File, st: File.Stat, path: []const u8) void { + const gpa = p.recentGpa(); + const io = ioOf(); + defer s.dropPending(gpa); + const buf = gpa.alloc(u8, 64 << 10) catch return; + defer gpa.free(buf); + var r: Reader = .{ .file = file, .io = io, .size = st.size, .buf = buf }; + var fold: recent.List = .{}; + defer fold.deinit(gpa); + const Live = struct { at: u64, end: u64, session: u64, pid: i32, serial: u32, keep: bool = false }; + var lives: std.ArrayList(Live) = .empty; + defer lives.deinit(gpa); + const Gone = struct { session: u64, serial: u32 }; + var gone: std.ArrayList(Gone) = .empty; + defer gone.deinit(gpa); + var at: u64 = 0; + while (at < r.size) { + switch (next(&r, at)) { + .partial => break, + .bad => at = resync(&r, at + 1), + .rec => |rec| { + at = rec.end(); + if (rec.kind == 'h' or !verify(&r, rec)) continue; + const b = r.bytes(rec.body, @min(rec.len, max_meta)) orelse continue; + switch (rec.kind) { + 'r' => if (recent.List.parseLine(b)) |e| fold.note(gpa, e.path, e.nums[0], e.nums[1], e.nums[2], e.nums[3]), + 'c' => if (parseMeta(b)) |m| lives.append(gpa, .{ .at = rec.at, .end = rec.end(), .session = m.session, .pid = m.pid, .serial = m.serial }) catch {}, + 'x' => { + const sp = std.mem.indexOfScalar(u8, b, ' ') orelse continue; + gone.append(gpa, .{ + .session = std.fmt.parseInt(u64, b[0..sp], 16) catch continue, + .serial = std.fmt.parseInt(u32, b[sp + 1 ..], 10) catch continue, + }) catch {}; + }, + else => {}, + } + }, + } + } + // The closed panes kept: of running sessions, not brought back, the + // newest `max_closed` a session, the newest within half the cap. + var budget: u64 = s.cap / 2 -| s.pending.items.len; + var k = lives.items.len; + while (k > 0) : (k -= 1) { + const l = &lives.items[k - 1]; + const reopened = for (gone.items) |g| { + if (g.session == l.session and g.serial == l.serial) break true; + } else false; + if (reopened or (l.session != s.session and !alive(l.pid))) continue; + var newer: usize = 0; + for (lives.items[k..]) |o| if (o.keep and o.session == l.session) { + newer += 1; + }; + if (newer >= max_closed or l.end - l.at > budget) continue; + budget -= l.end - l.at; + l.keep = true; + } + var name_buf: [4096 + 16]u8 = undefined; + const new_path = std.fmt.bufPrint(&name_buf, "{s}.new", .{path}) catch return; + const out = host(Dir.createFile, .{ cwd(), io, new_path, Dir.CreateFileOptions{} }) catch return; + var ok = false; + defer if (!ok) { + host(File.close, .{ out, io }); + host(Dir.deleteFile, .{ cwd(), io, new_path }) catch {}; + }; + var head: std.ArrayList(u8) = .empty; + defer head.deinit(gpa); + var gen_buf: [64]u8 = undefined; + const now = clockNs(); + const gen = std.hash.Wyhash.hash(s.session, std.mem.asBytes(&now)); + frame(gpa, &head, 'h', &.{std.fmt.bufPrint(&gen_buf, magic ++ " {x}", .{gen}) catch return}) catch return; + var line_buf: [4096 + 64]u8 = undefined; + var i = fold.entries.items.len; + while (i > 0) : (i -= 1) { + var w = std.Io.Writer.fixed(&line_buf); + recent.List.writeEntry(fold.entries.items[i - 1], &w) catch continue; + const line = std.mem.trimEnd(u8, w.buffered(), "\n"); + if (line.len > 0) frame(gpa, &head, 'r', &.{line}) catch return; + } + host(File.writePositionalAll, .{ out, io, head.items, 0 }) catch return; + var off: u64 = head.items.len; + for (lives.items) |l| if (l.keep) { + var from = l.at; + while (from < l.end) { + const n: usize = @intCast(@min(buf.len, l.end - from)); + const b = r.bytes(from, n) orelse return; + host(File.writePositionalAll, .{ out, io, b, off }) catch return; + off += n; + from += n; + } + }; + host(File.writePositionalAll, .{ out, io, s.pending.items, off }) catch return; + host(File.sync, .{ out, io }) catch return; + host(File.close, .{ out, io }); + ok = true; + host(Dir.rename, .{ cwd(), new_path, cwd(), path, io }) catch { + host(Dir.deleteFile, .{ cwd(), io, new_path }) catch {}; + return; + }; + // Every closed pane of this session is in the new file now: read again + // from it, at its offsets there. + for (s.closed.items) |c| freeClosed(gpa, c); + s.closed.clearRetainingCapacity(); + s.inode = 0; + const again = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch return; + defer host(File.close, .{ again, io }); + const nst = host(File.stat, .{ again, io }) catch return; + s.readFile(p, again, nst); +} + +// ---- bringing a closed pane back ---- + +/// Closed pane `serial` of this session made again, where it was: beside +/// the pane its rows went to, taking them from that pane alone (attached +/// again to its owner when that is still open), else placed as a new pane +/// from `from`. False when it is not this session's, or its record is gone +/// or bad; the keyboard on it otherwise. +pub fn reopen(s: *Store, p: *Pardes, serial: u32, from: usize) bool { + s.refresh(p); + const gpa = p.recentGpa(); + const place = (s.closedBySerial(serial) orelse return false).*; + const body = s.bodyOf(p, place) orelse return false; + // Read from the file: this call's to free (`unlist` frees one held). + defer if (place.body.len == 0) gpa.free(body); + const m = parseMeta(body) orelse return false; + var parsed = dump.readZon(p.gpa, body[m.dump_at..], "closed pane") catch return false; + defer parsed.deinit(); + const free = p.freeSlot() orelse { + p.reportError(from, "Panes", error.NoPaneSlots); + return false; + }; + const src = parsed.value.panes[0]; + const pane = dump.restorePane(p, free, src) catch |err| { + p.reportError(from, "Panes", err); + return false; + }; + pane.collapsed = false; + const owner = if (place.owner != 0) p.paneBySerial(place.owner) else null; + const gainer = if (place.gainer != 0) p.paneBySerial(place.gainer) else null; + const placed = if (owner) |o| + layout.attachFrom(p, o, free, place.rows, o) + else if (gainer) |g| + layout.giveBack(p, free, g, place.below, place.rows) + else + false; + if (!placed) exec.placeNew(p, from, from, free, .doc); + if (layout.findPane(p, free) == null) { + p.removePane(free, null) catch {}; + return false; + } + // No room anywhere: refused, it closes at the step's end, still listed. + if (p.unplaced.isSet(free)) return false; + // Brought back: no longer listed, here or when read again. + var rec_buf: [64]u8 = undefined; + const rec = std.fmt.bufPrint(&rec_buf, "{x:0>16} {d}", .{ s.session, serial }) catch unreachable; + if (s.path != null) frame(gpa, &s.pending, 'x', &.{rec}) catch {}; + s.unlist(gpa, serial); + p.active = free; + if (layout.findPane(p, free)) |f| p.setActiveColumn(f.col); + p.sync(); + return true; +} + +/// A closed pane's record body: held here, or read from the file and +/// checked against its CRC (gpa; the caller frees it when it is not +/// `c.body`). +fn bodyOf(s: *Store, p: *Pardes, c: Closed) ?[]u8 { + if (c.body.len > 0) return c.body; + const path = s.path orelse return null; + if (comptime !pardes.hosted) return null; + const gpa = p.recentGpa(); + const io = ioOf(); + const file = host(Dir.openFile, .{ cwd(), io, path, Dir.OpenFileOptions{} }) catch return null; + defer host(File.close, .{ file, io }); + const st = host(File.stat, .{ file, io }) catch return null; + if (st.inode != s.inode) return null; + var head_buf: [max_head]u8 = undefined; + var r: Reader = .{ .file = file, .io = io, .size = st.size, .buf = &head_buf }; + const rec = switch (next(&r, c.at)) { + .rec => |rec| rec, + else => return null, + }; + if (rec.kind != 'c') return null; + const body = gpa.alloc(u8, rec.len) catch return null; + const n = host(File.readPositionalAll, .{ file, io, body, rec.body }) catch 0; + if (n != rec.len or std.hash.Crc32.hash(body) != rec.crc) { + gpa.free(body); + return null; + } + return body; +} + +/// `@p` naming a pane this session closed: its serial. +pub fn closedAddress(s: *const Store, word: []const u8) ?u32 { + const addr = @import("config.zig").pane_addr; + if (!std.mem.startsWith(u8, word, addr)) return null; + const digits = word[addr.len..]; + const end = for (digits, 0..) |ch, i| { + if (!std.ascii.isDigit(ch)) break i; + } else digits.len; + // `@p7` alone, or `@p7:` with nothing after it: the pane, no place in it. + if (end == 0 or (end < digits.len and !(digits[end] == ':' and end + 1 == digits.len))) return null; + const serial = std.fmt.parseInt(u32, digits[0..end], 10) catch return null; + return if (s.closedBySerial(serial) != null) serial else null; +} + +// ---- tests ---- + +const testing = std.testing; + +/// The store file of a test, in its own directory (never the user's). +fn testPath(tmp: *std.testing.TmpDir) ![]u8 { + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(testing.io, &base_buf)]; + return std.fs.path.join(testing.allocator, &.{ dir, "store" }); +} + +fn testWindow(path: []const u8) !*Pardes { + return Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48, .store_path = path }); +} + +fn fileSize(path: []const u8) u64 { + const st = std.Io.Dir.cwd().statFile(testing.io, path, .{}) catch return 0; + return st.size; +} + +test "store: two windows share Recent, each reading the other's writes on use; a busy lock delays, never loses" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + const a = try testWindow(path); + defer a.deinit(); + const b = try testWindow(path); + defer b.deinit(); + try testing.expect(a.store.session != b.store.session); + a.recent.opened(a.recentGpa(), "/w/a.zig"); + a.saveRecent(); + b.recent.opened(b.recentGpa(), "/w/b.zig"); + b.saveRecent(); + a.recent.closed(a.recentGpa(), "/w/a.zig", 7, 3); + a.saveRecent(); + // Each has both, in the order of the log: a closed last, then b. + a.store.refresh(a); + b.store.refresh(b); + for ([_]*Pardes{ a, b }) |w| { + try testing.expectEqual(@as(usize, 2), w.recent.entries.items.len); + try testing.expectEqualStrings("/w/a.zig", w.recent.entries.items[0].path); + try testing.expectEqualStrings("/w/b.zig", w.recent.entries.items[1].path); + try testing.expectEqual(@as(u32, 7), w.recent.get("/w/a.zig").?.line); + } + // Another window holding the lock: b's change waits in memory... + const lock_path = try std.fmt.allocPrint(testing.allocator, "{s}.lock", .{path}); + defer testing.allocator.free(lock_path); + const lock = try std.Io.Dir.cwd().createFile(testing.io, lock_path, .{ .truncate = false }); + try lock.lock(testing.io, .exclusive); + b.recent.opened(b.recentGpa(), "/w/c.zig"); + const size = fileSize(path); + b.saveRecent(); + try testing.expectEqual(size, fileSize(path)); + try testing.expect(b.recent.dirty); + // ...and is written at the next step after it is let go. + lock.close(testing.io); + b.saveRecent(); + try testing.expect(fileSize(path) > size); + a.store.refresh(a); + try testing.expectEqualStrings("/w/c.zig", a.recent.entries.items[0].path); + // A window started now folds the same list. + const c = try testWindow(path); + defer c.deinit(); + try testing.expectEqual(@as(usize, 3), c.recent.entries.items.len); + for (a.recent.entries.items, c.recent.entries.items) |x, y| try testing.expectEqualStrings(x.path, y.path); +} + +test "store: the cap holds, compaction keeps the newest, Recent keeps its 200" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + const a = try testWindow(path); + defer a.deinit(); + a.store.cap = 48 << 10; + var name: [32]u8 = undefined; + var inodes: usize = 0; + var last_inode = a.store.inode; + for (0..3000) |i| { + const file = std.fmt.bufPrint(&name, "/w/file{d}.zig", .{i}) catch unreachable; + a.recent.opened(a.recentGpa(), file); + a.recent.closed(a.recentGpa(), file, 1, 1); + a.saveRecent(); + try testing.expect(fileSize(path) <= a.store.cap); + if (a.store.inode != last_inode) inodes += 1; + last_inode = a.store.inode; + } + try testing.expect(inodes > 2); + try testing.expectEqual(@as(usize, recent.cap), a.recent.entries.items.len); + try testing.expectEqualStrings("/w/file2999.zig", a.recent.entries.items[0].path); + const b = try testWindow(path); + defer b.deinit(); + try testing.expectEqual(@as(usize, recent.cap), b.recent.entries.items.len); + try testing.expectEqualStrings("/w/file2999.zig", b.recent.entries.items[0].path); + try testing.expectEqualStrings("/w/file2800.zig", b.recent.entries.items[recent.cap - 1].path); + // Closed panes' text counts too: the newest stay, within the cap. + a.store.cap = 256 << 10; + var text: [20 << 10]u8 = @splat('t'); + var serial: u32 = 0; + for (0..30) |i| { + a.newScratchBelow(a.active); + const id = a.active; + const f = &a.panes[id].?.file.?; + text[0] = @intCast('a' + i % 26); + @import("File.zig").setContent(a, f, try a.gpa.dupe(u8, &text)); + serial = a.panes[id].?.serial; + // Made outside a step: announced as a step's end would. + pardes.ctlfs.events.announce(a); + try a.removePane(id, null); + a.saveRecent(); + try testing.expect(fileSize(path) <= a.store.cap); + } + try testing.expect(a.store.closed.items.len < 30); + try testing.expectEqual(serial, a.store.closed.items[a.store.closed.items.len - 1].serial); + try testing.expect(a.store.reopen(a, serial, a.active)); + try testing.expectEqual(@as(u8, 'a' + 29 % 26), a.panes[a.active].?.file.?.content[0]); +} + +test "store: a garbage or torn file never stops pardes, records past garbage are read, the next writer mends it" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = path, .data = "\x00\xffnot a store at all\n@r 9 zz\n" }); + const a = try testWindow(path); + defer a.deinit(); + try testing.expectEqual(@as(usize, 0), a.recent.entries.items.len); + try testing.expect(a.store.garbage); + a.recent.opened(a.recentGpa(), "/w/a.zig"); + a.saveRecent(); + try testing.expect(!a.store.garbage); + // A torn record at the end (its writer died), then garbage, then a + // whole record: the whole one is read, the rest passed over. + var tail: std.ArrayList(u8) = .empty; + defer tail.deinit(testing.allocator); + try tail.appendSlice(testing.allocator, "@r 40 0000"); + try tail.appendSlice(testing.allocator, "\x00junk\n@x not a header\n"); + try frame(testing.allocator, &tail, 'r', &.{"3 1 0 0 /w/after.zig"}); + { + const f = try std.Io.Dir.cwd().openFile(testing.io, path, .{ .mode = .read_write }); + defer f.close(testing.io); + try f.writePositionalAll(testing.io, tail.items, (try f.stat(testing.io)).size); + } + const b = try testWindow(path); + defer b.deinit(); + try testing.expect(b.recent.get("/w/a.zig") != null); + try testing.expectEqual(@as(u32, 3), b.recent.get("/w/after.zig").?.line); + try testing.expect(b.store.garbage); + // A record half written (the length runs past the end) is waited for, + // not garbage: a reader reads it once it is whole. + var half: std.ArrayList(u8) = .empty; + defer half.deinit(testing.allocator); + try frame(testing.allocator, &half, 'r', &.{"5 1 0 0 /w/late.zig"}); + { + const f = try std.Io.Dir.cwd().openFile(testing.io, path, .{ .mode = .read_write }); + defer f.close(testing.io); + const end = (try f.stat(testing.io)).size; + try f.writePositionalAll(testing.io, half.items[0..10], end); + a.store.refresh(a); + try testing.expect(a.recent.get("/w/late.zig") == null); + try f.writePositionalAll(testing.io, half.items[10..], end + 10); + } + a.store.refresh(a); + try testing.expectEqual(@as(u32, 5), a.recent.get("/w/late.zig").?.line); + // The next write compacts it: a reader then finds no garbage. + b.recent.opened(b.recentGpa(), "/w/b.zig"); + b.saveRecent(); + const c = try testWindow(path); + defer c.deinit(); + try testing.expect(!c.store.garbage); + for ([_][]const u8{ "/w/a.zig", "/w/after.zig", "/w/late.zig", "/w/b.zig" }) |want| try testing.expect(c.recent.get(want) != null); +} + +test "store: a closed pane comes back where it was, its rows from the pane that took them, nothing else moving; Panes lists it, marked" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(&tmp); + defer testing.allocator.free(path); + const p = try testWindow(path); + defer p.deinit(); + _ = try p.setTestFile("alpha\nbeta\n"); + p.newScratchBelow(0); + const sid = p.active; + @import("File.zig").setContent(p, &p.panes[sid].?.file.?, try p.gpa.dupe(u8, "kept text\n")); + const other = p.col_panes[0][1]; + p.newScratchBelow(0); + try testing.expect(layout.splitColumn(p, p.active, p.active, false)); + const far = p.active; + _ = other; + p.active = 0; + // Made outside a step: announced as a step's end would. + pardes.ctlfs.events.announce(p); + layout.compute(p); + const before = p.rects; + const serial = p.panes[sid].?.serial; + try p.removePane(sid, null); + layout.compute(p); + try testing.expectEqualDeep(before[far], p.rects[far]); + // Written to the store: brought back from the file, not memory. + p.saveRecent(); + try testing.expectEqual(@as(usize, 0), p.store.closedBySerial(serial).?.body.len); + try testing.expect(p.store.reopen(p, serial, 0)); + const back = p.active; + layout.compute(p); + try testing.expectEqualStrings("kept text\n", p.panes[back].?.file.?.content); + try testing.expect(p.panes[back].?.serial != serial); + // Its rect as it was, the one above as it was, the other column's + // untouched: its rows came from the pane that took them alone. + try testing.expectEqualDeep(before[sid], p.rects[back]); + try testing.expectEqualDeep(before[0], p.rects[0]); + try testing.expectEqualDeep(before[far], p.rects[far]); + try testing.expect(p.store.closedBySerial(serial) == null); + // Closed again: Panes lists it after the open ones, `(closed)`. + const again = p.panes[back].?.serial; + pardes.ctlfs.events.announce(p); + try p.removePane(back, null); + p.saveRecent(); + p.active = 0; + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + for ("bb") |ch| p.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const q = p.panes[qid].?.query.?; + const row = for (q.items.items, 0..) |it, i| { + if (it.ref == again) break i; + } else return error.NotListed; + const line = @import("modal.zig").lineSlice(p.panes[qid].?.file.?.content, @intCast(row + 1)); + try testing.expect(std.mem.endsWith(u8, line, "(closed)")); + // Enter on it: back, and listed no more (nor in the store when read). + panes_mod.Query.land(p, qid, row); + const found = for (p.panes) |slot| { + if (slot) |pp| if (pp.file) |f| if (std.mem.eql(u8, f.content, "kept text\n")) break true; + } else false; + try testing.expect(found); + try testing.expect(p.store.closedBySerial(again) == null); + p.saveRecent(); + p.store.inode = 0; + p.store.refresh(p); + try testing.expect(p.store.closedBySerial(again) == null); + // Another session lists none of this one's. + const w = try testWindow(path); + defer w.deinit(); + try testing.expectEqual(@as(usize, 0), w.store.closed.items.len); +} + +const panes_mod = @import("panes.zig"); + +test "zz store timings on a 90 MiB store (STORE_TIMES=)" { + const dir_z = std.c.getenv("STORE_TIMES") orelse return error.SkipZigTest; + const gpa = testing.allocator; + const path = try std.fs.path.join(gpa, &.{ std.mem.span(dir_z), "store" }); + defer gpa.free(path); + // A store as another running session leaves it: 200 files, then 90 + // closed panes of 1 MiB each (this pid: alive, so a compaction keeps + // what fits). + { + var bytes: std.ArrayList(u8) = .empty; + defer bytes.deinit(gpa); + try frame(gpa, &bytes, 'h', &.{magic ++ " 1"}); + var line: [64]u8 = undefined; + for (0..200) |i| try frame(gpa, &bytes, 'r', &.{std.fmt.bufPrint(&line, "1 1 0 0 /w/file{d}.zig", .{i}) catch unreachable}); + const out = try std.Io.Dir.cwd().createFile(testing.io, path, .{}); + defer out.close(testing.io); + try out.writePositionalAll(testing.io, bytes.items, 0); + var off: u64 = bytes.items.len; + const big = try gpa.alloc(u8, 1 << 20); + defer gpa.free(big); + @memset(big, 'z'); + for (0..90) |i| { + bytes.clearRetainingCapacity(); + var meta: [128]u8 = undefined; + const m = std.fmt.bufPrint(&meta, "{x:0>16} {d} {d} 1 0 0 0 10\t/w/closed{d}\n", .{ @as(u64, 0xfeed), std.c.getpid(), i + 1, i }) catch unreachable; + try frame(gpa, &bytes, 'c', &.{ m, big }); + try out.writePositionalAll(testing.io, bytes.items, off); + off += bytes.items.len; + } + } + const t0 = nowNs(); + const p = try testWindow(path); + defer p.deinit(); + const load_ns = nowNs() - t0; + var t = nowNs(); + for (0..1000) |_| p.store.refresh(p); + const refresh_ns = (nowNs() - t) / 1000; + t = nowNs(); + var name: [32]u8 = undefined; + for (0..100) |i| { + const f = std.fmt.bufPrint(&name, "/w/new{d}.zig", .{i}) catch unreachable; + p.recent.opened(p.recentGpa(), f); + p.recent.closed(p.recentGpa(), f, 1, 1); + p.saveRecent(); + } + const flush_ns = (nowNs() - t) / 100; + const before = fileSize(path); + p.store.garbage = true; + p.recent.opened(p.recentGpa(), "/w/last.zig"); + t = nowNs(); + p.saveRecent(); + const compact_ns = nowNs() - t; + std.debug.print("store timings: load {d} us, refresh (unchanged) {d} ns, flush one record {d} us, compaction {d} -> {d} bytes {d} ms\n", .{ + load_ns / 1000, refresh_ns, flush_ns / 1000, before, fileSize(path), compact_ns / 1_000_000, + }); +} + +fn nowNs() u64 { + return @intCast(clockNs()); +} diff --git a/src/dump.zig b/src/dump.zig index 0ce44c40..140bc476 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -717,34 +717,7 @@ pub fn dumpState(p: *Pardes) !void { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; slot_to_pane[id] = panes_len; - const tag = try tagline.tagText(p, arena, pane); - const body = try body_layer.bodyText(p, arena, pane); - const scroll: usize = @intCast(@max(0, pane.scroll())); - var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( - p, - arena, - pane, - f, - tag, - body, - scroll, - if (f.output) |o| pardes.panes.Output.word(o.from) else "", - if (f.output) |*o| o.arg() else "", - ) else if (pane.hasPdf()) blk: { - if (comptime !pdf_enabled) unreachable; - const pv = &pane.pdf.?; - break :blk try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{}); - } else if (pane.image) |iv| - try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) - else - try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); - dp.tag_tail = pane.tag.own; - if (dp.file) |*df| { - const dot = ctlfs.pane.dotOf(pane); - df.dot = .{ dot.q0, dot.q1 }; - } - dp.serial = pane.serial; - dump_panes[panes_len] = dp; + dump_panes[panes_len] = try dumpPane(p, arena, pane); panes_len += 1; } // An attachment names its owner by its place in the dump: serials are @@ -814,6 +787,39 @@ pub fn dumpState(p: *Pardes) !void { p.emit(.write_dump); } +/// One pane as a dump keeps it, its strings in `arena`: a Restore's, and a +/// closed pane's in the store (Store.zig), which Panes brings back. +pub fn dumpPane(p: *Pardes, arena: std.mem.Allocator, pane: *pardes.panes.Pane) !Pane { + const tag = try tagline.tagText(p, arena, pane); + const body = try body_layer.bodyText(p, arena, pane); + const scroll: usize = @intCast(@max(0, pane.scroll())); + var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( + p, + arena, + pane, + f, + tag, + body, + scroll, + if (f.output) |o| pardes.panes.Output.word(o.from) else "", + if (f.output) |*o| o.arg() else "", + ) else if (pane.hasPdf()) blk: { + if (comptime !pdf_enabled) unreachable; + const pv = &pane.pdf.?; + break :blk try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{}); + } else if (pane.image) |iv| + try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) + else + try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); + dp.tag_tail = pane.tag.own; + if (dp.file) |*df| { + const dot = ctlfs.pane.dotOf(pane); + df.dot = .{ dot.q0, dot.q1 }; + } + dp.serial = pane.serial; + return dp; +} + /// The setting lines that differ from a fresh session's, as the root ctl /// reads them, less the ones a dump keeps apart. fn changedSettings(p: *Pardes, arena: std.mem.Allocator) ![]const []const u8 { @@ -901,7 +907,8 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo if (old.last_dump) |d| p.last_dump = try gpa.dupe(u8, d); // Recent goes on across a Restore, the old session's own list. p.recent = old.recent.clone(p.recentGpa()); - p.recent_loaded = old.recent_loaded; + // The same session: its closed panes go on being its own. + p.store = old.store.clone(p.recentGpa()); } else p.loadRecent(); var parsed = try readZon(gpa, zon_bytes, "load"); defer parsed.deinit(); @@ -944,77 +951,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo for (st.panes, 0..) |src, i| { if (i >= MAX_PANES) break; if (old_serials) |o| o.panes[i] = src.serial; - const pane: *pardes.panes.Pane = switch (src.kind) { - .terminal => terminal: { - const t = src.terminal.?; - // A host that runs shells gets them back: the old history - // above a new shell in the directory it was in. The web - // shell and an isolated build only ever replay it. - // A command pane comes back finished, showing what it said - // and how it ended: its command is not run again. - const live = comptime (terminal_panes and platform != .web and !isolated); - const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; - const restored = try pardes.panes.terminal.restore(p, src, revive); - p.installPane(i, restored); - try restored.setOwnedCwd(t.cwd); - if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); - if (t.command.len > 0) { - restored.command = try gpa.dupe(u8, t.command); - restored.command_done = true; - restored.command_status = t.status; - } - if (revive) p.emitSpawn(i, restored.serial, t.cwd); - if (t.petscii and pardes.panes.terminal.petscii(restored) == false) pardes.panes.terminal.togglePetscii(restored); - break :terminal restored; - }, - .file => file: { - const restored = try pardes.panes.File.restore(p, i, src); - // A twin: on the earlier pane's buffer again. - if (src.file.?.twin_of) |j| if (j < i) pardes.panes.File.relink(p, j, i, src.file.?.dot); - break :file restored; - }, - .image => restore_image: { - const im = src.image.?; - if (pardes.panes.Pdf.isPath(im.path)) { - var raw: []u8 = if (im.bytes_b64.len > 0) - try decodeBytes(gpa, im.bytes_b64) - else - &.{}; - errdefer if (raw.len > 0) gpa.free(raw); - if (comptime pdf_enabled) { - if (pardes.panes.Pdf.openPane(p, i, im.path, src.scroll + 1, .last) catch null) |restored| { - if (raw.len > 0) gpa.free(raw); - raw = &.{}; - // Its fit and tint as they were (PdfFit, PdfTint). - const pv = &restored.pdf.?; - if (std.meta.stringToEnum(@TypeOf(pv.fit), im.pdf_fit)) |fit| if (fit != pv.fit) pardes.panes.Pdf.toggleFit(restored); - if (std.meta.stringToEnum(@TypeOf(pv.tint), im.pdf_tint)) |tint| while (pv.tint != tint) pardes.panes.Pdf.toggleTint(restored); - restored.cols = @max(1, src.cols); - restored.rows = @max(1, src.rows); - break :restore_image restored; - } - } - // If the source path is unavailable, retain its bytes - // as an ordinary file rather than dropping the pane. - const path = try gpa.dupe(u8, im.path); - errdefer gpa.free(path); - const content = if (raw.len > 0) raw else try gpa.dupe(u8, ""); - raw = &.{}; - errdefer if (content.len > 0) gpa.free(content); - const history = try pardes.panes.File.History.create(gpa); - errdefer gpa.destroy(history); - const restored = try p.newDocPane(i); - restored.file = .{ .path = path, .content = content, .history = history }; - restored.body.cur_pinned = true; - restored.cols = @max(1, src.cols); - restored.rows = @max(1, src.rows); - p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true, .mode = .baseline_disk } }); - break :restore_image restored; - } - break :restore_image try pardes.panes.Image.restore(p, i, src); - }, - }; - tagline.restoreDumpTail(p, pane, src); + const pane = try restorePane(p, i, src); pane.vweight = src.vweight; pane.collapsed = src.collapsed; } @@ -1049,6 +986,85 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo return p; } +/// Dump pane `src` made a pane again in slot `i`, installed (a fresh +/// serial) and not yet placed: a Restore's, and a closed pane Panes brings +/// back (Store.zig). +pub fn restorePane(p: *Pardes, i: usize, src: Pane) !*pardes.panes.Pane { + const gpa = p.gpa; + const pane: *pardes.panes.Pane = switch (src.kind) { + .terminal => terminal: { + const t = src.terminal.?; + // A host that runs shells gets them back: the old history + // above a new shell in the directory it was in. The web + // shell and an isolated build only ever replay it. + // A command pane comes back finished, showing what it said + // and how it ended: its command is not run again. + const live = comptime (terminal_panes and platform != .web and !isolated); + const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; + const restored = try pardes.panes.terminal.restore(p, src, revive); + p.installPane(i, restored); + try restored.setOwnedCwd(t.cwd); + if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); + if (t.command.len > 0) { + restored.command = try gpa.dupe(u8, t.command); + restored.command_done = true; + restored.command_status = t.status; + } + if (revive) p.emitSpawn(i, restored.serial, t.cwd); + if (t.petscii and pardes.panes.terminal.petscii(restored) == false) pardes.panes.terminal.togglePetscii(restored); + break :terminal restored; + }, + .file => file: { + const restored = try pardes.panes.File.restore(p, i, src); + // A twin: on the earlier pane's buffer again. + if (src.file.?.twin_of) |j| if (j < i) pardes.panes.File.relink(p, j, i, src.file.?.dot); + break :file restored; + }, + .image => restore_image: { + const im = src.image.?; + if (pardes.panes.Pdf.isPath(im.path)) { + var raw: []u8 = if (im.bytes_b64.len > 0) + try decodeBytes(gpa, im.bytes_b64) + else + &.{}; + errdefer if (raw.len > 0) gpa.free(raw); + if (comptime pdf_enabled) { + if (pardes.panes.Pdf.openPane(p, i, im.path, src.scroll + 1, .last) catch null) |restored| { + if (raw.len > 0) gpa.free(raw); + raw = &.{}; + // Its fit and tint as they were (PdfFit, PdfTint). + const pv = &restored.pdf.?; + if (std.meta.stringToEnum(@TypeOf(pv.fit), im.pdf_fit)) |fit| if (fit != pv.fit) pardes.panes.Pdf.toggleFit(restored); + if (std.meta.stringToEnum(@TypeOf(pv.tint), im.pdf_tint)) |tint| while (pv.tint != tint) pardes.panes.Pdf.toggleTint(restored); + restored.cols = @max(1, src.cols); + restored.rows = @max(1, src.rows); + break :restore_image restored; + } + } + // If the source path is unavailable, retain its bytes + // as an ordinary file rather than dropping the pane. + const path = try gpa.dupe(u8, im.path); + errdefer gpa.free(path); + const content = if (raw.len > 0) raw else try gpa.dupe(u8, ""); + raw = &.{}; + errdefer if (content.len > 0) gpa.free(content); + const history = try pardes.panes.File.History.create(gpa); + errdefer gpa.destroy(history); + const restored = try p.newDocPane(i); + restored.file = .{ .path = path, .content = content, .history = history }; + restored.body.cur_pinned = true; + restored.cols = @max(1, src.cols); + restored.rows = @max(1, src.rows); + p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true, .mode = .baseline_disk } }); + break :restore_image restored; + } + break :restore_image try pardes.panes.Image.restore(p, i, src); + }, + }; + tagline.restoreDumpTail(p, pane, src); + return pane; +} + test "a dump keeps the settings that differ from a fresh session's, and a restore applies them" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); diff --git a/src/layout.zig b/src/layout.zig index e674ccbf..efa79394 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1070,6 +1070,32 @@ pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) return true; } +/// A closed pane brought back (Store.reopen) where it was: next to +/// `gainer`, the pane its rows went to when it closed, below it (under its +/// group) or above it, `rows` tall, those rows taken from `gainer` alone, +/// so no other pane moves. False when the gainer is folded or too short +/// to give a pane its minimum and keep its own. +pub fn giveBack(p: *Pardes, id: usize, gainer: usize, below: bool, rows: u16) bool { + const g = p.panes[gainer] orelse return false; + const nw = p.panes[id] orelse return false; + if (g.collapsed) return false; + compute(p); + const f = findPane(p, gainer) orelse return false; + // Its tag wraps at the column's width: measured there. + p.rects[id].w = p.col_w[f.col]; + const gh = p.rects[gainer].h; + const least = minRows(p, id); + const keeps = minRows(p, gainer); + if (gh < least + keeps) return false; + const give = std.math.clamp(rows, least, gh - keeps); + snapColWeights(p, f.col); + insert(p, f.col, if (below) groupEnd(p, f.col, f.idx) else f.idx, id); + g.vweight = @floatFromInt(gh - give); + nw.vweight = @floatFromInt(give); + compute(p); + return true; +} + /// Collapse on an owner with attachments: the whole group folds to its /// tags, every row it gave up to the one unfolded neighbour outside it, /// and unfolds again from that neighbour, as one pane's Collapse does. diff --git a/src/look.zig b/src/look.zig index cd8df4fc..ede7d910 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1813,8 +1813,12 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { switch (found) { .none => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .pane => |t| { - // `@p` names no open pane: a miss, said. - if (t.id >= MAX_PANES or p.panes[t.id] == null) return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); + // `@p` names no open pane: one this session closed comes + // back where it was (Store.reopen), any other is a miss, said. + if (t.id >= MAX_PANES or p.panes[t.id] == null) { + if (p.store.closedAddress(pl.path)) |serial| if (p.store.reopen(p, serial, id)) return; + return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); + } const target = p.panes[t.id].?; // A PDF's page past its last is a miss, as a line past a file's // end is: never the last page in its place (opening one, the diff --git a/src/main.zig b/src/main.zig index 9086fa90..26431324 100644 --- a/src/main.zig +++ b/src/main.zig @@ -707,7 +707,7 @@ fn nativeMain(std_init: std.process.Init) !void { opts.startup_config = found.bytes; opts.startup_config_path = found.path; opts.config_dir = found.dir; - opts.recent_path = recentPath(init.io, arena, init.environ_map); + opts.store_path = storePath(init.io, arena, init.environ_map); if (found.dir) |d| @import("crash.zig").setDir(d); if (detach) |name| { const named = if (name.len != 0) @@ -789,10 +789,11 @@ test { if (comptime pardes.font_picker) _ = @import("fonts.zig"); } -/// Where the list of files opened lately is kept: $XDG_STATE_HOME/pardes -/// /recent, else ~/.local/state/pardes/recent, the directory made if need -/// be; null with no home to keep it in (the list then lasts the session). -fn recentPath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { +/// Where the store every window shares is kept (Store.zig): +/// $XDG_STATE_HOME/pardes/store, else ~/.local/state/pardes/store, the +/// directory made if need be; null with no home to keep it in (Recent and +/// the closed panes then last the session). +fn storePath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { const dir = dir: { if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.fs.path.isAbsolute(base)) break :dir std.fs.path.join(arena, &.{ base, "pardes" }) catch return null; @@ -801,5 +802,5 @@ fn recentPath(io: std.Io, arena: std.mem.Allocator, env: *const std.process.Envi break :dir std.fs.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch return null; }; std.Io.Dir.cwd().createDirPath(io, dir) catch return null; - return std.fs.path.join(arena, &.{ dir, "recent" }) catch null; + return std.fs.path.join(arena, &.{ dir, "store" }) catch null; } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 59ef5ef4..7b107ea7 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1110,6 +1110,10 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { .ctl => ctl.readRoot(p, req), .commands => ctl.readCommands(p, req), .recent => recent: { + // Every window's files: what the others wrote since, read, + // unless a step is out mid-syscall (nothing may change the + // core under it): then the list as it was. + if (pardes.turn.out == 0) p.store.refresh(p); var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); pardes.panes.Output.recentText(p, &text.writer, false) catch break :recent Reply.fail(req.tag, E.NOMEM); p.fs.stage(p.gpa).appendSlice(p.gpa, text.written()) catch break :recent Reply.fail(req.tag, E.NOMEM); diff --git a/src/pardes.zig b/src/pardes.zig index 3c5cf6a7..7f79f094 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -16,6 +16,7 @@ const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); const recent_files = @import("recent.zig"); +const Store = @import("Store.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); pub const edit = @import("edit.zig"); @@ -484,6 +485,7 @@ test { _ = @import("draw.zig"); _ = @import("dump.zig"); // its tests ran nowhere before _ = @import("recent.zig"); + _ = @import("Store.zig"); _ = @import("Presentation.zig"); _ = @import("animation.zig"); _ = @import("pager.zig"); @@ -4326,10 +4328,10 @@ pub const Options = struct { ninep_quic: ?[]const u8 = null, mounts: []const filesystem.Mount = &.{}, config_dir: ?[]const u8 = null, - /// Where the list of files opened lately is kept across sessions - /// (recent.zig), set by the host that has a state directory; none, it - /// lives as long as the session. - recent_path: ?[]const u8 = null, + /// The store every window shares (Store.zig): the files opened lately, + /// the panes closed. Set by the host that has a state directory; none, + /// they last as long as the session. + store_path: ?[]const u8 = null, startup_config_path: ?[]const u8 = null, image_allocator: ?std.mem.Allocator = null, pdf_allocator: ?std.mem.Allocator = null, @@ -4402,6 +4404,9 @@ pub const Pardes = struct { /// The files opened lately, closed ones too (recent.zig): `Recent`, /// /recent, and the jumplist's way back to a closed pane. recent: recent_files.List = .{}, + /// Where Recent is kept, shared with every other window, and the panes + /// this session closed, which Panes brings back (Store.zig). + store: Store = .{}, /// acme's Incl: the directories a look at a name that is nowhere else /// (`stdio.h`, ``) is tried in, in order. The session's, seeded /// with C's (/usr/include, /usr/local/include), kept in a dump. @@ -4410,9 +4415,6 @@ pub const Pardes = struct { /// the next takes. twin_groups: std.ArrayList(panes.File.TwinGroup) = .empty, next_twin: u32 = 1, - /// The kept list was read (or there was none): only then is it written, - /// so a session never writes over one it did not read. - recent_loaded: bool = false, jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, @@ -4852,29 +4854,15 @@ pub const Pardes = struct { return if (comptime hosted) std.heap.smp_allocator else p.gpa; } - /// The kept list of files opened lately, read once at start. + /// The store read once at start: a new session's, Recent from it. pub fn loadRecent(p: *Pardes) void { - const path = p.opts.recent_path orelse return; - if (comptime !hosted) return; - defer p.recent_loaded = true; - const bytes = filesystem.readFile(p.gpa, path) catch return; - defer p.gpa.free(bytes); - p.recent.read(p.recentGpa(), bytes); + p.store = Store.init(p.opts.store_path); + p.store.load(p); } - /// Written out when it changed, at the end of a step and at the end. + /// What changed written out, at the end of a step and at the end. pub fn saveRecent(p: *Pardes) void { - if (!p.recent.dirty) return; - p.recent.dirty = false; - const path = p.opts.recent_path orelse return; - if (comptime !hosted) return; - if (!p.recent_loaded) return; - var out: std.Io.Writer.Allocating = .init(p.gpa); - defer out.deinit(); - p.recent.write(&out.writer) catch return; - turn.yield(); - defer turn.back(); - std.Io.Dir.cwd().writeFile(std.Io.Threaded.global_single_threaded.io(), .{ .sub_path = path, .data = out.written() }) catch {}; + p.store.flush(p, false); } /// A file pane's path and dot, for the recent list (0 when none). @@ -4928,7 +4916,8 @@ pub const Pardes = struct { pub fn deinit(p: *Pardes) void { // Every file open now is closed with its dot, and the list kept. for (p.panes) |slot| if (slot) |pane| p.noteClosed(pane); - p.saveRecent(); + p.store.flush(p, true); + p.store.deinit(p.recentGpa()); p.recent.deinit(p.recentGpa()); for (p.incl.items) |dir| p.gpa.free(dir); p.incl.deinit(p.gpa); @@ -7230,12 +7219,16 @@ pub const Pardes = struct { const owner = layout.ownerOf(p, id); const place = layout.findPane(p, id); const emptied = if (place) |f| (if (p.col_n[f.col] == 1) f.col else null) else null; + // What it was and where, for Panes to bring back (Store.zig). + const kept = p.store.keep(p, id); + errdefer if (kept) |k| k.free(p.recentGpa()); // Before anything is torn down, so a failure here changes nothing. try p.deinitPane(pane); const gainer = layout.absorbVWeight(p, id, owner orelse to); const beside = if (emptied) |c| p.besideColumn(c, p.rects[id]) else null; layout.removePane(p, id); p.panes[id] = null; + if (kept) |k| p.store.close(p, k, gainer); // The finder's last pane takes the column with it. const finder_gone = if (emptied) |c| p.finder.emptied(p, c) else false; if (p.active != id) return; @@ -7257,6 +7250,8 @@ pub const Pardes = struct { } try p.detachCwds(parents[0..count]); for (ids[0..count], parents[0..count]) |closed, pane| { + // Kept for Panes; its column goes, so it comes back as a new pane. + if (p.store.keep(p, closed)) |k| p.store.close(p, k, null); p.retirePane(pane); layout.removePane(p, closed); p.panes[closed] = null; diff --git a/src/recent.zig b/src/recent.zig index 112cb59f..2e3aabde 100644 --- a/src/recent.zig +++ b/src/recent.zig @@ -1,9 +1,11 @@ //! The files opened lately, most recent first, those since closed too, as //! `Recent` lists them and a jump to a closed pane reopens them: a path -//! and where the dot was when it closed. Kept across sessions in a small -//! file under $XDG_STATE_HOME/pardes (Options.recent_path) when the host -//! gives one. acme has nothing like it (its dump and Load are the nearest): -//! a file closed by accident, its path forgotten, is found here again. +//! and where the dot was when it closed. Kept across sessions, and shared +//! by every window, in the store (Store.zig) when the host gives one: each +//! change is a record there, and the records other windows wrote are +//! `note`d here as they are read. acme has nothing like it (its dump and +//! Load are the nearest): a file closed by accident, its path forgotten, +//! is found here again. const std = @import("std"); @@ -22,11 +24,14 @@ pub const Entry = struct { /// cap drops. ponytail: a pane renamed away leaves its old path marked /// open until the session ends; kept rather than tracked by pane. open: bool = false, + /// Changed here since the store last heard of it: written out as a + /// record at the end of the step (Store.flush). + changed: bool = false, }; pub const List = struct { entries: std.ArrayList(Entry) = .empty, - /// Changed since it was last written out. + /// Some entry is `changed`. dirty: bool = false, pub fn deinit(l: *List, gpa: std.mem.Allocator) void { @@ -46,14 +51,8 @@ pub const List = struct { .path = gpa.dupe(u8, path) catch return, }; entry.open = true; - // The oldest closed file goes for it; an open one never does. - if (l.entries.items.len >= cap) { - var i = l.entries.items.len; - while (i > 0) : (i -= 1) if (!l.entries.items[i - 1].open) { - gpa.free(l.entries.orderedRemove(i - 1).path); - break; - }; - } + entry.changed = true; + l.dropOldest(gpa); l.entries.insert(gpa, 0, entry) catch { gpa.free(entry.path); entry = undefined; @@ -80,13 +79,58 @@ pub const List = struct { l.entries.items[i].aline = aline; l.entries.items[i].acol = acol; l.entries.items[i].open = false; + l.entries.items[i].changed = true; l.dirty = true; } + /// Full: the oldest closed file goes, to make room for one more; an + /// open one never does. + fn dropOldest(l: *List, gpa: std.mem.Allocator) void { + if (l.entries.items.len < cap) return; + var i = l.entries.items.len; + while (i > 0) : (i -= 1) if (!l.entries.items[i - 1].open) { + gpa.free(l.entries.orderedRemove(i - 1).path); + return; + }; + } + + /// A record read from the store (another window's, or this one's read + /// again): `path` was opened or closed there last, at that place. It + /// goes first, with that place; whether it is open HERE stays as it + /// was, and nothing is changed for the store to hear again. + pub fn note(l: *List, gpa: std.mem.Allocator, path: []const u8, line: u32, col: u32, aline: u32, acol: u32) void { + if (path.len == 0) return; + var entry: Entry = if (l.find(path)) |i| l.entries.orderedRemove(i) else blk: { + l.dropOldest(gpa); + break :blk .{ .path = gpa.dupe(u8, path) catch return }; + }; + entry.line = line; + entry.col = col; + entry.aline = aline; + entry.acol = acol; + l.entries.insert(gpa, 0, entry) catch { + gpa.free(entry.path); + entry = undefined; + }; + } + + /// This window's changes first again, in their order, after others' + /// records were noted over them: they are written after those, so + /// that is where every window's fold puts them. + pub fn changedFirst(l: *List) void { + var w: usize = 0; + for (0..l.entries.items.len) |i| if (l.entries.items[i].changed) { + const e = l.entries.items[i]; + std.mem.copyBackwards(Entry, l.entries.items[w + 1 .. i + 1], l.entries.items[w..i]); + l.entries.items[w] = e; + w += 1; + }; + } + /// A copy, for the session a Restore makes: its files closed until it /// opens them again. Out of memory, what was copied so far. pub fn clone(l: *const List, gpa: std.mem.Allocator) List { - var copy: List = .{ .dirty = true }; + var copy: List = .{ .dirty = l.dirty }; for (l.entries.items) |e| { const path = gpa.dupe(u8, e.path) catch break; var kept = e; @@ -105,14 +149,19 @@ pub const List = struct { } /// One line a file, ` `, most recent - /// first. + /// first: the old `recent` file, and a store record's body, a line. pub fn write(l: *const List, w: *std.Io.Writer) !void { + for (l.entries.items) |e| try writeEntry(e, w); + } + + pub fn writeEntry(e: Entry, w: *std.Io.Writer) !void { // A name with a newline in it would read back as two lines: not kept. - for (l.entries.items) |e| if (std.mem.indexOfScalar(u8, e.path, '\n') == null) + if (std.mem.indexOfScalar(u8, e.path, '\n') == null) try w.print("{d} {d} {d} {d} {s}\n", .{ e.line, e.col, e.aline, e.acol, e.path }); } - /// The lines `write` wrote; a line that is not one is passed over. + /// The lines `write` wrote (the old `recent` file), each changed for + /// the store to hear of; a line that is not one is passed over. pub fn read(l: *List, gpa: std.mem.Allocator, bytes: []const u8) void { var lines = std.mem.splitScalar(u8, bytes, '\n'); while (lines.next()) |line| { @@ -131,11 +180,25 @@ pub const List = struct { const path = rest; if (path.len == 0 or path[0] != '/' or l.find(path) != null) continue; const owned = gpa.dupe(u8, path) catch return; - l.entries.append(gpa, .{ .path = owned, .line = nums[0], .col = nums[1], .aline = nums[2], .acol = nums[3] }) catch { + l.entries.append(gpa, .{ .path = owned, .line = nums[0], .col = nums[1], .aline = nums[2], .acol = nums[3], .changed = true }) catch { gpa.free(owned); return; }; + l.dirty = true; + } + } + + /// One record's body read back: ` `. + pub fn parseLine(line: []const u8) ?struct { nums: [4]u32, path: []const u8 } { + var nums: [4]u32 = @splat(0); + var rest = line; + for (&nums) |*n| { + const sp = std.mem.indexOfScalar(u8, rest, ' ') orelse return null; + n.* = std.fmt.parseInt(u32, rest[0..sp], 10) catch return null; + rest = rest[sp + 1 ..]; } + if (rest.len == 0 or rest[0] != '/') return null; + return .{ .nums = nums, .path = rest }; } }; diff --git a/test/fs.py b/test/fs.py index 841dd32a..c0f0995c 100644 --- a/test/fs.py +++ b/test/fs.py @@ -711,7 +711,7 @@ def recent_survives_restart(binary): assert f'open {kept}\n' in client.read('/recent').decode() client.write(f'/pane/{serial}/ctl', b'Del\n') assert f'closed {kept}\n' in client.read('/recent').decode(), client.read('/recent') - assert (root / '.local' / 'state' / 'pardes' / 'recent').exists() + assert (root / '.local' / 'state' / 'pardes' / 'store').exists() with session(binary, root, 'recent2') as (client, _): listed = client.read('/recent').decode() assert f'closed {kept}\n' in listed, listed @@ -726,6 +726,45 @@ def recent_survives_restart(binary): assert f'open {kept}\n' in client.read('/recent').decode() +def del_twice(client, serial): + """Del, and again when the first refused over unsaved text.""" + try: + client.write(f'/pane/{serial}/ctl', b'Del\n') + except OSError: + client.write(f'/pane/{serial}/ctl', b'Del\n') + + +def store_shared_between_windows(binary): + """Two windows share one store (Store.zig): a file opened in one is in + the other's /recent at its next read, with no restart; a pane Del'd in + one comes back where it was from a look at its @p serial there, its text + with it, and only there.""" + with tempfile.TemporaryDirectory(prefix='pardes-store-') as directory: + root = Path(directory) + shared = root / 'shared.txt' + shared.write_bytes(b'one\ntwo\nthree\n') + with session(binary, root, 'store1') as (one, _), session(binary, root, 'store2') as (two, _): + serial = look(one, f'{shared}:3') + assert f'open {shared}\n' in one.read('/recent').decode() + assert f'closed {shared}\n' in two.read('/recent').decode(), two.read('/recent') + one.write(f'/pane/{serial}/ctl', b'Del\n') + assert f'closed {shared}\n' in one.read('/recent').decode() + scratch = new_pane(one, b'kept across a Del\n') + del_twice(one, scratch) + assert str(scratch) not in [row.split()[0] for row in one.read('/index').decode().splitlines()] + back = look(one, f'@p{scratch}') + assert one.read(f'/pane/{back}/body') == b'kept across a Del\n' + # The other window's session closed no such pane. + source = new_pane(two, b'') + try: + two.write(f'/pane/{source}/look', f'@p{scratch}\n'.encode()) + except OSError: + pass + assert b'kept across a Del' not in b''.join(two.read(f'/pane/{row.split()[0]}/body') + for row in two.read('/index').decode().splitlines()) + assert (root / '.local' / 'state' / 'pardes' / 'store').exists() + + def workflow_canary(binary): """One session driven as the dogfood agents drive it, asserting the log and the read-backs at every step: the canary for the main paths (the @@ -1163,6 +1202,7 @@ def test(binary, quic=False): putall_answers_after_its_saves(binary) workflow_canary(binary) recent_survives_restart(binary) + store_shared_between_windows(binary) python_repl_runs_one_line(binary) signal_cleans_up(binary) for options, message in [ -- cgit v1.3 From bfdc8a9e61dd20c91b68f62187e724d1a98445a4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 25 Oct 2026 10:27:05 -0300 Subject: query: a language server's list is answered, not typed: one place lands on it (Diagnostics too now), the place fed as the text's places so it is tinted and n/N have it, no query pane; several open the list with the keyboard on its current row in normal mode (showCurrent: the caret on the rows is the current row, n/N take it there), its target shown, Esc in it back to the text as it was; none is a message; line 1 keeps its word as text; Diagnostics keep the keyboard in the text for ]d; lsp-client and lsprelpath step with n, their goldens the caret on the row and no insert marker Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016u3hBPFfja5pK4EBRC1UVD --- docs/search-proto-converge.md | 12 +++++ docs/typ/guide.typ | 2 +- src/Query.zig | 95 ++++++++++++++++++++++++++++++++++++++-- src/pardes.zig | 13 +++++- test/output.zig | 6 ++- test/snapshots/lsp-client.golden | 4 +- test/snapshots/lsp-client.snap | 10 +++-- test/snapshots/lsprelpath.golden | 8 ++-- test/snapshots/lsprelpath.snap | 7 +-- 9 files changed, 136 insertions(+), 21 deletions(-) (limited to 'src/Query.zig') diff --git a/docs/search-proto-converge.md b/docs/search-proto-converge.md index 4c7b7006..af9068a0 100644 --- a/docs/search-proto-converge.md +++ b/docs/search-proto-converge.md @@ -56,6 +56,18 @@ end without a word; with no places (or after an `s` changed the register) they are helix's register search as before. `]d` / `[d` step the diagnostics' places once a Diagnostics query fed them. +**A language server's list is answered, not typed.** `gd`, `gr`, `gi` +and `SPC l d` ask; the answer decides: one place is a jump (the keyboard +on it, the place that text's places, so it is tinted and n/N have it; no +query pane); several open the query pane with its rows there and the +keyboard in its normal mode on the current row (the first after where it +was asked), its target shown, so j/k/n/N step, Enter lands and Esc goes +back to the text as it was; none is a message. Line 1 reads `Refs` as text +(B2 asks again; editing it to `/x` works), but no language key puts the +keyboard there in insert mode. Diagnostics keep the keyboard in the text +so `]d`/`[d` step their places. `Symbols` (`SPC s s`) is fuzzy, typed +into: a query. + **The current row shows its target**, the keyboard staying on line 1: a place in an open pane's text is selected there and scrolled into view (remembered for Esc); a file an open pane shows, its line there; any other diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index d479a884..4b783c64 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -193,7 +193,7 @@ Line 1's first word names what it searches, and editing the word changes it: [`Panes name`], [the open panes, then the ones closed this session, `(closed)` and dimmer: #key("Enter") (or a #word("Look") at its `@pN`) brings one back where it was, its text with it (#key("SPC b b"), #word("Panes"))], [`Symbols name`], [the text's declarations (#key("SPC s s"))], [`All pat`], [every open pane's text, its rows under each pane (#key("SPC /"))], - [`Refs`, `Def`, `Impl`, `Diagnostics`], [the language server's lists; their places in the text tinted as a `/`'s are, `]d` stepping the diagnostics], + [`Refs`, `Def`, `Impl`, `Diagnostics`], [the language server's lists (#key("gr"), #key("gd"), #key("gi"), #key("SPC l d")): one answer is a jump, none a message; several open the list with the keyboard on its current row in normal mode (#keys("j", "k", "n", "N") step it, #key("Enter") lands, #key("Esc") goes back), the diagnostics' keeping it in the text for `]d`; their places in the text tinted as a `/`'s are], ) A row in a file no pane shows is shown in a `+Preview` under the query diff --git a/src/Query.zig b/src/Query.zig index 98419c7b..2ab687ee 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -1201,9 +1201,25 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v const line = lineOne(rp.file.?.content); const a = parse(line) orelse return; makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); - // A list to pick from, typed into; diagnostics are a jump (]d): the - // keyboard stays on the place in the text. - if (source != .diagnostics) toLineOne(p, qid) else p.active = owner_id; + // Diagnostics are a jump (]d): the keyboard stays on the place in the + // text. The others are a list answered, not a query typed: the keyboard + // on the current row in normal mode (j, k, n, N step, Enter lands, Esc + // goes back), line 1 left as text for whoever wants to edit it. + if (source == .diagnostics) { + p.active = owner_id; + return; + } + tagline.exitHeader(p); + p.active = qid; + if (layout.findPane(p, qid)) |at| p.setActiveColumn(at.col); + rp.focus = .body; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + t.vsel.active = false; + t.nsel = 0; + t.cur_row = @intCast((q.current orelse 0) + 1); + showCurrent(rp); + showTarget(p, qid); } fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { @@ -1334,12 +1350,25 @@ fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anyt /// is current. Scrolled into view, line 1 kept when it can be. fn showCurrent(rp: *Pane) void { const q = rp.query orelse return; - if (rp.body.cur_row != 0 and rp.focus == .body) return; + const on_rows = rp.body.cur_row != 0 and rp.focus == .body; + if (on_rows and rp.body.mode != .normal) return; const c = q.current orelse { rp.body.msel.active = false; return; }; const r: i32 = @intCast(c + 1); + if (on_rows) { + // The keyboard on the rows is the current row: n and N take it there. + rp.body.msel.active = false; + rp.body.cur_row = r; + rp.body.cur_col = 0; + rp.body.cur_pinned = true; + q.seen_row = r; + const off = rp.scroll(); + const shown = off + @as(i32, rp.rows) - 1; + if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); + return; + } rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; // Typed into, line 1 stays in view whatever the current row: what you // type is never scrolled away (the live rows start just before the @@ -1821,6 +1850,12 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { step(p, id, if (k.cp == 'n') 1 else -1); return true; } + // A language server's list, live: Esc is back to the text it was + // asked in, every view as it was. + if (hit(k, config.escape) and !q.frozen and q.lsp_rows.len > 0 and t.nsel == 0 and !t.vsel.active) { + cancel(p, id); + return true; + } if (hit(k, config.look_key) and t.cur_row > 0) { const i: usize = @intCast(t.cur_row - 1); if (i >= q.items.items.len or q.items.items[i].kind != .hit) return false; @@ -2341,3 +2376,55 @@ fn queryPane2(p: *Pardes, not: usize) ?usize { for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i; return null; } + +test "a language server's list: one answer lands with no pane, several open the list in normal mode on the current row, none is a message, Esc goes back" { + const lsp = pardes.lsp; + if (!lsp.supports.contains(.references) or !lsp.supports.contains(.diagnostics)) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalpha two\ngamma\nalpha three\n"); + const npanes = struct { + fn of(pp: *Pardes) usize { + var n: usize = 0; + for (pp.panes) |slot| n += @intFromBool(slot != null); + return n; + } + }.of; + // One: the keyboard on it, no pane, the place tinted and n's. + p.lspRequest(0, .references, ""); + p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "/test.txt:3:1-5 alpha two\n" } }); + try std.testing.expectEqual(@as(usize, 1), npanes(p)); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try std.testing.expectEqual(@as(usize, 1), pane.places.hits.items.len); + try std.testing.expectEqual(Places.Hit{ .start = 15, .end = 20 }, pane.places.hits.items[0]); + // None: a message, no pane. + p.lspRequest(0, .diagnostics, ""); + p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "" } }); + try std.testing.expectEqual(@as(usize, 1), npanes(p)); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "none") != null); + // Several: the list open, the keyboard in it in normal mode on the + // current row, which the text shows; line 1 as text. + pane.body.cur_row = 0; + pane.body.cur_col = 0; + p.lspRequest(0, .references, ""); + p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "/test.txt:1:1-5 alpha one\n/test.txt:3:1-5 alpha two\n/test.txt:5:1-5 alpha three\n" } }); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + try std.testing.expectEqual(qid, p.active); + try std.testing.expect(qp.body.mode == .normal); + try std.testing.expect(std.mem.startsWith(u8, qp.file.?.content, "Refs")); + try std.testing.expectEqual(@as(i32, @intCast(q.current.? + 1)), qp.body.cur_row); + try std.testing.expectEqual(@as(usize, 3), pane.places.hits.items.len); + const first = pane.places.current.?; + // n steps the rows, the caret with them, the text following. + typeKeys(p, "n"); + try std.testing.expectEqual(@as(i32, @intCast(q.current.? + 1)), qp.body.cur_row); + try std.testing.expectEqual(first + 1, pane.places.current.?); + // Esc: back to the text, as it was, the list gone. + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); +} diff --git a/src/pardes.zig b/src/pardes.zig index a23039ef..a35d1604 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -7093,11 +7093,22 @@ pub const Pardes = struct { const from: panes.Output.Origin = .{ .query = w.kind }; const nrows = std.mem.count(u8, rows, "\n"); - if (panes.Output.traits(from).jumps and nrows == 1) { + if ((panes.Output.traits(from).jumps or w.kind == .diagnostics) and nrows == 1) { const ln = std.mem.trimEnd(u8, rows, "\n"); const place = ln[0..panes.Output.location(ln).end]; p.look_missed = false; look.lookAt(p, w.pane, place); + // The one place is the text's places, as a list's would be: tinted, + // and n and N step it. + const spot = look.parsePathLine(place); + if (!p.look_missed and spot.at.line > 0) if (p.panes[p.active]) |there| if (there.file) |*tf| if (spot.at.line <= panes.File.nlines(p.gpa, tf)) { + const ls = panes.File.lineStart(p.gpa, tf, spot.at.line - 1); + const line = tf.content[ls .. std.mem.indexOfScalarPos(u8, tf.content, ls, '\n') orelse tf.content.len]; + const col = @min(spot.at.col -| 1, line.len); + // To its end when the server said it, else the word there. + const end = if (spot.at.end_line == spot.at.line and spot.at.end_col > col) @min(spot.at.end_col, line.len) else if (look.expandedWord(line, col)) |word| word.hi else col + 1; + if (ls + end <= tf.content.len) there.places.feed(p, there, 0, &.{.{ .start = ls + col, .end = ls + end }}, ls + col); + }; // A word that asks for a list (Callers, Refs) with one answer // jumps to it with no list: where it went is said, as the list // would have shown it. A definition's jump is the answer itself. diff --git a/test/output.zig b/test/output.zig index 8eb389c8..530db77c 100644 --- a/test/output.zig +++ b/test/output.zig @@ -219,9 +219,11 @@ test "references fill the asking text's query pane: sorted under their files, th try std.testing.expectEqual(@as(?usize, 2), source.places.current); try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); try std.testing.expectEqual(@as(usize, 6), results.query.?.total); - // Ctrl-n on line 1, Enter: the keyboard on that ref in the text + // A list answered, not a query typed: the keyboard on its current row in + // normal mode; n, Enter: the keyboard on that ref in the text try std.testing.expectEqual(qid, p.active); - p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expect(results.body.mode == .normal and results.body.cur_row > 0); + p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(@as(?usize, 3), source.places.current); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(@as(usize, 0), p.active); diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 18ccd775..f3d7006e 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -15,9 +15,9 @@ | 3 a + b | 4 } | 5 -== snap gr-list grid=100x25 cursor=7,14 +== snap gr-list grid=100x25 cursor=2,16 |3: 1 mod lib; -|13: ^ +Search 1/3 Del +|13: +Search 1/3 Del |14: Refs |15: lib.rs |16: 2 pub fn add(a: i32, b: i32) -> i32 { diff --git a/test/snapshots/lsp-client.snap b/test/snapshots/lsp-client.snap index d9827a2a..159bf80e 100644 --- a/test/snapshots/lsp-client.snap +++ b/test/snapshots/lsp-client.snap @@ -7,7 +7,8 @@ # and the message row still carries the server's settled state # ("lsp lspmock: ready") because nothing has cleared it yet. # gr -> the text's query pane, line 1 `Refs`, rows under their files, -# the next occurrence current; n/N step the places in the text. +# the next occurrence current, the keyboard on it in normal mode +# (a list answered, not a query typed); n/N step the places. file main.rs mod lib;\n\nfn main() {\n let x = add(1, 2);\n let y = add(3, 4);\n let _ = x + y;\n}\n file lib.rs // mock fixture\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n start 25 100 main.rs @@ -27,9 +28,10 @@ key r wait 10000 add(3, 4) stable 700 15000 snap gr-list -# Ctrl-n on line 1 steps to the next hit, Enter lands there; N in the text -# goes back to the one before, round the places in main.rs -key c-n +# the list opens in normal mode, the caret on the current row: n steps to +# the next hit, Enter lands there; N in the text goes back to the one +# before, round the places in main.rs +key n key enter stable 700 15000 snap gr-opened diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 59a3c5d0..6351de03 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,4 +1,4 @@ -== snap absrow grid=100x35 cursor=7,17 +== snap absrow grid=100x35 cursor=2,21 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse TreeContext Def Refs Del @@ -15,7 +15,7 @@ | | | -|^ +Search 2/2 Del +| +Search 2/2 Del | Refs | /tmp/pardes-snap/lsprelpath/cwd/shade.zig | 1 pub const Shade = enum { @@ -72,7 +72,7 @@ |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, -== snap subrow grid=100x35 cursor=7,17 +== snap subrow grid=100x35 cursor=2,21 | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse TreeContext Def Refs Del @@ -89,7 +89,7 @@ | | | -|^ +Search 2/2 Del +| +Search 2/2 Del | Refs | inner/tint.zig | 1 pub const Tint = enum { diff --git a/test/snapshots/lsprelpath.snap b/test/snapshots/lsprelpath.snap index 8420e134..70ca3fdc 100644 --- a/test/snapshots/lsprelpath.snap +++ b/test/snapshots/lsprelpath.snap @@ -44,8 +44,9 @@ wait 15000 cwd/shade.zig stable 700 15000 snap absrow # the current row is parent.zig's own; the one before it is shade.zig's, -# shown in the +Preview, which Enter makes shade.zig's pane -key c-p +# shown in the +Preview (N, the list in normal mode), which Enter makes +# shade.zig's pane +key N wait 10000 verdigris stable 700 15000 key enter @@ -63,7 +64,7 @@ key r wait 15000 inner/tint.zig stable 700 15000 snap subrow -key c-p +key N wait 10000 ochre stable 700 15000 key enter -- cgit v1.3 From b8646ef838e4f33f1f3adbf3c08c251afc39ae73 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 25 Oct 2026 10:46:46 -0300 Subject: query: B1 on a query pane is acme's B1: it places the caret and selects, nothing else (no other pane moves, nothing is previewed, the current row stays); only the keyboard moves the current row: Ctrl-n/Ctrl-p typing, n/N in the pane's normal mode (the caret with them, caretTo), j/k taking the caret onto a row (produce follows the caret on a key step only); Enter lands the current row; the current row's line mark is no selection B2/B3 borrow (exec.operandAt), so a click on it takes the word as on any row Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016u3hBPFfja5pK4EBRC1UVD --- docs/search-proto-converge.md | 17 +++++-- docs/typ/guide.typ | 7 ++- src/Query.zig | 116 ++++++++++++++++++++++++++++++++---------- src/exec.zig | 4 +- src/mouse.zig | 2 +- src/pardes.zig | 2 +- 6 files changed, 113 insertions(+), 35 deletions(-) (limited to 'src/Query.zig') diff --git a/docs/search-proto-converge.md b/docs/search-proto-converge.md index af9068a0..2e992e3c 100644 --- a/docs/search-proto-converge.md +++ b/docs/search-proto-converge.md @@ -50,8 +50,9 @@ own, and its rows are read-only while live (queryline's clampEdit). **Keys** on line 1, typing: Ctrl-n / Ctrl-p (and Down / Up, `config.query_next` / `query_prev`) step the current row; Enter lands; Esc cancels. Tab stays the -exec chord. In the pane's normal mode (live or frozen): n / N step its rows, -Enter on a row lands on it. In the owner: n / N step its places, round the +exec chord. In the pane's normal mode (live or frozen): n / N step its rows +(the caret with them when it is on them), j / k onto a row make it current, +Enter lands the current row. In the owner: n / N step its places, round the end without a word; with no places (or after an `s` changed the register) they are helix's register search as before. `]d` / `[d` step the diagnostics' places once a Diagnostics query fed them. @@ -71,7 +72,17 @@ into: a query. **The current row shows its target**, the keyboard staying on line 1: a place in an open pane's text is selected there and scrolled into view (remembered for Esc); a file an open pane shows, its line there; any other -file in the +Preview. Never the pointer. +file in the +Preview. Only the keyboard moves it: Ctrl-n / Ctrl-p on line +1, n / N in the pane's normal mode, and j / k taking the caret onto a row +(a helix picker's preview follows its selection the same way). The mouse +never does: B1 (a click, a sweep, the chords) places the caret and selects +as in any pane, no other pane moves, nothing is previewed; B3 on a row's +address is a Look as anywhere, on its code a word Look; B2 on line 1 runs +it again. Enter lands the current row, which is the caret's once j / k put +it there, never a row B1 only clicked; Callstack has no current row apart +from its caret, so the two agree except after a click. The current row's +line mark is no selection: B2 / B3 on it take the word clicked, as on any +row. **Enter** puts the keyboard on the current hit in its pane (the +Preview promoted in place: same slot, serial, rect, an unattached file pane from diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 4b783c64..40fc7af9 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -197,8 +197,11 @@ Line 1's first word names what it searches, and editing the word changes it: ) A row in a file no pane shows is shown in a `+Preview` under the query -pane, following #keys("Ctrl-n", "Ctrl-p") and #btn("B1"), never the -pointer; #key("Enter") makes the preview that file's pane where it stands. +pane. The current row follows the keyboard only (#keys("Ctrl-n", "Ctrl-p") +typing, #keys("n", "N") and #keys("j", "k") in the pane's normal mode); +#btn("B1") on the rows places the caret and selects, as in any pane, and +moves nothing else. #key("Enter") lands the current row, making the +preview that file's pane where it stands. #btn("B3") on a row's line number looks at the row; #btn("B2") on line 1 runs it again. The next search from the same pane reuses its query pane, its kept rows back on #key("Esc") (#word("SearchPane") `new`: a pane each; diff --git a/src/Query.zig b/src/Query.zig index 2ab687ee..a5d33cf4 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -145,7 +145,8 @@ made_rev: u32 = 0, /// The owner's revision seen last tick: rows follow an edit of the owner /// once it has stood a frame (the rows refresh on idle frames). seen_rev: u32 = 0, -/// The body cursor's row as last seen: B1, j or k on a row makes it current. +/// The body cursor's row as last seen: j or k onto a row makes it current +/// (a caret B1 put there is only a caret). seen_row: i32 = 0, /// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits. window: struct { lo: usize = 0, hi: usize = 0 } = .{}, @@ -274,7 +275,7 @@ pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: boo // Every view as the search found it, for Esc to put back. owner.places.remember(p, owner); // Before the first key: a names source lists every candidate at once. - produce(p, id, false); + produce(p, id, false, false); // What a 9P exec reads back: the pane it filled (ninep/ctl.zig). p.fs.refilled = p.panes[id].?.serial; if (focus) toLineOne(p, id) else p.active = from; @@ -397,11 +398,11 @@ fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { /// source has something new, has its rows made again. A walk takes a slice /// on a tick. Nothing here is synchronous with an edit of the owner: its /// places shift (Places.shift) and the rows follow once it stands a frame. -pub fn produceAll(p: *Pardes, tick: bool) void { +pub fn produceAll(p: *Pardes, tick: bool, keyed: bool) void { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; if (pane.query == null) continue; - produce(p, id, tick); + produce(p, id, tick, keyed); } } @@ -416,7 +417,9 @@ pub fn busy(p: *const Pardes) bool { return false; } -fn produce(p: *Pardes, id: usize, tick: bool) void { +/// `keyed`: this step was a key, so a caret moved onto a row (j, k) makes +/// it current; a caret B1 placed is only a caret. +fn produce(p: *Pardes, id: usize, tick: bool, keyed: bool) void { const rp = p.panes[id] orelse return; const q = rp.query orelse return; const f = if (rp.file) |*file| file else return; @@ -445,10 +448,12 @@ fn produce(p: *Pardes, id: usize, tick: bool) void { if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked); } const a = asked orelse return noteRows(p, id, " line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n"); - // A row clicked or stepped onto (B1, j, k): current, and shown. + // A row stepped onto (j, k): current, and shown. One B1 put the caret + // on is not: B1 places the caret and selects, nothing else, as on any + // text; no other pane moves. if (rp.body.cur_row != q.seen_row) { q.seen_row = rp.body.cur_row; - if (rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { + if (keyed and rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { const i: usize = @intCast(rp.body.cur_row - 1); if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true); } @@ -1217,8 +1222,7 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v if (t.mode == .insert) edit.exitInsert(p, t); t.vsel.active = false; t.nsel = 0; - t.cur_row = @intCast((q.current orelse 0) + 1); - showCurrent(rp); + caretTo(rp, q.current orelse 0); showTarget(p, qid); } @@ -1350,25 +1354,12 @@ fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anyt /// is current. Scrolled into view, line 1 kept when it can be. fn showCurrent(rp: *Pane) void { const q = rp.query orelse return; - const on_rows = rp.body.cur_row != 0 and rp.focus == .body; - if (on_rows and rp.body.mode != .normal) return; + if (rp.body.cur_row != 0 and rp.focus == .body) return; const c = q.current orelse { rp.body.msel.active = false; return; }; const r: i32 = @intCast(c + 1); - if (on_rows) { - // The keyboard on the rows is the current row: n and N take it there. - rp.body.msel.active = false; - rp.body.cur_row = r; - rp.body.cur_col = 0; - rp.body.cur_pinned = true; - q.seen_row = r; - const off = rp.scroll(); - const shown = off + @as(i32, rp.rows) - 1; - if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); - return; - } rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; // Typed into, line 1 stays in view whatever the current row: what you // type is never scrolled away (the live rows start just before the @@ -1382,6 +1373,19 @@ fn showCurrent(rp: *Pane) void { if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); } +/// The caret on item `i`'s row, the row in view: the current row's own +/// mark from here (the line selection is for the caret on line 1). +fn caretTo(rp: *Pane, i: usize) void { + const r: i32 = @intCast(i + 1); + rp.body.msel.active = false; + rp.body.cur_row = r; + rp.body.cur_col = 0; + rp.body.cur_pinned = true; + rp.query.?.seen_row = r; + const off = rp.scroll(); + if (r >= off + @as(i32, rp.rows)) rp.scrollBy(r - off - @as(i32, rp.rows) + 1) else if (r < off) rp.scrollBy(r - off); +} + /// The line (0-based) of byte `at` of `f`'s text. fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize { const index = File.lineIndex(p.gpa, f) catch return 0; @@ -1848,6 +1852,11 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; if (k.cp == 'n' or k.cp == 'N') { step(p, id, if (k.cp == 'n') 1 else -1); + // The caret on the rows goes to the current row, as j and k + // would have taken it there. + if (t.cur_row != 0) if (q.current) |c| { + caretTo(rp, c); + }; return true; } // A language server's list, live: Esc is back to the text it was @@ -1856,10 +1865,10 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { cancel(p, id); return true; } - if (hit(k, config.look_key) and t.cur_row > 0) { - const i: usize = @intCast(t.cur_row - 1); - if (i >= q.items.items.len or q.items.items[i].kind != .hit) return false; - land(p, id, i); + // Enter lands the current row: the caret's when j or k took it + // there, never one a B1 only put the caret on. + if (hit(k, config.look_key) and t.cur_row > 0 and q.current != null) { + land(p, id, null); return true; } return false; @@ -2428,3 +2437,56 @@ test "a language server's list: one answer lands with no pane, several open the try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); } + +test "B1 on a query pane's rows places the caret and selects, nothing else; j, k and n make a row current, Enter lands the current" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + typeKeys(p, "/alpha"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + p.acknowledgePanelPresentation(&.{}); + const owner_sel = pane.body.primaryRange(pane.file.?.content, 0); + const owner_scroll = pane.file.?.scroll; + const current = q.current; + const place = pane.places.current; + const r = p.rects[qid]; + const y = r.y + qp.tag_rows + 3; + const x = r.x + config.GUTTER + File.gutterWidth(qp) + 6; + // a click: the caret there, the current row and every other pane as they were + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = y } }); + try std.testing.expectEqual(@as(i32, 3), qp.body.cur_row); + try std.testing.expectEqual(current, q.current); + try std.testing.expectEqual(place, pane.places.current); + try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0)); + try std.testing.expectEqual(owner_scroll, pane.file.?.scroll); + try std.testing.expect(p.panes[qid] != null and queryPane2(p, qid) == null); + // a sweep selects the text it went over, and nothing else + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = x + 4, .row = y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x + 4, .row = y } }); + const swept = qp.sel[@backingInt(config.select_button)]; + try std.testing.expect(swept.state == .done and swept.r0 == swept.r1 and swept.c1 - swept.c0 == 4); + try std.testing.expectEqual(current, q.current); + try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0)); + // the keyboard: j onto the next row makes it current, the text follows + p.active = qid; + if (qp.body.mode == .insert) p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] != null); + typeKeys(p, "j"); + try std.testing.expectEqual(@as(i32, 4), qp.body.cur_row); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + // n round the end: the caret goes with the current row + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + try std.testing.expectEqual(@as(i32, 1), qp.body.cur_row); + // B1 elsewhere, then Enter: the current row lands, not the caret's + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = y } }); + p.active = qid; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); +} diff --git a/src/exec.zig b/src/exec.zig index 5b0eb204..7248632b 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -182,7 +182,9 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l result.text = edit.currentSelText(p, pane); return result; } - if (pane.body.msel.active and row >= @min(pane.body.msel.r0, pane.body.msel.r1) and + // A query pane's line selection is its current row's mark, not a + // selection made: a click on that row takes its word, as on any row. + if (pane.body.msel.active and pane.query == null and row >= @min(pane.body.msel.r0, pane.body.msel.r1) and row <= @max(pane.body.msel.r0, pane.body.msel.r1)) { result.text = edit.currentSelText(p, pane); diff --git a/src/mouse.zig b/src/mouse.zig index d8f19059..2ff4fef3 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1104,7 +1104,7 @@ pub fn dispatchPointerBuiltin( p.gpa.free(q.asked); q.asked = &.{}; q.frozen = false; - panes.Query.produceAll(p, false); + panes.Query.produceAll(p, false, false); return; }; // A middle click on a body is the exec a bound REPL may take. diff --git a/src/pardes.zig b/src/pardes.zig index a35d1604..20415e69 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -6204,7 +6204,7 @@ pub const Pardes = struct { // step the ones an edit or a scroll left unfound in the view. for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); // Each live query pane's rows, made from what changed this step. - panes.Query.produceAll(p, ev == .tick); + panes.Query.produceAll(p, ev == .tick, ev == .key); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); -- cgit v1.3 From 4122224f07735a90dac8f2037f14b7d44b259fce Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 25 Oct 2026 10:55:04 -0300 Subject: query: the current row's mark is its own: a row tint the width of the body drawn from Query.current before the row's colours (Query.paintMark, so its match's tint, the places and any selection draw over it), not the pane's line selection; a click, a sweep or a chord never erases it and B2/B3 never borrow it (the operandAt exception goes); fsearch, lookrange, lsprelpath, stepgrain goldens: the current row now marked under its match tint, while typing too Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016u3hBPFfja5pK4EBRC1UVD --- docs/search-proto-converge.md | 5 +-- src/Query.zig | 75 +++++++++++++++++++++++++--------------- src/body_layer.zig | 1 + src/exec.zig | 4 +-- test/snapshots/fsearch.golden | 2 +- test/snapshots/lookrange.golden | 4 ++- test/snapshots/lsprelpath.golden | 4 +-- test/snapshots/stepgrain.golden | 4 +-- 8 files changed, 61 insertions(+), 38 deletions(-) (limited to 'src/Query.zig') diff --git a/docs/search-proto-converge.md b/docs/search-proto-converge.md index 2e992e3c..99adbc2c 100644 --- a/docs/search-proto-converge.md +++ b/docs/search-proto-converge.md @@ -81,8 +81,9 @@ address is a Look as anywhere, on its code a word Look; B2 on line 1 runs it again. Enter lands the current row, which is the caret's once j / k put it there, never a row B1 only clicked; Callstack has no current row apart from its caret, so the two agree except after a click. The current row's -line mark is no selection: B2 / B3 on it take the word clicked, as on any -row. +mark is its own, a row tint drawn from the current row under the match's +tint (`Query.paintMark`), no selection: a click, a sweep or a chord never +erases it and B2 / B3 on it take the word clicked, as on any row. **Enter** puts the keyboard on the current hit in its pane (the +Preview promoted in place: same slot, serial, rect, an unattached file pane from diff --git a/src/Query.zig b/src/Query.zig index a5d33cf4..11db8579 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -1349,18 +1349,15 @@ fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anyt // ---- the current row ---- -/// The current row drawn as the visited row is (a line selection), while -/// the keyboard is on line 1 or elsewhere; on the rows, the cursor itself -/// is current. Scrolled into view, line 1 kept when it can be. +/// The current row scrolled into view while the keyboard is on line 1 or +/// elsewhere, line 1 kept when it can be. Its mark is `paint`'s, drawn +/// from `current`: no selection, so no click, sweep or chord clears it and +/// no B2 or B3 borrows it. fn showCurrent(rp: *Pane) void { const q = rp.query orelse return; if (rp.body.cur_row != 0 and rp.focus == .body) return; - const c = q.current orelse { - rp.body.msel.active = false; - return; - }; + const c = q.current orelse return; const r: i32 = @intCast(c + 1); - rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; // Typed into, line 1 stays in view whatever the current row: what you // type is never scrolled away (the live rows start just before the // current one, so it sits under line 1). Frozen, the row is scrolled to. @@ -1373,11 +1370,9 @@ fn showCurrent(rp: *Pane) void { if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); } -/// The caret on item `i`'s row, the row in view: the current row's own -/// mark from here (the line selection is for the caret on line 1). +/// The caret on item `i`'s row, the row in view. fn caretTo(rp: *Pane, i: usize) void { const r: i32 = @intCast(i + 1); - rp.body.msel.active = false; rp.body.cur_row = r; rp.body.cur_col = 0; rp.body.cur_pinned = true; @@ -1941,6 +1936,25 @@ pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![ return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more }); } +/// The current row's mark: a tint the width of the body, painted before +/// the row's colours, so its match's tint, the places' and any selection +/// draw over it. Its own, from `current`: no click, sweep or chord clears +/// it, no B2 or B3 borrows it. +pub fn paintMark(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const q = pane.query orelse return; + const c = q.current orelse return; + const th = p.theme(); + const mark = colors.mix(th.bg orelse th.tag_bg, th.sel_bg); + const tx = r.x + config.GUTTER; + const tw = r.w -| config.GUTTER; + const col = File.gutterWidth(pane); + var row: i32 = 0; + while (row < body_h) : (row += 1) { + if (pane.wrapAt(row).line != @as(i32, @intCast(c + 1)) or col >= tw) continue; + s.tint(tx + col, p.bodyTop(pane, r) + @as(u16, @intCast(row)), tw - col, mark, null); + } +} + /// The other places on a hit row's line tinted, from the pane its rows are /// in (the first is the row's own mark, Output.decorateRow): the current /// one strongest, as in that pane's text. @@ -2438,7 +2452,7 @@ test "a language server's list: one answer lands with no pane, several open the try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); } -test "B1 on a query pane's rows places the caret and selects, nothing else; j, k and n make a row current, Enter lands the current" { +test "B1 on a query pane's rows places the caret and selects, nothing else, the current row's mark kept; j, k and n make a row current, Enter lands the current" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); @@ -2449,44 +2463,51 @@ test "B1 on a query pane's rows places the caret and selects, nothing else; j, k p.acknowledgePanelPresentation(&.{}); const owner_sel = pane.body.primaryRange(pane.file.?.content, 0); const owner_scroll = pane.file.?.scroll; - const current = q.current; + try std.testing.expectEqual(@as(?usize, 0), q.current); const place = pane.places.current; const r = p.rects[qid]; - const y = r.y + qp.tag_rows + 3; + const row_y = r.y + qp.tag_rows; + const y = row_y + 3; const x = r.x + config.GUTTER + File.gutterWidth(qp) + 6; // a click: the caret there, the current row and every other pane as they were p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = y } }); try std.testing.expectEqual(@as(i32, 3), qp.body.cur_row); - try std.testing.expectEqual(current, q.current); + try std.testing.expectEqual(@as(?usize, 0), q.current); try std.testing.expectEqual(place, pane.places.current); try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0)); try std.testing.expectEqual(owner_scroll, pane.file.?.scroll); - try std.testing.expect(p.panes[qid] != null and queryPane2(p, qid) == null); + try std.testing.expect(queryPane2(p, qid) == null); + // the current row (1) still marked, no other row (2) is + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const surf = try p.render(frame.allocator()); + const far = r.x + r.w - 2; + try std.testing.expect(!std.meta.eql(surf.at(far, row_y + 1).style.bg, surf.at(far, row_y + 2).style.bg)); // a sweep selects the text it went over, and nothing else p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = x + 4, .row = y } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x + 4, .row = y } }); const swept = qp.sel[@backingInt(config.select_button)]; try std.testing.expect(swept.state == .done and swept.r0 == swept.r1 and swept.c1 - swept.c0 == 4); - try std.testing.expectEqual(current, q.current); + try std.testing.expectEqual(@as(?usize, 0), q.current); try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0)); - // the keyboard: j onto the next row makes it current, the text follows + // the keyboard: n steps from the current row, not the caret's, the caret with it p.active = qid; if (qp.body.mode == .insert) p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(p.panes[qid] != null); - typeKeys(p, "j"); - try std.testing.expectEqual(@as(i32, 4), qp.body.cur_row); - try std.testing.expectEqual(@as(?usize, 3), pane.places.current); - // n round the end: the caret goes with the current row typeKeys(p, "n"); - try std.testing.expectEqual(@as(?usize, 0), pane.places.current); - try std.testing.expectEqual(@as(i32, 1), qp.body.cur_row); + try std.testing.expectEqual(@as(?usize, 1), pane.places.current); + try std.testing.expectEqual(@as(i32, 2), qp.body.cur_row); + // j onto the next row makes it current, the text following + typeKeys(p, "j"); + try std.testing.expectEqual(@as(i32, 3), qp.body.cur_row); + try std.testing.expectEqual(@as(?usize, 2), pane.places.current); // B1 elsewhere, then Enter: the current row lands, not the caret's - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = y } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = row_y + 1 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = x, .row = row_y + 1 } }); p.active = qid; p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); } diff --git a/src/body_layer.zig b/src/body_layer.zig index d4ca6d69..bfca268a 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -286,6 +286,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // File layout is independent of whether its producer requests colors. if (pane.file) |*f| { panes.File.drawGutter(p, s, pane, r, tx, tw, body_h, active); + panes.Query.paintMark(p, s, pane, r, body_h); if (p.settings.colors and pane.colorAlgo() != .none) panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.Tables.paint(p, s, pane, r, tx, tw, body_h); diff --git a/src/exec.zig b/src/exec.zig index 7248632b..5b0eb204 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -182,9 +182,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l result.text = edit.currentSelText(p, pane); return result; } - // A query pane's line selection is its current row's mark, not a - // selection made: a click on that row takes its word, as on any row. - if (pane.body.msel.active and pane.query == null and row >= @min(pane.body.msel.r0, pane.body.msel.r1) and + if (pane.body.msel.active and row >= @min(pane.body.msel.r0, pane.body.msel.r1) and row <= @max(pane.body.msel.r0, pane.body.msel.r1)) { result.text = edit.currentSelText(p, pane); diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index 5de12bab..f7e5bba6 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -46,7 +46,7 @@ |8: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |9: 0-1 #000000,#add38a, 2-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, |10: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#243a2d, 14-89 #e5eee5,#243a2d, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |12: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |13: 0-0 d,#608269, 1-4 d,#0d1410, 5-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |14: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 86a4b0ac..2c0aa63d 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -81,7 +81,7 @@ |21: 0-1 d,#496656, 2-149 #b2c3b8,#1d2824, |22: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, |23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#3c614a, 6-149 #f5f7ee,#3c614a, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-13 #e5eee5,#243a2d, 14-19 #f7e4a5,#5e4923, 20-149 #f7e4a5,#243a2d, == snap hit2 grid=150x31 cursor=15,14 == style hit2 grid=150x31 |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, @@ -89,6 +89,7 @@ |16: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |18: 0-0 d,#5e4923, 1-149 d,#0d1410, |23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-13 #e5eee5,#243a2d, 14-19 #f7e4a5,#352e19, 20-149 #f7e4a5,#243a2d, == snap back grid=150x31 cursor=17,15 == style back grid=150x31 |14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, @@ -96,3 +97,4 @@ |16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |18: 0-0 d,#e5eee5, 1-149 d,#0d1410, |23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-13 #e5eee5,#243a2d, 14-19 #f7e4a5,#5e4923, 20-149 #f7e4a5,#243a2d, diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 6351de03..dacb6b89 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -56,7 +56,7 @@ |16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, |17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-20 #e5eee5,#0d1410, 21-25 #f7e4a5,#5e4923, 26-26 #f7e4a5,#0d1410, 27-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-7 d,#243a2d, 8-10 #59675c,#243a2d, 11-20 #e5eee5,#243a2d, 21-25 #f7e4a5,#5e4923, 26-26 #f7e4a5,#243a2d, 27-99 #e5eee5,#243a2d, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-31 #e5eee5,#0d1410, 32-36 #f7e4a5,#5e4923, 37-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, @@ -130,7 +130,7 @@ |16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, |17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-20 #e5eee5,#0d1410, 21-24 #f7e4a5,#5e4923, 25-25 #f7e4a5,#0d1410, 26-99 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-7 d,#243a2d, 8-10 #59675c,#243a2d, 11-20 #e5eee5,#243a2d, 21-24 #f7e4a5,#5e4923, 25-25 #f7e4a5,#243a2d, 26-99 #e5eee5,#243a2d, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-29 #e5eee5,#0d1410, 30-33 #f7e4a5,#5e4923, 34-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index 43445ed4..a406597c 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -42,7 +42,7 @@ |13: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #e5eee5,#0d1410, 17-22 #f7e4a5,#5e4923, 23-23 #f7e4a5,#0d1410, 24-149 #e5eee5,#0d1410, -|16: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-33 #e5eee5,#0d1410, 34-39 #f7e4a5,#5e4923, 40-40 #f7e4a5,#0d1410, 41-149 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-7 d,#243a2d, 8-10 #59675c,#243a2d, 11-33 #e5eee5,#243a2d, 34-39 #f7e4a5,#5e4923, 40-40 #f7e4a5,#243a2d, 41-149 #e5eee5,#243a2d, |17: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #f7e4a5,#5e4923, 17-17 #f7e4a5,#0d1410, 18-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-149 d,#0d1410, @@ -77,7 +77,7 @@ |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-149 d,#0d1410, -|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #e5eee5,#0d1410, 6-10 #f7e4a5,#5e4923,b 11-149 #e5eee5,#0d1410, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #e5eee5,#243a2d, 6-10 #f7e4a5,#5e4923,b 11-149 #e5eee5,#243a2d, |15: 0-0 d,#608269, 1-149 d,#0d1410, |16: 0-0 d,#608269, 1-149 d,#0d1410, |17: 0-0 d,#608269, 1-149 d,#0d1410, -- cgit v1.3 From 685b4050bb0caaa95c4c6a209e69f7777469e9fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 25 Oct 2026 11:40:05 -0300 Subject: query: a row is its place as text, `path:line:col` then its code, the path the shortest a Look from the query pane resolves (Query.lookPath: relative, `../` included, when shorter, else absolute, never `@pN` but for a text with no file), aligned per group, the declaration headers `path:line`; its code coloured as its file's language colours it, the file painted whole on the worker (Stream.paintRows, highlightApart, kept in the locations cache, Query.Shades a walk a refill, Query.recolor in place as each lands) with the match tinted over it; the +Preview's places are the query's hits in its file (a Grep searched, a list fed), tinted and ticked, the row's one current and selected, as in a pane that already shows it; tests for B3 on an address, a saved list's Looks, the shortest path, the preview's places and colours, the worker's colours; fsearch, grep, lookrange, lsp-client, lsprelpath (now `../shade.zig`), stepgrain, tagbottom goldens: the address rows; docs/next-searchrows.md: the design and the numbers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016u3hBPFfja5pK4EBRC1UVD --- docs/next-searchrows.md | 89 ++++++++ docs/search-proto-converge.md | 48 ++++- docs/typ/guide.typ | 9 +- src/Query.zig | 443 ++++++++++++++++++++++++++++++++++----- src/Stream.zig | 272 +++++++++++++++++++++++- src/locations.zig | 34 +++ src/ninep/ctl.zig | 5 +- test/snapshots/fsearch.golden | 12 +- test/snapshots/grep.golden | 2 +- test/snapshots/lookrange.golden | 16 +- test/snapshots/lsp-client.golden | 4 +- test/snapshots/lsprelpath.golden | 22 +- test/snapshots/lsprelpath.snap | 23 +- test/snapshots/stepgrain.golden | 12 +- test/snapshots/tagbottom.golden | 4 +- 15 files changed, 877 insertions(+), 118 deletions(-) create mode 100644 docs/next-searchrows.md (limited to 'src/Query.zig') diff --git a/docs/next-searchrows.md b/docs/next-searchrows.md new file mode 100644 index 00000000..79ffc444 --- /dev/null +++ b/docs/next-searchrows.md @@ -0,0 +1,89 @@ +# searchrows: query rows that are addresses, coloured as their files + +The author's ask (2026-10-25): the search results "should show Lookable +locations for the matches, and it should highlight the near text on the +preview/result pane", then "using treesitter for the highlight I mean", +then on the row format: "the row can be just path:line:row but the path +should be minimal i.e. it should be the smallest one that doesn't refer to +panes like @p1 but that resolves a Look". Change `tsyvmpux`, on +`zmluwpuv`. Positions, not a verdict. + +## The row + + Places.zig:163:8 pub fn firstFrom(hits: []const Hit, at: usize) usize { + Places.zig:237:19 const i = firstFrom(set.hits.items, at); + ../shade.zig:1:11 pub const Shade = enum { + +- `path:line:col`, then the line's code from its first non-blank: plain + text, so B3 anywhere on the address is a Look as anywhere, a sweep copies + it, and a frozen pane saved is a list of addresses that still work. +- The path is `Query.lookPath(buf, path, dir)`: the shortest text a Look + from the query pane resolves: relative to the pane's directory (`x`, + `sub/x`, `../x`) when strictly shorter, else absolute. A relative name a + Look would read as something else (`@p...`, `://`) stays absolute. One + function, used by every hit row and by the file and declaration headers + of Grep, `/`/All and the language server lists. +- On every row, `/` in the owner included: a bare `:12:5` would be looked + up in the +Search itself (a Look resolves against the pane it is in) and + a saved list would lose its file. +- A group's code starts in one column: the address padded to + `path + ':' + digits(longest line in the group) + ':' + 3`, then two + spaces (a column of four digits or more pushes its own row one cell). +- Declaration headers carry `path:line` in the same column; file headers + stay the bare path (itself a Look). + +## Colours + +- Rows: `Stream.paintRows` paints a whole file on the worker + (`syntax.highlightApart`, the same call as the anim paint-ahead): the text + of the pane that shows it, else read from disk there. It lands in the + locations cache beside Callstack's (`locations.Cache.put`); each row takes + its line's slice when the line still reads as the row does + (`Query.Shades`, one walk down each file a refill). Until then rows are + plain; on arrival `Query.recolor` colours every query pane's plain rows + in place and asks for the next file: one at a time, each (path, revision) + once a Grep (a 256 ring). The match tint (`decorateRow`) sits on top, its + position past the address (`code_start`). Not on the loop, not in a 9P + write (asked again on the next step), not without workers. +- The +Preview: colours are its own pane's (painted as any file pane), and + the query's hits in that file are its places (`Places.search` literal for + a Grep, `Places.feed` from the rows for a list), tinted and ticked, the + current row's one current and selected, centred. A pane that already + shows the file gets the same (`selectPlace`). + +## Numbers + +`zz grep rows timings` (src/Stream.zig, `GREP_TIMES=`): Debug, a +TestShell worker, 160x50, the stress file (src/layout.zig x17, 1.22 MB, +29002 lines), typing `pane` three times with 400 ms of frames after each +key, then Enter on 2000 rows. Load 2.4-3.0 before, 2.7-2.8 after; after is +three runs. + +| frame work | before | after | +|---|---|---| +| keystroke (update + render) p50 / p90 / max | 2.2 / 4.2 / 6.0 ms | 2.0-2.1 / 2.9-6.5 / 4.4-6.7 ms | +| refill frame (rows remade) p50 / p90 / max | 4.4 / 5.2 / 5.2 ms | 4.8-5.1 / 5.4-6.1 / 5.4-6.1 ms | +| other frames p50 / p90 / max | 0.9 / 1.3 / 10.6 ms | 0.9 / 1.2-1.3 / 10.0-10.2 ms | +| Enter (2000 rows written) | 27.0 ms | 28.2-28.7 ms | +| frames after Enter p50 / max | 0.9 / 1.7 ms | 0.9 / 1.3-1.7 ms | + +Rows coloured after Enter: 1718 of 2000; the other 282 are plain in the +file's own colours too (checked against `highlightApart` of the file). A +refill costs ~0.4 ms more (the wider rows and the Shades walk), inside the +noise of the keystroke column; the paint itself never shows on the loop. + +## Pushback and rough edges + +- The current row's address is barely legible: the address's dim location + colour on the current row's mark tint (visible in the screenshot). The + thing B3 aims at should read; a brighter location fg on the marked row is + a one-line theme decision I left to you. +- A text with no file (a +New scratch) has no path any Look resolves, so + its `/` rows keep `@pN`, the only address that works there. +- `lsprelpath` asserted the opposite policy ("must NOT become + `../shade.zig`"); the author's shortest-path rule wins, the script says so. +- Rows of a file over 4 MB, and of markdown/typst (their injections share + parsers, so no worker paints them) stay plain; a disk file changed after + it was painted keeps plain rows for its changed lines until the next Grep. +- One file painted at a time: a Grep over hundreds of files colours file + by file (each lands in a frame); a worker per file if that is slow. diff --git a/docs/search-proto-converge.md b/docs/search-proto-converge.md index 99adbc2c..7a3e361a 100644 --- a/docs/search-proto-converge.md +++ b/docs/search-proto-converge.md @@ -40,13 +40,40 @@ only the prompts that are not search. `Search ` is the builtin under the three argument paths (`config.leader_args`, pick's table). -**Rows look like Callstack's**: a gutter line number, the hit's line with -the match tinted (every match on a line tinted, one row a line), under the -declaration it is in (once a parse exists, see below), under the file -(Grep, the LSP lists), under `@pN name (count)` in serial order (All). -B3 on a row's line number looks at its address; B3 on its code is a word -Look as anywhere; B2 on line 1 runs it again. The pane has no gutter of its -own, and its rows are read-only while live (queryline's clampEdit). +**Rows look like Callstack's**: each row's place first, as text, +`path:line:col`, the path the shortest a Look from the query pane +resolves (relative to its directory, `../` included, when that is shorter, +else absolute; `Query.lookPath`), never an `@pN` but for a text with no +file, padded so a group's code starts in one column, then +the hit's line coloured as its file's language colours it, the match +tinted over that (every match on a line tinted, one row a line); under the +declaration it is in (once a parse exists, see below; the header has its +`path:line` too), under the file (Grep, the LSP lists), under `@pN name +(count)` in serial order (All). B3 on the address is a Look as anywhere, a +sweep copies it, and a frozen pane saved is a list of addresses that still +work; B3 on its code is a word Look; B2 on line 1 runs it again. The pane +has no gutter of its own, and its rows are read-only while live +(queryline's clampEdit). The address is on every row, `/`'s included: +a bare `:12:5` would be looked up in the +Search itself (a Look resolves +against the pane it is in), and a saved list would lose its file. + +The rows' colours are their files' whole (`Stream.paintRows`): a file is +painted once on the worker (`syntax.highlightApart`, the text of the pane +that shows it, else read there from disk), kept in the locations cache +beside Callstack's, and each row takes its line's slice when the line +still reads as the row does (`Query.Shades`, one walk down each file a +refill). Until then the rows are plain; when a file lands, every query +pane's plain rows from it are coloured in place (`Query.recolor`), which +asks for the next file, one at a time. Without workers (tests) the rows +stay plain. + +**The +Preview is the file as its own pane shows it**: its colours are +the file's (`colorAlgo` `.source`, painted ahead as any pane), and the +query's hits in it are its places (a Grep's searched there as in an open +pane, a list's fed from its rows), tinted and ticked, the current row's +one current and selected, centred with its neighbours round it. A pane +that already shows the file gets the same: its places, the row's one +selected. **Keys** on line 1, typing: Ctrl-n / Ctrl-p (and Down / Up, `config.query_next` / `query_prev`) step the current row; Enter lands; Esc cancels. Tab stays the @@ -197,9 +224,10 @@ of 100 (the Debug SafeAllocator's stack capture per allocation was 30% at - LookNext / LookPrev do not step query rows (their addresses are in row metadata, not text). -- Grep rows carry no syntax colours; `/` rows are coloured where the - owner's highlights cover them (zeros elsewhere, so no fragment parse per - refill). +- Rows of a file bigger than 4 MB, of markdown and typst (their + injections share parsers, so no worker paints them) stay plain; a disk + file changed after it was painted keeps plain rows for its changed + lines until the next Grep. - Rail ticks are not carried over the detached wire (a detached frontend shows tints, not ticks). - In a window too short for the group (4 rows), only the query pane's tag diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 61ba5455..58e5d907 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -175,7 +175,7 @@ is born #word("SearchRows") rows tall and never resizes itself; nothing found is a count of `0` in its tag, not an exit. #pairs( - [#key("/") `vw`], [every match in the text tinted and ticked on its scroll rail, the first after the cursor selected; the rows under line 1 are the lines holding it, a line number in the gutter, each under the declaration it is in], + [#key("/") `vw`], [every match in the text tinted and ticked on its scroll rail, the first after the cursor selected; the rows under line 1 are the lines holding it, each its place as text first (`file:line:col`, the shortest path a #word("Look") from the pane resolves), then the line coloured as the file is, under the declaration it is in], [#keys("Ctrl-n", "Ctrl-p")], [the next or previous match, typing; the text follows it], [#key("Enter")], [the keyboard on the match, the pattern in `/`, the rows kept as text (#word("Save") keeps them as a file)], [#keys("n", "N")], [the next or previous match in the text, round the end without a word], @@ -202,8 +202,11 @@ typing, #keys("n", "N") and #keys("j", "k") in the pane's normal mode); #btn("B1") on the rows places the caret and selects, as in any pane, and moves nothing else. #key("Enter") lands the current row, making the preview that file's pane where it stands. -#btn("B3") on a row's line number looks at the row; #btn("B2") on line 1 -runs it again. The next search from the same pane reuses its query pane, +The preview colours the file as its own pane does, and the query's hits +in it are its places, tinted and ticked, the current one selected. +#btn("B3") on a row's place goes there, as on any address; the rows kept +as text (#word("Save")) are a list of places that still work. +#btn("B2") on line 1 runs it again. The next search from the same pane reuses its query pane, its kept rows back on #key("Esc") (#word("SearchPane") `new`: a pane each; #word("SearchPlace") `column`: in a finder column at the right). A PDF's and a terminal's #key("/") still ask on the message row and list a diff --git a/src/Query.zig b/src/Query.zig index 11db8579..09b46f3b 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -10,11 +10,12 @@ //! matched fuzzy (Names.zig), text by regex. Editing the word changes //! the source. //! -//! The rows look like a Callstack's: the hit line with the match tinted -//! under a gutter line number, under the declaration it is in (when the -//! owner's parse exists: never made here on the loop), under its file -//! (Grep) or under `@pN name (count)` (All). They are addresses, all text: -//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into +//! The rows look like a Callstack's: the hit's place as text, +//! `path:line:col`, then its line coloured as its file is (painted on a +//! worker, Shades) with the match tinted, under the declaration it is in +//! (when the owner's parse exists: never made here on the loop), under its +//! file (Grep) or under `@pN name (count)` (All). They are addresses, all +//! text: B3 on one looks, B2 on line 1 runs it again. Wherever a row points into //! an open pane's text, that pane's places (Places.zig) show the set: //! tints, rail ticks, the current one selected. A row pointing at a file //! no pane shows is shown in the +Preview attached under this pane; Enter @@ -399,6 +400,10 @@ fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { /// on a tick. Nothing here is synchronous with an edit of the owner: its /// places shift (Places.shift) and the rows follow once it stands a frame. pub fn produceAll(p: *Pardes, tick: bool, keyed: bool) void { + if (p.stream.rows_later) { + p.stream.rows_later = false; + recolor(p); + } for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; if (pane.query == null) continue; @@ -735,7 +740,7 @@ fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList( } else { locations.freeRows(p.gpa, f.location_rows); f.location_rows = meta; - f.syntax_dirty = true; + dropHighlights(p, f); } } else { File.setContent(p, f, content); @@ -758,41 +763,127 @@ fn gpa_free_pager(p: *Pardes, f: *File.State) void { f.pager_spans = &.{}; } -/// The gutter a file of `nlines` lines numbers its rows in: two spaces, -/// the number right-aligned, two spaces. -fn gutterWidth(nlines: usize) usize { +/// The room a group of rows gives its addresses, so that their code +/// starts in one column: the path, a colon, its longest line number, a +/// colon, three digits of column (a longer one pushes its code on a cell). +fn addressWidth(rel: []const u8, max_line: usize) usize { var digits: usize = 1; - var n = nlines; + var n = max_line; while (n >= 10) : (n /= 10) digits += 1; - return 2 + @max(3, digits) + 2; + return rel.len + 1 + digits + 1 + 3; } -fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { +/// One hit row: its place as text first, `rel:line:col` (`rel` the path +/// as Look finds it from the query pane's directory), so that B3 on it is a +/// Look as anywhere, a sweep copies it and a saved list is a list of +/// addresses; padded to `width`, then two spaces and the line's code from +/// its first non-blank. Coloured as its file is: `shade`, the line's +/// colours when its pane has them painted, else the whole file's from the +/// worker (Shades). +fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), sh: *Shades, width: usize, rel: []const u8, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { var lead: usize = 0; while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1; const code = std.mem.trimEnd(u8, whole[lead..], "\r"); - var buf: [4096 + 32]u8 = undefined; - var num: [24]u8 = undefined; - const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch ""; - const pad = width -| 2 -| number.len; - if (pad + number.len + 2 + code.len > buf.len) return; - @memset(buf[0..pad], ' '); - @memcpy(buf[pad..][0..number.len], number); - @memcpy(buf[pad + number.len ..][0..2], " "); - @memcpy(buf[pad + number.len + 2 ..][0..code.len], code); - const text = buf[0 .. pad + number.len + 2 + code.len]; - const gutter = pad + number.len + 2; - try writeRow(p, out, rows, text, .{ + var buf: [8192]u8 = undefined; + const address = std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ rel, line_no, col + 1 }) catch return; + const gutter = @max(width, address.len) + 2; + if (gutter + code.len > buf.len) return; + @memset(buf[address.len..gutter], ' '); + @memcpy(buf[gutter..][0..code.len], code); + try writeRow(p, out, rows, buf[0 .. gutter + code.len], .{ .kind = .match, .source_column = lead, .path = @constCast(path), .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, - .location_end = gutter, + .location_end = address.len, .code_start = gutter, - .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}), + .colors = @constCast(if (shade.len >= lead + code.len) shade[lead..][0..code.len] else sh.of(p, path, line_no, code, lead)), }); } +/// Rows' syntax colours from their file's whole (as Callstack's rows are), +/// kept in the locations cache once a worker has painted it +/// (Stream.paintRows): the line found going down the file a row at a time, +/// so a refill walks each file once. A file not painted, or whose line no +/// longer reads as the row does, is asked for (once a refill) and its rows +/// are plain till it lands (`recolor`). +const Shades = struct { + path: []const u8 = "", + source: []const u8 = "", + colors: []const u8 = &.{}, + /// The line (1-based) that starts at `at` in `source`. + line: usize = 1, + at: usize = 0, + asked: bool = false, + + /// The colours of `code`, which is line `line_no` of `path` from byte + /// `column` on, or none. + fn of(sh: *Shades, p: *Pardes, path: []const u8, line_no: usize, code: []const u8, column: usize) []const u8 { + if (path.len == 0 or line_no == 0 or code.len == 0) return &.{}; + if (!std.mem.eql(u8, path, sh.path)) { + // its own copy: a caller's path is often a buffer it reuses + sh.* = .{ .path = p.scratch.allocator().dupe(u8, path) catch return &.{} }; + if (p.locations_cache.peek(path)) |e| { + sh.source = e.source; + sh.colors = e.colors; + } + } + if (sh.colors.len == 0 or sh.colors.len != sh.source.len) return sh.ask(p); + if (line_no < sh.line) { + sh.line = 1; + sh.at = 0; + } + while (sh.line < line_no) : (sh.line += 1) { + sh.at = (std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse return sh.ask(p)) + 1; + } + const line = sh.source[sh.at .. std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse sh.source.len]; + if (column + code.len > line.len or !std.mem.eql(u8, line[column..][0..code.len], code)) return sh.ask(p); + return sh.colors[sh.at + column ..][0..code.len]; + } + + fn ask(sh: *Shades, p: *Pardes) []const u8 { + if (!sh.asked) Stream.paintRows(p, sh.path); + sh.asked = true; + return &.{}; + } +}; + +/// A file's colours arrived (Stream.paintRows): every query pane's hit +/// rows still plain, live or frozen, coloured from what is painted now, in +/// place; the first row of a file not painted yet asks for it, so they are +/// painted one after another. +pub fn recolor(p: *Pardes) void { + for (p.panes) |slot| { + const rp = slot orelse continue; + if (rp.query == null) continue; + const f = &rp.file.?; + var sh: Shades = .{}; + var lines = std.mem.splitScalar(u8, f.content, '\n'); + var changed = false; + for (f.location_rows) |row| { + const text = lines.next() orelse break; + if (row.kind != .match or row.location_end == 0 or row.at.line == 0 or row.colors.len == 0) continue; + if (std.mem.indexOfNone(u8, row.colors, &.{0}) != null) continue; + const code = text[@min(row.code_start, text.len)..]; + const got = sh.of(p, row.path, row.at.line, code[0..@min(code.len, row.colors.len)], row.source_column); + if (got.len == 0) continue; + @memcpy(row.colors[0..got.len], got); + changed = true; + } + if (changed) dropHighlights(p, f); + } +} + +/// The pane's painted colours let go, so the next frame paints them from +/// its rows again: with its text the same, a frame would keep the old ones +/// (refreshHighlights keeps a painting that covers the view). +fn dropHighlights(p: *Pardes, f: *File.State) void { + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; +} + /// The path a row of pane `tp`'s text says: its file's, or `@pN` for a /// text that is no file (a list, a scratch). fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { @@ -801,17 +892,47 @@ fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch ""; } +/// The shortest text that names file `path` to a Look from directory +/// `dir` (a Look joins a relative word to its pane's directory): the path +/// relative to `dir` (`x`, `sub/x`, `../x`) when that is shorter, else the +/// absolute one, never an `@pN`. A relative name a Look would read as +/// something else (a pane address, a URL) stays absolute. `buf` holds a +/// relative one that climbs. +pub fn lookPath(buf: []u8, path: []const u8, dir: []const u8) []const u8 { + // a relative pane's (a test's): its directory's prefix off, as ever + if (path.len == 0 or path[0] != '/' or dir.len == 0 or dir[0] != '/') return Names.relative(path, dir); + const d = std.mem.trimEnd(u8, dir, "/"); + // the last slash both share, ending a whole component of `dir` + var k: usize = 0; + var i: usize = 0; + while (i < path.len and i <= d.len) : (i += 1) { + if (path[i] == '/' and (i == d.len or d[i] == '/')) k = i; + if (i == d.len or d[i] != path[i]) break; + } + const ups = std.mem.count(u8, d[k..], "/"); + const rest = path[k + 1 ..]; + if (ups * 3 + rest.len >= path.len or ups * 3 + rest.len > buf.len) return path; + for (0..ups) |u| @memcpy(buf[u * 3 ..][0..3], "../"); + @memcpy(buf[ups * 3 ..][0..rest.len], rest); + const rel = buf[0 .. ups * 3 + rest.len]; + if (std.mem.startsWith(u8, rel, config.pane_addr) or std.mem.indexOf(u8, rel, "://") != null) return path; + return rel; +} + /// Rows from pane `tp`'s places: one a line with any (two on a line are /// one row: everywhere's bug), the declaration they are in over them when /// its parse exists, from place `from` on, `budget` rows at most. The /// place it stopped before. -fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize { +fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, dir: []const u8, from: usize, budget: *usize) !usize { const f = &tp.file.?; const set = &tp.places; const hits = set.hits.items; const index = try File.lineIndex(p.gpa, f); - const width = gutterWidth(index.len); const path = addressOf(p.scratch.allocator(), tp); + var relbuf: [4096]u8 = undefined; + const rel = lookPath(&relbuf, path, dir); + const width = addressWidth(rel, index.len); + var sh: Shades = .{}; const decls = ownerDecls(p, f, false) orelse &.{}; var decl_now: ?usize = null; var i: usize = @min(from, hits.len); @@ -852,15 +973,20 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar const head_ls = index[decls[di].start_line]; const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len; const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r"); - var hb: [600]u8 = undefined; - const text = std.fmt.bufPrint(&hb, " {s}", .{head[0..@min(head.len, 560)]}) catch ""; + // Its address too, `rel:line`, in the column the hits' are. + var hb: [8192]u8 = undefined; + const address = std.fmt.bufPrint(&hb, "{s}:{d}", .{ rel, decls[di].start_line + 1 }) catch ""; + const gutter = @max(width, address.len) + 2; + const shown = head[0..@min(head.len, hb.len -| gutter)]; + @memset(hb[address.len..gutter], ' '); + @memcpy(hb[gutter..][0..shown.len], shown); try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); - try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 }); + try writeRow(p, out, rows, hb[0 .. gutter + shown.len], .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = address.len, .code_start = gutter }); }; } const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); - try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + try writeHitRow(p, out, rows, &sh, width, rel, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); i += n; } return i; @@ -891,7 +1017,7 @@ fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { var hb: [64]u8 = undefined; try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} places before these", .{from}) catch " ..."); } - q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget); + q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, std.fs.path.dirname(rp.file.?.path) orelse "/", from, &budget); q.window.lo = @min(from, q.window.hi); } if (q.more) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); @@ -974,7 +1100,7 @@ fn makeAllRows(p: *Pardes, id: usize) !void { const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch ""; try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); - _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget); + _ = try writePlacesRows(p, q, &out, &rows, tp, std.fs.path.dirname(rp.file.?.path) orelse "/", 0, &budget); } if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); setRows(p, rp, &out, &rows); @@ -1084,6 +1210,8 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { const q = rp.query.?; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; const at: usize = @min(q.grep_at, q.found.items.len -| 1); + // nothing current before these rows: the first one's shown once it is + const shown = q.current != null; q.items.clearRetainingCapacity(); var out: std.ArrayList(u8) = .empty; defer out.deinit(p.gpa); @@ -1097,18 +1225,29 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} lines before these", .{lo}) catch " ..."); } var current: ?usize = null; + var sh: Shades = .{}; + var width: usize = 0; + var relbuf: [4096]u8 = undefined; for (q.found.items[lo..hi], lo..) |fd, i| { - const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; - const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; - if (!std.mem.eql(u8, rel, last_path)) { - last_path = rel; + const name = q.found_bytes.items[fd.path..][0..fd.path_len]; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), name }) catch continue; + const rel = lookPath(&relbuf, path, dir); + if (!std.mem.eql(u8, name, last_path)) { + last_path = name; try q.items.append(p.gpa, .{ .kind = .header }); try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + // the file's rows in this window, for the widest line number + var max_line: usize = fd.line; + for (q.found.items[i..hi]) |next| { + if (!std.mem.eql(u8, q.found_bytes.items[next.path..][0..next.path_len], name)) break; + max_line = @max(max_line, next.line); + } + width = addressWidth(rel, max_line); } const code = q.found_bytes.items[fd.code..][0..fd.code_len]; if (i == at) current = q.items.items.len; try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); - try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); + try writeHitRow(p, &out, &rows, &sh, width, rel, path, fd.line, code, fd.col, fd.end, &.{}); } if (hi < q.found.items.len) { var hb: [64]u8 = undefined; @@ -1122,7 +1261,7 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { q.current = current orelse firstHit(q); countGrepCurrent(q); showCurrent(rp); - if (q.current == null) blankPreview(p, id); + if (q.current == null) blankPreview(p, id) else if (!shown) showTarget(p, id); } /// What the disk walk passed over, said under the rows: a search that @@ -1258,16 +1397,28 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { var last_path: []const u8 = ""; var pathbuf: [4096 + 8]u8 = undefined; var n: usize = 0; - for (sorted.items) |ln| { + var sh: Shades = .{}; + var width: usize = 0; + var relbuf: [4096]u8 = undefined; + for (sorted.items, 0..) |ln, li| { if (ln.len == 0) continue; if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; const t = look.parsePathLine(ln); if (t.at.line == 0) continue; const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + const rel = lookPath(&relbuf, path, dir); if (!std.mem.eql(u8, t.path, last_path)) { last_path = t.path; try q.items.append(p.gpa, .{ .kind = .header }); - try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + // sorted by place: the file's last row has its widest line number + var max_line: usize = t.at.line; + for (sorted.items[li..]) |next| { + const tn = look.parsePathLine(next); + if (!std.mem.eql(u8, tn.path, t.path)) break; + max_line = @max(max_line, tn.at.line); + } + width = addressWidth(rel, max_line); } const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); const col0 = t.at.col -| 1; @@ -1293,7 +1444,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { break; } try q.items.append(p.gpa, .{ .kind = .hit, .n = 1, .serial = shown_in }); - try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); + try writeHitRow(p, &out, &rows, &sh, width, rel, path, t.at.line, code, col, end, &.{}); n += 1; } if (n == 0) try noteRow(p, q, &out, &rows, " nothing"); @@ -1520,11 +1671,26 @@ fn showTarget(p: *Pardes, id: usize) void { const line0 = meta.at.line -| 1; const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows; if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center); + _ = selectPlace(p, tp, rp.serial, meta.at); return; } displayPreview(p, id, meta.path, meta.at); } +/// The place a row points at (its line and column) made current in pane +/// `tp`'s places, when query `serial` fed them: selected and in view, as +/// the owner's are. False when there is none there. +fn selectPlace(p: *Pardes, tp: *Pane, serial: u32, at: look.Spot) bool { + const f = if (tp.file) |*file| file else return false; + const set = &tp.places; + if (set.from != serial or !set.started or at.line == 0 or at.line > File.nlines(p.gpa, f)) return false; + const ls = File.lineStart(p.gpa, f, at.line - 1); + const i = Places.firstFrom(set.hits.items, ls + (at.col -| 1)); + if (i >= set.hits.items.len or (at.line < File.nlines(p.gpa, f) and set.hits.items[i].start >= File.lineStart(p.gpa, f, at.line))) return false; + set.goTo(tp, i, false); + return true; +} + // ---- the +Preview ---- /// The +Preview under query pane `qid`, if it has one: by serial. @@ -1597,6 +1763,8 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void f.scroll = 0; f.syntax_dirty = true; pane.hscroll = 0; + // another file: its own places, found below + pane.places.clear(p.gpa); p.sync(); } look.clearNavigationSelection(p, pane); @@ -1609,6 +1777,36 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void return; } look.focusPaneLine(p, id, at, .center); + // The query's hits in this file are the preview's places, tinted and + // ticked as in the file's own pane would be, the row's one current and + // selected; the view centred on it, its neighbours round it. + const qp = p.panes[qid].?; + const q = qp.query.?; + switch (q.source) { + .grep => if (parse(q.asked)) |a| pane.places.search(p, pane, .list, qp.serial, a.pat, true, null, false), + .refs, .defs, .impls, .diagnostics => if (pane.places.from != qp.serial or !pane.places.shows(pane)) { + var hits: std.ArrayList(Places.Hit) = .empty; + defer hits.deinit(p.gpa); + const dir = std.fs.path.dirname(qp.file.?.path) orelse "/"; + const nlines = File.nlines(p.gpa, f); + var pathbuf: [4096 + 8]u8 = undefined; + var lines = std.mem.splitScalar(u8, q.lsp_rows, '\n'); + while (lines.next()) |ln| { + const t = look.parsePathLine(ln); + if (t.at.line == 0 or t.at.line > nlines) continue; + const full = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + if (!std.mem.eql(u8, full, f.path)) continue; + const ls = File.lineStart(p.gpa, f, t.at.line - 1); + const le = std.mem.indexOfScalarPos(u8, f.content, ls, '\n') orelse f.content.len; + const col = @min(t.at.col -| 1, le - ls); + const end = @min(if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col + 1, le - ls); + hits.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch break; + } + pane.places.feed(p, pane, qp.serial, hits.items, null); + }, + else => {}, + } + if (selectPlace(p, pane, qp.serial, at)) return; if (at.end_line == 0 or at.end_col <= at.col) pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) }; } @@ -1914,8 +2112,9 @@ pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { return out; } -/// B3 on a row's gutter (its line number): the row's address, as a +Diff -/// line's prefix is its place (exec.operandAt). Null off a gutter. +/// B3 on a row's address text: the address whole, as a +Diff line's +/// prefix is its place (exec.operandAt), so a path with a space in it is +/// still one; the text says the same place. Null off the address. pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 { if (pane.query == null) return null; const f = pane.file orelse return null; @@ -2122,9 +2321,9 @@ test "a / query: Enter lands and freezes, the register filled, n and N step sile try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance); const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content); defer std.testing.allocator.free(frozen); - // the rows: one a line (gamma alpha has one), a gutter number each - try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); - // B3 on a row's line number is its address; on its code, no address + // the rows: one a line (gamma alpha has one), each its place as text + try std.testing.expect(std.mem.indexOf(u8, frozen, "\ntest.txt:1:1 alpha one\n") != null); + // B3 on a row's address is its address; on its code, no address var abuf: [256]u8 = undefined; const addr = rowAddress(qp, 1, 2, &abuf).?; try std.testing.expect(std.mem.endsWith(u8, addr, ":1:1")); @@ -2511,3 +2710,151 @@ test "B1 on a query pane's rows places the caret and selects, nothing else, the try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); } + +test "a query row's place is its text: the match tinted after it, B3 on it opens the place, the rows saved and read again still Look" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "zero\none needle\ntwo\nthree needle here\n"); + leader(p, "fg"); + typeKeys(p, "needle"); + settle(p); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const f = &qp.file.?; + // each row `path:line:col`, relative to the pane's directory, the code + // after it in one column + try std.testing.expect(std.mem.indexOf(u8, f.content, "\na.txt:2:5 one needle\n") != null); + try std.testing.expect(std.mem.indexOf(u8, f.content, "\na.txt:4:7 three needle here\n") != null); + // the match's tint where the match is, past the address + var row4: usize = 0; + var lines = std.mem.splitScalar(u8, f.content, '\n'); + var i: usize = 0; + while (lines.next()) |line| : (i += 1) { + if (i >= f.location_rows.len) break; + const meta = f.location_rows[i]; + if (meta.kind != .match or meta.location_end == 0) continue; + const dec = Output.decorateRow(f.output, line, meta); + try std.testing.expectEqualStrings("needle", line[dec.mark_start..dec.mark_end]); + try std.testing.expect(look.parsePathLine(line[0..meta.location_end]).at.line == meta.at.line); + if (meta.at.line == 4) row4 = i; + } + try std.testing.expect(row4 > 0); + // B3 on the address: the place, in the pane that shows it + a.body.cur_row = 0; + p.acknowledgePanelPresentation(&.{}); + const r = p.rects[qid]; + const y = r.y + qp.tag_rows + @as(u16, @intCast(row4)) - @as(u16, @intCast(qp.scroll())); + const x = r.x + config.GUTTER + File.gutterWidth(qp) + 3; + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = y } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = y } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 3), a.body.cur_row); + // the rows as a plain text in that directory (what Save writes): a + // Look at a row's address word still goes there + const saved = try std.testing.allocator.dupe(u8, f.content); + defer std.testing.allocator.free(saved); + p.newScratchBelow(0); + const sid = p.active; + const sp = p.panes[sid].?; + File.setContent(p, &sp.file.?, try p.gpa.dupe(u8, saved)); + try std.testing.expect(sp.query == null and sp.file.?.location_rows.len == 0); + const at = std.mem.indexOf(u8, saved, "a.txt:2:5").?; + const line = saved[at .. std.mem.indexOfScalarPos(u8, saved, at, '\n').?]; + const word = look.expandedWord(line, 3).?; + a.body.cur_row = 0; + look.lookAt(p, sid, line[word.lo..word.hi]); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), a.body.cur_row); +} + +test "the +Preview: the query's hits in its file are its places, the row's one current and selected, coloured as the file is" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const text = "const needle = 1;\nconst hay = 2;\nfn f() void {\n _ = needle;\n}\npub const needle_too = needle;\n"; + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = text }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 60 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "a.txt", "x\n"); + leader(p, "fg"); + typeKeys(p, "needle"); + settle(p); + const qid = queryPane(p).?; + // the first row shown in the preview as the rows land; a step, the next + const pid = previewOf(p, qid).?; + try std.testing.expectEqual(@as(?usize, 0), p.panes[pid].?.places.current); + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + const pv = p.panes[pid].?; + try std.testing.expect(std.mem.endsWith(u8, pv.file.?.path, "/b.zig")); + // its places: every `needle` in the file, as its own pane would find them + var expected: std.ArrayList(Places.Hit) = .empty; + defer expected.deinit(std.testing.allocator); + var from: usize = 0; + while (std.mem.indexOfPos(u8, text, from, "needle")) |at| : (from = at + 1) try expected.append(std.testing.allocator, .{ .start = at, .end = at + 6 }); + try std.testing.expectEqualSlices(Places.Hit, expected.items, pv.places.hits.items); + // the current row's (line 4, column 9) current and selected + try std.testing.expectEqual(@as(?usize, 1), pv.places.current); + var sel = pv.body.primaryRange(pv.file.?.content, 0); + try std.testing.expectEqual(expected.items[1].start, @min(sel.anchor, sel.head)); + // the next row: the next place, the preview's places standing + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(pid, previewOf(p, qid).?); + try std.testing.expectEqual(@as(?usize, 2), pv.places.current); + sel = pv.body.primaryRange(pv.file.?.content, 0); + try std.testing.expectEqual(expected.items[2].start, @min(sel.anchor, sel.head)); + // its colours the file's, as its own pane paints them + if (!syntax.enabled) return; + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const pf = &pv.file.?; + try std.testing.expect(pf.highlights.len > 0 and std.mem.indexOfNone(u8, pf.highlights, &.{0}) != null); + const own = try syntax.highlightFileRange(p.tree_sitter_gpa, pf.path, pf.content, pf.highlight_start, pf.highlight_start + pf.highlights.len); + defer p.tree_sitter_gpa.free(own); + try std.testing.expectEqualSlices(u8, own, pf.highlights); +} + +test "a row's address is the shortest path a Look from the query pane resolves: in its directory, under it, above it, else absolute" { + if (!filesystem.platform_has_fs) return; + if (!pardes.lsp.supports.contains(.references)) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "q/sub"); + for ([_][]const u8{ "q/sub/deep.txt", "up.txt" }) |name| try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "one\ntwo\n" }); + var root_buf: [std.fs.max_path_bytes]u8 = undefined; + const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)]; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "q/here.txt", "one\ntwo\n"); + // another tree, where the climb out would be longer than the path + const far = "/etc/passwd"; + if (std.c.access(far, std.c.F_OK) != 0) return; + const answer = try std.fmt.allocPrint(std.testing.allocator, "{s}/q/here.txt:2:1 two\n{s}/q/sub/deep.txt:2:1 two\n{s}/up.txt:2:1 two\n" ++ far ++ ":1:1 root\n", .{ root, root, root }); + defer std.testing.allocator.free(answer); + fillList(p, 0, .refs, answer); + const qp = p.panes[queryPane(p).?].?; + const f = &qp.file.?; + const dir = std.fs.path.dirname(f.path).?; + var lines = std.mem.splitScalar(u8, f.content, '\n'); + var seen: std.ArrayList([]const u8) = .empty; + defer seen.deinit(std.testing.allocator); + for (f.location_rows) |row| { + const line = lines.next().?; + if (row.kind != .match or row.location_end == 0) continue; + const addr = line[0..row.location_end]; + try seen.append(std.testing.allocator, addr); + // Looked at from the pane: the row's file, at its line + var realbuf: [4096]u8 = undefined; + const t = look.resolve(p, addr, dir, &realbuf); + try std.testing.expectEqualStrings(row.path, t.file.path); + try std.testing.expectEqual(row.at.line, t.file.at.line); + } + for ([_][]const u8{ "here.txt:2:1", "sub/deep.txt:2:1", "../up.txt:2:1", far ++ ":1:1" }) |want| { + for (seen.items) |got| { + if (std.mem.eql(u8, got, want)) break; + } else return error.TestUnexpectedResult; + } +} diff --git a/src/Stream.zig b/src/Stream.zig index e42d4a16..da7d12eb 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -218,6 +218,20 @@ painted_ahead: u32 = 0, painted_on_loop: u32 = 0, /// The view the last paint was asked from, and which way it was going. ahead_seen: struct { serial: u32 = 0, scroll: usize = 0, dir: i2 = 1 } = .{}, +/// A file's colours for query rows being worked out (paintRows), one at a +/// time, its own task beside the scroll's. ponytail: one file at a time, +/// the next asked when it lands (Query.recolor); a worker per file if a +/// Grep of hundreds of files colours too slowly. +rows_paint: ?PaintTask = null, +/// The files (a hash of path and revision) asked since the last Grep +/// began: each asked once, so a file whose colours never fit its rows +/// (changed on disk since) is not painted again and again. ponytail: a +/// ring of 256; the oldest forgotten. +rows_asked: [256]u64 = @splat(0), +rows_asked_at: u8 = 0, +/// Rows asked for their colours while a 9P write was served: asked again +/// on the next step (Query.produceAll). +rows_later: bool = false, pub fn deinit(s: *Stream, gpa: std.mem.Allocator) void { s.cancelTask(); @@ -244,7 +258,7 @@ pub fn cancelParse(s: *Stream) void { /// The paints' workers told to stop and joined (the session's end). pub fn cancelPaint(s: *Stream) void { - for ([_]*?PaintTask{ &s.paint, &s.paint_retired }) |slot| { + for ([_]*?PaintTask{ &s.paint, &s.paint_retired, &s.rows_paint }) |slot| { const t = slot.* orelse continue; slot.* = null; t.job.stop.store(true, .release); @@ -310,11 +324,69 @@ pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, cont p.emit(.{ .search = .{ .gen = gen } }); } -fn paintWork(job: *PaintJob, ctx: ?*anyopaque, sink: Sink) void { +/// A file's colours for the query rows that show its lines, the whole +/// file painted on a worker (rows coloured as the file's language colours +/// them, as Callstack's are): the text of the pane that shows it, else read +/// from disk there. Kept in the locations cache when it lands, where the +/// rows find them (Query.Shades). Not without workers (the rows stay +/// plain), nor for a file bigger than `max_rows_paint_bytes`, nor twice for +/// one revision of a file. +pub fn paintRows(p: *Pardes, path: []const u8) void { + const s = &p.stream; + if (s.rows_paint != null or p.host.vtable.search == null) return; + // Asked while a 9P write is served (a script's Grep): not now, as no + // paint is (the write would wait for it to settle); the next step asks. + if (p.fs.serving) { + s.rows_later = true; + return; + } + if (!syntax.readyApart(path)) return; + var content: ?[]const u8 = null; + var revision: u32 = 0; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output == null and std.mem.eql(u8, f.path, path)) { + content = f.content; + revision = f.revision; + break; + }; + if (content) |c| if (c.len > max_rows_paint_bytes) return; + const key = std.hash.Wyhash.hash(revision, path) | 1; + if (std.mem.indexOfScalar(u64, &s.rows_asked, key) != null) return; + const job = p.gpa.create(PaintJob) catch return; + const path_copy = p.gpa.dupe(u8, path) catch { + p.gpa.destroy(job); + return; + }; + const source = p.gpa.dupe(u8, content orelse "") catch { + p.gpa.free(path_copy); + p.gpa.destroy(job); + return; + }; + s.rows_asked[s.rows_asked_at] = key; + s.rows_asked_at +%= 1; + s.paint_count +%= 1; + const gen = paint_bit | (s.paint_count & ~paint_bit); + job.* = .{ .gpa = p.gpa, .out = p.gpa, .gen = gen, .serial = 0, .revision = revision, .start = 0, .path = path_copy, .source = source }; + s.rows_paint = .{ .job = job }; + p.emit(.{ .search = .{ .gen = gen } }); +} + +/// The biggest file whose colours query rows are painted from. +const max_rows_paint_bytes = 4 << 20; + +fn paintWork(io: std.Io, job: *PaintJob, ctx: ?*anyopaque, sink: Sink) void { + // A file's colours for query rows (paintRows, serial 0) with no text + // given: read here, off the loop, and sent back with the colours, the + // text they are of. + const read: []u8 = if (job.serial == 0 and job.source.len == 0) + std.Io.Dir.cwd().readFileAlloc(io, job.path, job.out, .limited(max_rows_paint_bytes)) catch @constCast(&[_]u8{}) + else + @constCast(&[_]u8{}); + const source = if (read.len > 0) read else job.source; // Stopped or failed, it still answers (with nothing), so the loop // knows to join it. - const styles: []u8 = syntax.highlightApart(job.out, job.path, job.source, &job.stop) catch @constCast(&[_]u8{}); - _ = sink(ctx, .{ .gen = job.gen, .styles = styles, .painted = .{ .serial = job.serial, .revision = job.revision, .start = job.start }, .end = .done }); + const styles: []u8 = syntax.highlightApart(job.out, job.path, source, &job.stop) catch @constCast(&[_]u8{}); + const text: []u8 = if (job.serial != 0 or read.len > 0) read else job.out.dupe(u8, job.source) catch @constCast(&[_]u8{}); + _ = sink(ctx, .{ .gen = job.gen, .rows = text, .styles = styles, .painted = .{ .serial = job.serial, .revision = job.revision, .start = job.start }, .end = .done }); } /// A paint's answer: its task joined, its stretch kept for when the view @@ -322,6 +394,22 @@ fn paintWork(job: *PaintJob, ctx: ?*anyopaque, sink: Sink) void { fn receivePaint(p: *Pardes, b: *const Batch) void { const s = &p.stream; const painted = b.painted.?; + // A file's colours for query rows: kept where the rows find them, and + // the rows coloured from them (which asks for the next file). + if (s.rows_paint) |t| if (t.job.gen == b.gen) { + s.rows_paint = null; + if (t.future) |f| { + pardes.turn.yield(); + var future = f; + future.await(t.io.?); + pardes.turn.back(); + } + defer t.job.deinit(); + p.locations_cache.put(p.tree_sitter_gpa, t.job.path, b.rows, b.styles) catch {}; + panes.Query.recolor(p); + p.needs_frame = true; + return; + }; // Its task joined: it has sent its last, so the join is a return away. for ([_]*?PaintTask{ &s.paint, &s.paint_retired }) |slot| if (slot.*) |t| if (t.job.gen == b.gen) { slot.* = null; @@ -436,6 +524,7 @@ pub fn query(p: *Pardes, target: u32, kind: Kind, pattern: []const u8, dir: []co s.first_ns = null; s.state = .waiting; s.due_ns = if (how == .typed) p.now_ns + debounce_ns else p.now_ns; + if (kind == .grep) s.rows_asked = @splat(0); } /// Over: the worker canceled, nothing more of it lands. @@ -502,11 +591,11 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*an const s = &p.stream; // A paint's generation: its own task, its own worker. if (gen & paint_bit != 0) { - if (s.paint) |*t| if (t.job.gen == gen and t.future == null) { + for ([_]*?PaintTask{ &s.paint, &s.rows_paint }) |slot| if (slot.*) |*t| if (t.job.gen == gen and t.future == null) { t.job.out = gpa; - t.future = io.concurrent(paintWork, .{ t.job, ctx, sink }) catch { + t.future = io.concurrent(paintWork, .{ io, t.job, ctx, sink }) catch { const job = t.job; - s.paint = null; + slot.* = null; job.deinit(); return; }; @@ -555,6 +644,16 @@ fn makeJob(gpa: std.mem.Allocator, s: *const Stream) !*Job { /// the whole search on the loop, the turn out for it, its batches taken in /// as a worker's would be. Its cap is a hard stop. pub fn runHere(p: *Pardes, gen: u32) void { + // A paint with no worker to run it (a shell not threaded yet): let go, + // never left to hold its slot; the rows or the view ask again. + if (gen & paint_bit != 0) { + const s = &p.stream; + for ([_]*?PaintTask{ &s.paint, &s.rows_paint }) |slot| if (slot.*) |t| if (t.job.gen == gen and t.future == null) { + slot.* = null; + t.job.deinit(); + }; + return; + } if (comptime !filesystem.platform_has_fs) { p.stream.state = .failed; return; @@ -1395,3 +1494,162 @@ test "Stream: a Grep stops at its 2000 lines and waits; More in the query pane's try testing.expectEqual(@as(usize, 3000), qp.query.?.found.items.len); try testing.expect(!qp.query.?.capped); } + +test "zz grep rows timings: a Grep of about 2000 rows on the stress file, a worker (GREP_TIMES=)" { + const Key = pardes.Key; + const path_z = std.c.getenv("GREP_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const bytes = try std.Io.Dir.cwd().readFileAlloc(testing.io, path, testing.allocator, .limited(8 << 20)); + defer testing.allocator.free(bytes); + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + p.advance(1); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + p.stream.cancelParse(); + p.stream.cancelPaint(); + shell.q.deinit(); + } + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const Stats = struct { + fn print(name: []const u8, xs: []u64) void { + if (xs.len == 0) return; + std.mem.sort(u64, xs, {}, std.sort.asc(u64)); + std.debug.print("{s}: n {d} p50 {d} us p90 {d} us max {d} us\n", .{ name, xs.len, xs[xs.len / 2] / 1000, xs[xs.len * 9 / 10] / 1000, xs[xs.len - 1] / 1000 }); + } + }; + var keys: std.ArrayList(u64) = .empty; + defer keys.deinit(testing.allocator); + var refills: std.ArrayList(u64) = .empty; + defer refills.deinit(testing.allocator); + var idle: std.ArrayList(u64) = .empty; + defer idle.deinit(testing.allocator); + panes.Query.open(p, 0, .grep, "", true); + const qid = p.active; + const q = p.panes[qid].?.query.?; + for (0..3) |round| { + for ("pane") |c| { + const t0 = now(); + p.advance(t0); + p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try keys.append(testing.allocator, now() - t0); + // the frames till the next key: the debounce, the batches, the paints + const until = now() + 400 * std.time.ns_per_ms; + while (now() < until) { + const made = q.made_gen; + const t1 = now(); + p.advance(t1); + shell.pump(p); + p.update(.tick); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try (if (q.made_gen != made) &refills else &idle).append(testing.allocator, now() - t1); + testing.io.sleep(.fromMilliseconds(2), .awake) catch {}; + } + } + // back to an empty pattern for the next round + if (round < 2) for (0..4) |_| p.update(.{ .key = .{ .cp = Key.backspace } }); + } + // Enter: the whole list frozen, 2000 rows, and the frames after it. + var after: std.ArrayList(u64) = .empty; + defer after.deinit(testing.allocator); + const t3 = now(); + p.advance(t3); + p.update(.{ .key = .{ .cp = Key.enter } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const t_enter = now() - t3; + const until = now() + 1000 * std.time.ns_per_ms; + while (now() < until) { + const t1 = now(); + p.advance(t1); + shell.pump(p); + p.update(.tick); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try after.append(testing.allocator, now() - t1); + testing.io.sleep(.fromMilliseconds(2), .awake) catch {}; + } + var coloured: usize = 0; + for (p.panes[qid].?.file.?.location_rows) |row| coloured += @intFromBool(row.kind == .match and std.mem.indexOfNone(u8, row.colors, &.{0}) != null); + std.debug.print("grep rows: {d} found ({s}), {d} rows frozen, {d} coloured; Enter (2000 rows written) {d} us\n", .{ q.found.items.len, @tagName(p.stream.used), p.panes[qid].?.file.?.location_rows.len, coloured, t_enter / 1000 }); + Stats.print("frames after Enter", after.items); + Stats.print("keystroke (update + render)", keys.items); + Stats.print("refill frame (pump + tick + render, rows remade)", refills.items); + Stats.print("other frames", idle.items); +} + +test "Stream: a Grep's rows are coloured as their file's language colours them, the file painted on a worker, the match tint on top" { + if (comptime !filesystem.platform_has_fs) return; + if (!syntax.enabled or !syntax.readyApart("c.zig")) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const text = "const std = @import(\"std\");\npub fn value() u32 {\n return 42; // value\n}\n"; + try tmp.dir.writeFile(testing.io, .{ .sub_path = "c.zig", .data = text }); + var root_buf: [4096]u8 = undefined; + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + // the file open in the pane that asks: its text painted, not the disk's + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ root, "c.zig" }); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + p.stream.cancelPaint(); + shell.q.deinit(); + } + panes.Query.open(p, 0, .grep, "value", false); + const qid = for (p.panes, 0..) |slot, i| { + if (slot) |qp| if (qp.query != null) break i; + } else return error.NoQueryPane; + const f = &p.panes[qid].?.file.?; + var halt: std.atomic.Value(bool) = .init(false); + const own = try syntax.highlightApart(testing.allocator, "c.zig", text, &halt); + defer testing.allocator.free(own); + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const until = now() + 10 * std.time.ns_per_s; + var coloured: usize = 0; + while (now() < until) { + p.advance(now()); + shell.pump(p); + p.update(.tick); + // a frame each, as a shell draws: the rows painted before their colours land + _ = arena.reset(.retain_capacity); + _ = try p.render(arena.allocator()); + coloured = 0; + for (f.location_rows) |row| if (row.kind == .match and row.location_end > 0 and std.mem.indexOfNone(u8, row.colors, &.{0}) != null) { + coloured += 1; + }; + if (coloured == 2 and p.stream.rows_paint == null) break; + testing.io.sleep(.fromMilliseconds(2), .awake) catch {}; + } + try testing.expectEqual(@as(usize, 2), coloured); + // and painted: the frame's colours are the rows' + _ = arena.reset(.retain_capacity); + _ = try p.render(arena.allocator()); + // each row's colours its line's, byte for byte; the match tinted over them + var lines = std.mem.splitScalar(u8, f.content, '\n'); + for (f.location_rows) |row| { + const line = lines.next().?; + if (row.kind != .match or row.location_end == 0) continue; + const ls = @import("modal.zig").lineStartOffset(text, row.at.line - 1); + try testing.expectEqualSlices(u8, own[ls + row.source_column ..][0..row.colors.len], row.colors); + const at = @intFromPtr(line.ptr) - @intFromPtr(f.content.ptr) + row.code_start - f.highlight_start; + try testing.expectEqualSlices(u8, row.colors, f.highlights[at..][0..row.colors.len]); + const dec = panes.Output.decorateRow(f.output, line, row); + try testing.expectEqualStrings("value", line[dec.mark_start..dec.mark_end]); + } +} diff --git a/src/locations.zig b/src/locations.zig index 6f086214..cdb228a6 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -814,6 +814,40 @@ pub const Cache = struct { return .{ .analysis = next.analysis }; } + /// The analysis kept for `path` with its colours, if any, of whatever + /// source it was made from (a caller compares the lines it uses): + /// never parses. Borrowed, as `get`'s. + pub fn peek(cache: *const Cache, path: []const u8) ?struct { source: []const u8, colors: []const u8 } { + for (cache.entries[0..cache.len]) |entry| if (entry.colors_ready and std.mem.eql(u8, entry.path, path)) + return .{ .source = entry.source, .colors = entry.analysis.colors }; + return null; + } + + /// `source`'s colours, worked out elsewhere (a worker's, Stream.paintRows), + /// kept for `path` in place of what was: copies of both. + pub fn put(cache: *Cache, gpa: std.mem.Allocator, path: []const u8, source: []const u8, colors: []const u8) !void { + if (path.len + source.len + colors.len > max_bytes) return error.SourceTooLarge; + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + const owned_source = try gpa.dupe(u8, source); + errdefer gpa.free(owned_source); + const next: Entry = .{ + .path = owned_path, + .source = owned_source, + .analysis = .{ .colors = try gpa.dupe(u8, colors) }, + .declarations_ready = false, + .colors_ready = true, + }; + for (cache.entries[0..cache.len], 0..) |entry, index| if (std.mem.eql(u8, entry.path, path)) { + cache.remove(gpa, index); + break; + }; + while (cache.len == max_entries or cache.bytes > max_bytes - next.size()) cache.remove(gpa, 0); + cache.entries[cache.len] = next; + cache.len += 1; + cache.bytes += next.size(); + } + fn remove(cache: *Cache, gpa: std.mem.Allocator, index: usize) void { cache.bytes -= cache.entries[index].size(); cache.entries[index].deinit(gpa); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index d9bd4372..9cb96667 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -3059,8 +3059,9 @@ test "a script's Grep and Find fill the pane's one query pane, a row a line unde const rows = grepped.file.?.content; try testing.expect(std.mem.startsWith(u8, rows, "Grep bravo\n")); try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt\n") != null); - try testing.expect(std.mem.indexOf(u8, rows, "2 bravo here\n") != null); - try testing.expect(std.mem.indexOf(u8, rows, "3 three bravo\n") != null); + // each row its place as text, `path:line:col`, the code in one column + try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt:2:1 bravo here\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt:3:7 three bravo\n") != null); try testing.expectEqual(@as(usize, 2), grepped.query.?.total); try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); const found = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index f7e5bba6..b195e7a5 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -31,9 +31,9 @@ == snap typing grid=180x31 cursor=7,10 |9: ^ +Search 1/3 Del |10: /MARK -|11: 2 MARK a -|12: 6 MARK b -|13: 10 MARK c +|11: g.txt:2:1 MARK a +|12: g.txt:6:1 MARK b +|13: g.txt:10:1 MARK c == style typing grid=180x31 |0: 0-1 d,#1d2824, 2-179 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-89 #becfc4,#314738, 90-91 #becfc4,#887455, 92-179 #b2c3b8,#1d2824, @@ -46,9 +46,9 @@ |8: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |9: 0-1 #000000,#add38a, 2-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, |10: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#243a2d, 14-89 #e5eee5,#243a2d, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|13: 0-0 d,#608269, 1-4 d,#0d1410, 5-8 #59675c,#0d1410, 9-12 #f7e4a5,#352e19, 13-13 #f7e4a5,#0d1410, 14-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#243a2d, 16-19 #f7e4a5,#5e4923, 20-20 #f7e4a5,#243a2d, 21-89 #e5eee5,#243a2d, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-19 #f7e4a5,#352e19, 20-20 #f7e4a5,#0d1410, 21-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-15 #59675c,#0d1410, 16-19 #f7e4a5,#352e19, 20-20 #f7e4a5,#0d1410, 21-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |14: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |15: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, |16: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 6dbe19fa..165839f7 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -23,7 +23,7 @@ |9: ^ +Search 1/3 Del |10: Grep TARGET |11: a.txt -|12: 1 hello TARGET one +|12: a.txt:1:7 hello TARGET one |13: /tmp/pardes-snap/grep/cwd/+Preview Del |14: 1 == snap second grid=180x31 cursor=13,10 diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 2c0aa63d..8f5908bb 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -71,8 +71,8 @@ == snap hit1 grid=150x31 cursor=17,15 |21: +Search 2/2 Save Unattach Del |22: /NEEDLE -|23: 7 gg NEEDLE gg -|24: 8 hhhh NEEDLE +|23: r.txt:7:4 gg NEEDLE gg +|24: r.txt:8:6 hhhh NEEDLE == style hit1 grid=150x31 |14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, @@ -80,21 +80,21 @@ |18: 0-0 d,#e5eee5, 1-149 d,#0d1410, |21: 0-1 d,#496656, 2-149 #b2c3b8,#1d2824, |22: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, -|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-13 #e5eee5,#243a2d, 14-19 #f7e4a5,#5e4923, 20-149 #f7e4a5,#243a2d, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-17 #e5eee5,#0d1410, 18-23 #f7e4a5,#352e19, 24-24 #f7e4a5,#0d1410, 25-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-19 #e5eee5,#243a2d, 20-25 #f7e4a5,#5e4923, 26-149 #f7e4a5,#243a2d, == snap hit2 grid=150x31 cursor=15,14 == style hit2 grid=150x31 |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-17 #e5eee5,#352e19, 18-149 #e5eee5,#0d1410, |16: 0-0 d,#e5eee5, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |18: 0-0 d,#5e4923, 1-149 d,#0d1410, -|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#5e4923, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-13 #e5eee5,#243a2d, 14-19 #f7e4a5,#352e19, 20-149 #f7e4a5,#243a2d, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-17 #e5eee5,#0d1410, 18-23 #f7e4a5,#5e4923, 24-24 #f7e4a5,#0d1410, 25-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-19 #e5eee5,#243a2d, 20-25 #f7e4a5,#352e19, 26-149 #f7e4a5,#243a2d, == snap back grid=150x31 cursor=17,15 == style back grid=150x31 |14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #e5eee5,#352e19, 16-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #e5eee5,#0d1410, 12-17 #f5f7ee,#3c614a, 18-149 #f5f7ee,#0d1410, |16: 0-0 d,#5e4923, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |18: 0-0 d,#e5eee5, 1-149 d,#0d1410, -|23: 0-0 d,#608269, 1-5 d,#0d1410, 6-8 #59675c,#0d1410, 9-11 #e5eee5,#0d1410, 12-17 #f7e4a5,#352e19, 18-18 #f7e4a5,#0d1410, 19-149 #e5eee5,#0d1410, -|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 d,#243a2d, 6-8 #59675c,#243a2d, 9-13 #e5eee5,#243a2d, 14-19 #f7e4a5,#5e4923, 20-149 #f7e4a5,#243a2d, +|23: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-17 #e5eee5,#0d1410, 18-23 #f7e4a5,#352e19, 24-24 #f7e4a5,#0d1410, 25-149 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-19 #e5eee5,#243a2d, 20-25 #f7e4a5,#5e4923, 26-149 #f7e4a5,#243a2d, diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index f3d7006e..670d6a86 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -20,9 +20,9 @@ |13: +Search 1/3 Del |14: Refs |15: lib.rs -|16: 2 pub fn add(a: i32, b: i32) -> i32 { +|16: lib.rs:2:8 pub fn add(a: i32, b: i32) -> i32 { |17: main.rs -|18: 4 let x = add(1, 2); +|18: main.rs:4:13 let x = add(1, 2); |19: /tmp/pardes-snap/lsp-client/cwd/+Preview Del |20: 1 == snap gr-opened grid=100x25 cursor=21,6 diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index dacb6b89..3af53a5c 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -17,10 +17,10 @@ | | +Search 2/2 Del | Refs -| /tmp/pardes-snap/lsprelpath/cwd/shade.zig -| 1 pub const Shade = enum { +| ../shade.zig +| ../shade.zig:1:11 pub const Shade = enum { | parent.zig -| 3 pub fn pick(s: shade.Shade) u8 { +| parent.zig:3:22 pub fn pick(s: shade.Shade) u8 { | | | @@ -56,15 +56,15 @@ |16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, |17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-7 d,#243a2d, 8-10 #59675c,#243a2d, 11-20 #e5eee5,#243a2d, 21-25 #f7e4a5,#5e4923, 26-26 #f7e4a5,#243a2d, 27-99 #e5eee5,#243a2d, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-21 #59675c,#243a2d, 22-31 #e5eee5,#243a2d, 32-36 #f7e4a5,#5e4923, 37-37 #f7e4a5,#243a2d, 38-39 #e5eee5,#243a2d, 40-44 #c9a7ed,#243a2d, 45-99 #e5eee5,#243a2d, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-31 #e5eee5,#0d1410, 32-36 #f7e4a5,#5e4923, 37-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-23 #e5eee5,#0d1410, 24-26 #c9a7ed,#0d1410, 27-40 #e5eee5,#0d1410, 41-45 #f7e4a5,#5e4923, 46-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, |24: 0-0 d,#608269, 1-99 d,#0d1410, |25: 0-0 d,#608269, 1-99 d,#0d1410, |26: 0-1 d,#add38a, 2-33 #becfc4,#314738, 34-43 #dfbce5,#314738, 44-99 #becfc4,#314738, -|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, +|27: 0-0 d,#e5eee5, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, |28: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |29: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |30: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, @@ -92,9 +92,9 @@ | +Search 2/2 Del | Refs | inner/tint.zig -| 1 pub const Tint = enum { +| inner/tint.zig:1:11 pub const Tint = enum { | subdir.zig -| 3 pub fn hue(t: tint.Tint) u8 { +| subdir.zig:3:20 pub fn hue(t: tint.Tint) u8 { | | | @@ -130,15 +130,15 @@ |16: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, |17: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-7 d,#243a2d, 8-10 #59675c,#243a2d, 11-20 #e5eee5,#243a2d, 21-24 #f7e4a5,#5e4923, 25-25 #f7e4a5,#243a2d, 26-99 #e5eee5,#243a2d, +|19: 0-0 d,#608269, 1-1 d,#0d1410, 2-23 #59675c,#243a2d, 24-33 #e5eee5,#243a2d, 34-37 #f7e4a5,#5e4923, 38-38 #f7e4a5,#243a2d, 39-40 #e5eee5,#243a2d, 41-45 #c9a7ed,#243a2d, 46-99 #e5eee5,#243a2d, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|21: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-29 #e5eee5,#0d1410, 30-33 #f7e4a5,#5e4923, 34-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-19 #59675c,#0d1410, 20-23 #e5eee5,#0d1410, 24-26 #c9a7ed,#0d1410, 27-38 #e5eee5,#0d1410, 39-42 #f7e4a5,#5e4923, 43-99 #e5eee5,#0d1410, |22: 0-0 d,#608269, 1-99 d,#0d1410, |23: 0-0 d,#608269, 1-99 d,#0d1410, |24: 0-0 d,#608269, 1-99 d,#0d1410, |25: 0-0 d,#608269, 1-99 d,#0d1410, |26: 0-1 d,#add38a, 2-43 #becfc4,#314738, 44-52 #dfbce5,#314738, 53-99 #becfc4,#314738, -|27: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, +|27: 0-0 d,#e5eee5, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, |28: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |29: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |30: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, diff --git a/test/snapshots/lsprelpath.snap b/test/snapshots/lsprelpath.snap index 70ca3fdc..152a13a3 100644 --- a/test/snapshots/lsprelpath.snap +++ b/test/snapshots/lsprelpath.snap @@ -1,19 +1,18 @@ # What a language row SPELLS its path as, and that both spellings still LOOK. # -# A row is written relative to the directory of the file the query was asked -# about (lsp.rel, fed from Req.root) when the answer lives UNDER that directory, -# and keeps its full absolute path when it does not — a `gr` list was otherwise +# A row spells its path the shortest way a Look from the query pane resolves +# (Query.lookPath): relative to the pane's directory, `../` included, when that +# is shorter than the absolute path, else absolute — a `gr` list was otherwise # the same forty-character prefix repeated down the pane with the part you came -# to read pushed off the right edge, and a path outside the tree has nothing -# short to be called. +# to read pushed off the right edge. # # A row in the SAME directory shortens to a bare basename; the two that a -# prefix strip can actually get wrong are here, one app each, as `gr` rows +# careless shortening can get wrong are here, one app each, as `gr` rows # (the file headers of the asking text's query pane, line 1 `Refs`): # -# PARENT the enum is one level UP from the asking file, so nothing is -# stripped and the row carries `/tmp/.../cwd/shade.zig`. This is -# the case that must NOT become `../shade.zig`. +# PARENT the enum is one level UP from the asking file, so the row +# climbs: `../shade.zig`, shorter than `/tmp/.../cwd/shade.zig`, +# and a Look from the pane still lands on it. # SUBDIRECTORY the enum is one level DOWN, so the strip leaves a path with a # separator still in it — `inner/tint.zig`, not `tint.zig`. A # strip that took the basename instead would produce a row that @@ -29,7 +28,7 @@ file shade.zig pub const Shade = enum {\n verdigris,\n cinnabar,\n};\n file sub/inner/tint.zig pub const Tint = enum {\n ochre,\n indigo,\n};\n file sub/parent.zig const shade = @import("../shade.zig");\n\npub fn pick(s: shade.Shade) u8 {\n return switch (s) {\n \n };\n}\n file sub/subdir.zig const tint = @import("inner/tint.zig");\n\npub fn hue(t: tint.Tint) u8 {\n return switch (t) {\n \n };\n}\n -# ---- PARENT: outside the asking file's tree, so the row stays absolute ---- +# ---- PARENT: outside the asking file's tree, so the row climbs ---- start 35 100 sub/parent.zig wait 8000 fn pick stable 700 20000 @@ -39,8 +38,8 @@ stable 400 5000 key g key r # the query pane under parent.zig, line 1 `Refs`, the rows under each file: -# shade.zig's spelled whole, its directory being above -wait 15000 cwd/shade.zig +# shade.zig's spelled from above, `../shade.zig` +wait 15000 ../shade.zig:1 stable 700 15000 snap absrow # the current row is parent.zig's own; the one before it is shade.zig's, diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index a406597c..33eea330 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -14,10 +14,10 @@ |^ +Search 1/3 Del | Grep ZQMARK | a.txt -| 1 hello ZQMARK one -| 2 see also sub/b.txt for ZQMARK two +| a.txt:1:7 hello ZQMARK one +| a.txt:2:24 see also sub/b.txt for ZQMARK two | sub/b.txt -| 1 ZQMARK inside sub +| sub/b.txt:1:1 ZQMARK inside sub | | | @@ -41,10 +41,10 @@ |12: 0-1 #000000,#add38a, 2-149 #becfc4,#314738, |13: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, -|15: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #e5eee5,#0d1410, 17-22 #f7e4a5,#5e4923, 23-23 #f7e4a5,#0d1410, 24-149 #e5eee5,#0d1410, -|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-7 d,#243a2d, 8-10 #59675c,#243a2d, 11-33 #e5eee5,#243a2d, 34-39 #f7e4a5,#5e4923, 40-40 #f7e4a5,#243a2d, 41-149 #e5eee5,#243a2d, +|15: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#0d1410, 15-20 #e5eee5,#0d1410, 21-26 #f7e4a5,#5e4923, 27-27 #f7e4a5,#0d1410, 28-149 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-1 d,#0d1410, 2-14 #59675c,#243a2d, 15-37 #e5eee5,#243a2d, 38-43 #f7e4a5,#5e4923, 44-44 #f7e4a5,#243a2d, 45-149 #e5eee5,#243a2d, |17: 0-0 d,#608269, 1-1 d,#0d1410, 2-149 #e5eee5,#0d1410, -|18: 0-0 d,#608269, 1-7 d,#0d1410, 8-10 #59675c,#0d1410, 11-16 #f7e4a5,#5e4923, 17-17 #f7e4a5,#0d1410, 18-149 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-1 d,#0d1410, 2-18 #59675c,#0d1410, 19-24 #f7e4a5,#5e4923, 25-25 #f7e4a5,#0d1410, 26-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-149 d,#0d1410, |20: 0-0 d,#608269, 1-149 d,#0d1410, |21: 0-0 d,#608269, 1-149 d,#0d1410, diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index cf690a40..06798df3 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -153,8 +153,8 @@ == snap search-prompt grid=100x31 cursor=5,21 |20: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del |21: /ZZ -|22: 1 ZZONE -|23: 2 ZZTWO +|22: bottom.txt:1:1 ZZONE +|23: bottom.txt:2:1 ZZTWO |30: ^ +Search 1/2 Del == snap leader grid=100x31 cursor=9,13 |12: 1 ZZONE SPC -- cgit v1.3