//! 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'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 //! 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. 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 Store = @import("Store.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: j or k onto a row makes it current /// (a caret B1 put there is only a caret). seen_row: i32 = 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 { pub const replica = .{ .blob = .{"rows"} }; 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 owner's query pane (attached to it, or left where it was by /// Unattach): 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) |reused| { id = reused; 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); // 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) + born_rows, layout.groupRoot(p, id)); } else 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, 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; } /// The body rows a query pane is born with under its line 1 (and its /// +Preview with): it never resizes itself after. pub const born_rows: u16 = 8; /// A new query pane under pane `owner_id`, `born_rows` of the owner's rows, /// 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 + born_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 + born_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 (!layout.attachFrom(p, owner_id, free, want, owner_id)) { // 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 locations.cloneRows(p.gpa, f.location_rows); errdefer locations.freeRows(p.gpa, rows); 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, 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; produce(p, id, tick, keyed); } } /// 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; } /// `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; 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, rp.serial, owner_id); } 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 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 (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); } } 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(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) 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, 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(); var lines = std.mem.splitScalar(u8, pardes.tape.authority(recentRows, .{ p, &out }), '\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; } // 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. The // session's, which a replica has from the authority. for (pardes.tape.authority(Store.closedNames, .{p})) |c| { 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; 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 => {}, } } /// What a Panes row of a closed pane ends with. const closed_word = " (closed)"; /// Every session's files, as a Recent query lists them: what the others /// wrote since, read first. The session's (`tape.authority`): in `out`. fn recentRows(p: *Pardes, out: *std.Io.Writer.Allocating) []const u8 { p.db.readRecent(p); Output.recentText(p, &out.writer, true) catch {}; return out.written(); } /// 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 and colours 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'); // 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)..]; var m = meta; if (meta.colors.len >= code.len) m.colors = meta.colors[0..code.len] else { m.colors = try p.scratch.allocator().alloc(u8, code.len); @memset(m.colors, 0); @memcpy(m.colors[0..meta.colors.len], meta.colors); } try locations.appendRow(p.gpa, rows, m); } /// 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; dropHighlights(p, f); } } else { File.setContent(p, f, content); locations.freeRows(p.gpa, f.location_rows); f.location_rows = meta; f.saved_revision = f.revision; } if (f.pager_spans.len > 0) p.gpa.free(f.pager_spans); f.pager_spans = &.{}; // 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; } /// 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 = max_line; while (n >= 10) : (n /= 10) digits += 1; return rel.len + 1 + digits + 1 + 3; } /// 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: [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 = address.len, .code_start = gutter, .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'); // The rows are a blob (File.State): a digest keeps its word for // them and a rollback copy pins them, so they are made again, never // written. Written in place, a session's digest kept the word of // their colours before; a client joining hashed them after, and // loaded "as another session" (and so did a replica that hashed them // at another time). var fresh: ?[]locations.Row = null; for (f.location_rows, 0..) |row, i| { 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; const rows = fresh orelse locations.cloneRows(p.gpa, f.location_rows) catch break; fresh = rows; @memcpy(rows[i].colors[0..got.len], got); } if (fresh) |rows| { locations.freeRows(p.gpa, f.location_rows); f.location_rows = rows; 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 { 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 ""; } /// 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. fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, dir: []const u8, from: usize, budget: *usize) !void { const f = &tp.file.?; const set = &tp.places; const hits = set.hits.items; const index = try File.lineIndex(p.gpa, f); 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); // the line of the first, found in the index var line: usize = if (i < hits.len) Places.lineOf(index, hits[i].start) 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"); // 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, 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, &sh, width, rel, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); i += n; } } /// 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; 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 " ..."); } try writePlacesRows(p, q, &out, &rows, owner, std.fs.path.dirname(rp.file.?.path) orelse "/", from, &budget); } 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 = Places.lineOf(File.lineIndex(p.gpa, &owner.file.?) catch &.{}, 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, 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); // 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) !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 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); // 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); 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'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); // 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); 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; var sh: Shades = .{}; var width: usize = 0; var relbuf: [4096]u8 = undefined; for (q.found.items[lo..hi], lo..) |fd, i| { 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, &sh, width, rel, 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) else if (!shown) showTarget(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, serial: u32, pat: []const u8) void { 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); // 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; caretTo(rp, q.current orelse 0); showTarget(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 ""; // 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; 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, 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; // 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, &sh, width, rel, 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_ask.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, serial: u32, owner_id: ?usize) void { 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(tp); tp.places.clear(p.gpa); } } // ---- the current row ---- /// 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 return; const r: i32 = @intCast(c + 1); // 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 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.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 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); _ = 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. 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 = pardes.tape.site(.preview, p.gpa, 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; // another file: its own places, found below pane.places.clear(p.gpa); 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); // 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) { // the place's whole line, selected back from its end pane.body.vsel = .{ .active = true, .row = @intCast(at.line - 1), .col = @intCast(File.textLine(&pane.body, f.content, at.line - 1).len), .explicit = true }; pane.body.cur_row = @intCast(at.line - 1); pane.body.cur_col = 0; } } /// 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.jumps.force = true; p.active = oid; return; } const f = &rp.file.?; // A current row whose place went with its text (a frozen pane's rows // edited: setContentSpan drops them, and an Esc's `saved` keeps that) // is none: there is nowhere to land, as with no current one. const current = if (q.current) |i| (if (i < q.items.items.len and i + 1 < f.location_rows.len) i else null) else null; const c = current orelse { if (owner_id) |oid| p.active = oid; return; }; const it = q.items.items[c]; const meta = f.location_rows[c + 1]; p.jumps.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; } // 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 => {}, } // 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. 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); } /// 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(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; else 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 != null 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 // 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; } // 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; } 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 (panes.paneIdOf(p, 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 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; 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 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. 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.cols[0].panes[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 dump holding a query pane, live or frozen, restores it as it was" { 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].?; const was = p.panes[qid].?; try std.testing.expectEqual(was.query.?.frozen, back.query.?.frozen); try std.testing.expectEqual(was.file.?.location_rows.len, back.file.?.location_rows.len); try std.testing.expectEqualStrings(was.file.?.content, back.file.?.content); 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(); 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), 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")); 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.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.clock.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.cols[0].panes[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 "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration" { 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; } 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_ask.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_ask.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_ask.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); } 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"); typeKeys(p, "/alpha"); const qid = queryPane(p).?; const qp = p.panes[qid].?; const q = qp.query.?; p.presented(); const owner_sel = pane.body.primaryRange(pane.file.?.content, 0); const owner_scroll = pane.file.?.scroll; try std.testing.expectEqual(@as(?usize, 0), q.current); const place = pane.places.current; const r = p.rects[qid]; 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(@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(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(@as(?usize, 0), q.current); try std.testing.expectEqual(owner_sel, pane.body.primaryRange(pane.file.?.content, 0)); // 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, "n"); 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 = 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, 3), pane.body.cur_row); } test "Enter on a frozen query pane's rows after its text was edited: no row to land on, the keyboard to its owner" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); _ = try p.setTestFile("alpha\n"); p.newScratchBelow(0); p.active = 0; // SPC b b and Enter: the current row lands, the rows frozen. leader(p, "bb"); const qid = queryPane(p).?; p.update(.{ .key = .{ .cp = Key.enter } }); const qp = p.panes[qid].?; try std.testing.expect(qp.query.?.frozen and qp.query.?.current != null); // Its text edited: the rows' places go with the text they were of. p.active = qid; typeKeys(p, "ggjxd"); try std.testing.expectEqual(@as(usize, 0), qp.file.?.location_rows.len); try std.testing.expect(qp.body.cur_row > 0); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(@as(usize, 0), p.active); } 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.presented(); 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; } }