//! 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 Stream = @import("Stream.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, 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 /// 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, 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 (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. 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 // 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: // 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) { // 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. exec.placeNew(p, owner_id, owner_id, free, .doc); } if (with_preview) _ = makePreview(p, free, preview_rows, owner_id); 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 p.stream.busyFor(pane.serial) 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 (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_gen +%= 1; q.grep_at = 0; q.current = null; // On the disk engine's worker, once the typing pauses. // 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); } 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, false) catch |err| p.reportError(id, "search", err); }, .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(); const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; const gpa = p.gpa; 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); if (p.fs.serving) Stream.step(p); }, .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, 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"); 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; // 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); // 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) { 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; // 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; // 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 { 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; 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"); 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 &.{}; q.total = q.names.hits.items.len; 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); showCurrent(rp); 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`). pub const grep_cap = 2000; /// 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 = @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 -| 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)) { 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]; 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, &.{}); } 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"); 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. 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 { _ = 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); // 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 { 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 ""; // 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); 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; // 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 = @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; } 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); 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); 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 }; // 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); } /// 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]; 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].?; 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; } }; // 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); 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); } /// 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 /// 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`, `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 "/"; 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); if (!layout.attachFrom(p, qid, free, rows, giver)) { 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, 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)) { 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; }; // 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 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; } // 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, 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 {}; } /// 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); }; } // ---- 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; // 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') { step(p, id, if (k.cp == 'n') 1 else -1); 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); 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); return true; } if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) { land(p, id, null); return true; } 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; } 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); // 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); 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 { // 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); } 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; }