diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-24 11:57:26 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-24 11:57:35 -0300 |
| commit | 51903dd947f90381d1a908c488a019289a1c8413 (patch) | |
| tree | ab5b2574642493c60476e6e9bcd7cc0e1c5e8d9e /src | |
| parent | 18d89dcedaed1f8437799621675e88ca47d7cdc1 (diff) | |
| download | pardes-51903dd947f90381d1a908c488a019289a1c8413.tar.gz pardes-51903dd947f90381d1a908c488a019289a1c8413.zip | |
Search converge 3/6: the query pane, line 1 the query and its first word the source, rows made live like Callstack's, the owner's places showing the set, a +Preview promoted in place, Enter freezes, Esc restores
Diffstat (limited to 'src')
| -rw-r--r-- | src/File.zig | 2 | ||||
| -rw-r--r-- | src/Names.zig | 446 | ||||
| -rw-r--r-- | src/Output.zig | 8 | ||||
| -rw-r--r-- | src/Places.zig | 39 | ||||
| -rw-r--r-- | src/Query.zig | 2155 | ||||
| -rw-r--r-- | src/Text.zig | 5 | ||||
| -rw-r--r-- | src/body_layer.zig | 1 | ||||
| -rw-r--r-- | src/builtins.zig | 35 | ||||
| -rw-r--r-- | src/config.zig | 54 | ||||
| -rw-r--r-- | src/edit.zig | 20 | ||||
| -rw-r--r-- | src/exec.zig | 20 | ||||
| -rw-r--r-- | src/fs.zig | 2 | ||||
| -rw-r--r-- | src/layout.zig | 18 | ||||
| -rw-r--r-- | src/look.zig | 2 | ||||
| -rw-r--r-- | src/mouse.zig | 9 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 16 | ||||
| -rw-r--r-- | src/normal.zig | 16 | ||||
| -rw-r--r-- | src/panes.zig | 7 | ||||
| -rw-r--r-- | src/pardes.zig | 54 | ||||
| -rw-r--r-- | src/tagline.zig | 8 |
20 files changed, 2887 insertions, 30 deletions
diff --git a/src/File.zig b/src/File.zig index 3db22f95..f633cad0 100644 --- a/src/File.zig +++ b/src/File.zig @@ -598,6 +598,8 @@ pub fn gutterWidth(pane: *const Pane) u16 { // pager and delta show none. if (file.pager) return 0; if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; + // A query pane's rows carry their own line numbers (Query.zig). + if (pane.query != null) return 0; var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; diff --git a/src/Names.zig b/src/Names.zig new file mode 100644 index 00000000..48447f56 --- /dev/null +++ b/src/Names.zig @@ -0,0 +1,446 @@ +//! Names a query pane picks from by a fuzzy query: the files under a +//! directory (walked a slice a frame), the recent files, the open panes, +//! a file's declarations. Each keystroke scores them again with a small +//! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses +//! at the starts of words and path segments), a frame's budget at a time, +//! the best kept first. Lifted from the pick prototype (Pick.zig), whose +//! scorer took ~1 ms for 20k paths in a release build. Embedded in a +//! Query; the rows it shows are the Query's to make. +const Names = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const Pardes = pardes.Pardes; + +/// The candidates' rows, back to back, no newlines. +bytes: std.ArrayList(u8) = .empty, +/// `bytes` in lowercase, for a lowercase query to match without folding. +lower: std.ArrayList(u8) = .empty, +cands: std.ArrayList(Cand) = .empty, +/// The candidates `query` matches, best first. +hits: std.ArrayList(Hit) = .empty, +/// `cands[0..scored]` were scored against `query` (in `hits` or not): the +/// ones a walk adds past it are scored as they come. +scored: u32 = 0, +/// Candidates to score before `cands[scored..]`: what the last query +/// matched, when this one only grew from it. +pending: std.ArrayList(u32) = .empty, +pending_at: usize = 0, +query_buf: [max_query]u8 = undefined, +query_len: u8 = 0, +/// The files walk, while it lasts (Find in a query pane until the disk +/// engine has it). +walk: ?Walk = null, +/// Bumped whenever `hits` change: the rows are made again only then. +gen: u32 = 0, + +pub const Cand = struct { + /// The row: `bytes[start..][0..len]`. + start: u32, + len: u16, + /// What is scored: the row's `[key..][0..key_len]` (a path, a + /// declaration's text, a name), its basename from `base` within it. + key: u16, + key_len: u16, + base: u16, + /// What the row is of: a line of the owner (Symbols, 1-based), a + /// pane's serial (Panes); 0 for a path. + ref: u32 = 0, +}; + +pub const Hit = struct { cand: u32, score: i32 }; + +/// The most rows shown: the rest are counted. +pub const max_rows = 200; +pub const max_query = 64; +/// A candidate is scored over its first this many bytes. +const max_text = 512; +const max_cands = 200_000; +/// Entries a walk reads a frame: ~1-3 ms warm. +const walk_slice = 2000; +const walk_max_depth = 16; +/// A keystroke's scoring, and a frame's: what is left waits a frame. +const score_budget_ns = 4 * std.time.ns_per_ms; + +const Walk = struct { + root: std.Io.Dir, + walker: std.Io.Dir.SelectiveWalker, + done: bool = false, + skipped: u32 = 0, + + fn deinit(w: *Walk) void { + const io = std.Io.Threaded.global_single_threaded.io(); + // The walker closes a directory only as it leaves it: the ones it + // is still in (all but the root, which is ours) are closed here. + if (w.walker.stack.items.len > 1) for (w.walker.stack.items[1..]) |*item| item.iter.reader.dir.close(io); + w.walker.deinit(); + w.root.close(io); + } +}; + +pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { + if (n.walk) |*w| w.deinit(); + n.bytes.deinit(gpa); + n.lower.deinit(gpa); + n.cands.deinit(gpa); + n.hits.deinit(gpa); + n.pending.deinit(gpa); + n.* = .{}; +} + +/// No candidates, no walk: for a source filled again. +pub fn reset(n: *Names) void { + if (n.walk) |*w| w.deinit(); + n.walk = null; + n.bytes.clearRetainingCapacity(); + n.lower.clearRetainingCapacity(); + n.cands.clearRetainingCapacity(); + n.hits.clearRetainingCapacity(); + n.pending.clearRetainingCapacity(); + n.pending_at = 0; + n.scored = 0; + n.gen +%= 1; +} + +pub fn queryText(n: *const Names) []const u8 { + return n.query_buf[0..n.query_len]; +} + +pub fn add(n: *Names, gpa: std.mem.Allocator, row_in: []const u8, key: usize, key_len: usize, base: u16, ref: u32) !void { + if (n.cands.items.len >= max_cands) return; + const text = row_in[0..@min(row_in.len, std.math.maxInt(u16))]; + try n.cands.append(gpa, .{ + .start = @intCast(n.bytes.items.len), + .len = @intCast(text.len), + .key = @intCast(@min(key, text.len)), + .key_len = @intCast(@min(key_len, text.len - @min(key, text.len))), + .base = base, + .ref = ref, + }); + try n.bytes.appendSlice(gpa, text); + try n.lower.ensureUnusedCapacity(gpa, text.len); + for (text) |c| n.lower.appendAssumeCapacity(std.ascii.toLower(c)); +} + +pub fn relative(path: []const u8, dir: []const u8) []const u8 { + const d = std.mem.trimEnd(u8, dir, "/"); + if (d.len > 0 and path.len > d.len + 1 and std.mem.startsWith(u8, path, d) and path[d.len] == '/') return path[d.len + 1 ..]; + return path; +} + +pub fn baseOf(path: []const u8) u16 { + const slash = std.mem.lastIndexOfScalar(u8, std.mem.trimEnd(u8, path, "/"), '/') orelse return 0; + return @intCast(@min(slash + 1, max_text)); +} + +/// The files under `dir`, walked from now on a slice a frame (`walkSlice`): +/// the first slice now, so a small tree is whole before the first frame. +pub fn startWalk(n: *Names, gpa: std.mem.Allocator, dir: []const u8) !void { + if (comptime !filesystem.platform_has_fs) return error.NoFilesystem; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var dir_handle = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); + errdefer dir_handle.close(io); + n.walk = .{ .root = dir_handle, .walker = try dir_handle.walkSelectively(gpa) }; + n.walkSlice(gpa); +} + +/// One frame's slice of a walk: up to `walk_slice` entries, files kept, +/// what a Find skips skipped and dot-directories too. +pub fn walkSlice(n: *Names, gpa: std.mem.Allocator) void { + const w = if (n.walk) |*w| w else return; + if (w.done) return; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var steps: usize = 0; + walk: while (steps < walk_slice) : (steps += 1) { + const e = (w.walker.next(io) catch { + w.skipped += 1; + continue; + }) orelse { + w.done = true; + break; + }; + if (e.kind != .directory) { + n.add(gpa, e.path, 0, e.path.len, baseOf(e.path), 0) catch { + w.done = true; + break; + }; + if (n.cands.items.len >= max_cands) { + w.done = true; + break; + } + continue; + } + if (e.depth() >= walk_max_depth or e.basename[0] == '.') continue; + for (filesystem.find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; + w.walker.enter(io, e) catch { + w.skipped += 1; + }; + } +} + +pub fn walking(n: *const Names) bool { + return if (n.walk) |w| !w.done else false; +} + +/// Still walking, or still scoring what it has: it wants the next frame. +pub fn busy(n: *const Names) bool { + return n.walking() or n.scored < n.cands.items.len or n.pending_at < n.pending.items.len; +} + +/// A new query: scored again, from what the last one matched when it only +/// grew from it. +pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void { + const q = text[0..@min(text.len, max_query)]; + if (std.mem.eql(u8, q, n.queryText()) and n.scored > 0) return; + // A query that only grew matches a subset of what the last one did: + // only those are scored again (and then the ones not yet scored). + const grew = n.query_len > 0 and std.mem.startsWith(u8, q, n.queryText()) and std.mem.indexOfScalar(u8, q[n.query_len..], ' ') == null; + n.query_len = @intCast(q.len); + @memcpy(n.query_buf[0..q.len], q); + if (grew) { + const pending = n.pending.items[n.pending_at..]; + std.mem.copyForwards(u32, n.pending.items[0..pending.len], pending); + n.pending.items.len = pending.len; + n.pending.ensureUnusedCapacity(gpa, n.hits.items.len) catch return; + for (n.hits.items) |h| n.pending.appendAssumeCapacity(h.cand); + } else { + n.scored = 0; + n.pending.clearRetainingCapacity(); + } + n.pending_at = 0; + n.hits.clearRetainingCapacity(); + n.rescore(gpa); +} + +/// Scores the pending candidates, then `cands[scored..]`, into `hits`, and +/// sorts them: at most `score_budget_ns` of it a call, the rest on the +/// next frames while the best so far is shown. +pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { + const q = n.queryText(); + const empty = std.mem.trim(u8, q, " ").len == 0; + const io = std.Io.Threaded.global_single_threaded.io(); + const started = std.Io.Clock.awake.now(io); + const had = n.hits.items.len; + const was_scored = n.scored; + var count: usize = 0; + while (true) : (count += 1) { + const i: u32 = if (n.pending_at < n.pending.items.len) blk: { + n.pending_at += 1; + break :blk n.pending.items[n.pending_at - 1]; + } else if (n.scored < n.cands.items.len) blk: { + n.scored += 1; + break :blk n.scored - 1; + } else break; + const c = n.cands.items[i]; + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null, null); + if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break; + // The clock every 256 candidates: reading it is not free either. + if (!empty and count % 256 == 255 and + started.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds() > score_budget_ns) break; + } + // An empty query keeps the source's order (the walk's, recency): no + // row moves as the walk goes on, it only grows at the foot. + if (!empty) std.sort.pdq(Hit, n.hits.items, n.cands.items, struct { + fn lt(cands: []const Cand, a: Hit, b: Hit) bool { + if (a.score != b.score) return a.score > b.score; + const la = cands[a.cand].key_len; + const lb = cands[b.cand].key_len; + if (la != lb) return la < lb; + return a.cand < b.cand; + } + }.lt); + if (n.hits.items.len != had or n.scored != was_scored or count > 0) n.gen +%= 1; +} + +/// The row of hit `i` and, in `marks`, the bytes of it the query matched. +pub fn row(n: *const Names, i: usize, marks: []u16, nmarks: *usize) []const u8 { + const c = n.cands.items[n.hits.items[i].cand]; + nmarks.* = 0; + const q = n.queryText(); + if (std.mem.trim(u8, q, " ").len > 0) { + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + _ = match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, marks, nmarks, &dp_trace); + for (marks[0..nmarks.*]) |*m| m.* += c.key; + } + return n.bytes.items[c.start..][0..c.len]; +} + +// ---- the scorer (pick's) ---- + +const neg: i32 = -(1 << 24); +const score_match = 16; +const gap_start = 3; +const gap_ext = 1; +const bonus_consecutive = 7; +/// At the start of the text or of a path segment. +const bonus_start = 12; +/// After `_ - . : space`. +const bonus_delim = 9; +/// A camelCase hump, or a word after other punctuation. +const bonus_camel = 8; +/// Each matched character in the basename. +const bonus_base = 2; + +/// The scorer's two rows, and the whole table the marks are backtracked +/// through: the main loop's, one score at a time. Not locals: a safe build +/// fills an undefined local, 4 KB a candidate, which was most of a +/// keystroke's time. +var dp_rows: [2][max_text]i32 = undefined; +var dp_trace: [max_query * max_text]i32 = undefined; + +fn bonusAt(text: []const u8, j: usize) i32 { + if (j == 0) return bonus_start; + const prev = text[j - 1]; + const c = text[j]; + if (prev == '/') return bonus_start; + switch (prev) { + '_', '-', '.', ':', ' ', '\t' => return bonus_delim, + else => {}, + } + if (std.ascii.isLower(prev) and std.ascii.isUpper(c)) return bonus_camel; + if (!std.ascii.isAlphanumeric(prev) and std.ascii.isAlphanumeric(c)) return bonus_camel; + return 0; +} + +/// `query`'s score against `text` (`lower` its lowercase copy, its +/// basename from `base`), null if some term of it is not a subsequence of +/// `text`. Terms split on spaces are ANDed; smart case per term. With +/// `marks`, the bytes matched are written there, ascending. +pub fn match(query: []const u8, text_in: []const u8, lower_in: []const u8, base: usize, marks: ?[]u16, marks_len: ?*usize, trace: ?[]i32) ?i32 { + const text = text_in[0..@min(text_in.len, max_text)]; + const lower = lower_in[0..text.len]; + var total: i32 = 0; + var nmarks: usize = 0; + var terms = std.mem.tokenizeScalar(u8, query, ' '); + while (terms.next()) |term_in| { + const term = term_in[0..@min(term_in.len, max_query)]; + const m = term.len; + const sensitive = for (term) |c| { + if (std.ascii.isUpper(c)) break true; + } else false; + // A lowercase term is matched against the lowercase copy. + var low_buf: [max_query]u8 = undefined; + const want = if (sensitive) term else std.ascii.lowerString(&low_buf, term); + const hay = if (sensitive) text else lower; + // The window a match can be in: from the first character's first + // place to the last one's last place, else no match at all. + const lo = std.mem.indexOfScalar(u8, hay, want[0]) orelse return null; + var pos = lo + 1; + for (want[1..]) |c| pos = (std.mem.indexOfScalarPos(u8, hay, pos, c) orelse return null) + 1; + const end = std.mem.lastIndexOfScalar(u8, hay, want[m - 1]).? + 1; + // D[i][j]: the best score with term[i] matched at text[j]. + var prev = &dp_rows[0]; + var cur = &dp_rows[1]; + const width = text.len; + const keep = if (trace) |t| t.len >= m * width else false; + for (0..m) |i| { + var gapped: i32 = neg; // max over k <= j-2 of D[i-1][k], less the gap to j + for (lo..end) |col| { + var best: i32 = neg; + if (i > 0 and col >= lo + 2) gapped = @max(gapped - gap_ext, prev[col - 2] - gap_start); + if (hay[col] == want[i]) { + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (i == 0) { + best = own; + } else if (col > lo) { + const from = @max(if (prev[col - 1] > neg) prev[col - 1] + bonus_consecutive else neg, gapped); + if (from > neg) best = from + own; + } + } + cur[col] = best; + if (keep) trace.?[i * width + col] = best; + } + const t = prev; + prev = cur; + cur = t; + } + var best: i32 = neg; + var at: usize = lo; + for (lo..end) |col| if (prev[col] > best) { + best = prev[col]; + at = col; + }; + if (best <= neg) return null; + total += best; + // Back from the best end, the place each character was matched at. + if (keep and marks != null) { + const out = marks.?; + const t = trace.?; + var i = m; + var col = at; + while (i > 0) { + i -= 1; + if (nmarks < out.len) { + out[nmarks] = @intCast(col); + nmarks += 1; + } + if (i == 0) break; + const here = t[i * width + col]; + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (col > lo and t[(i - 1) * width + col - 1] > neg and t[(i - 1) * width + col - 1] + bonus_consecutive + own == here) { + col -= 1; + continue; + } + var found = col - 1; + if (col >= lo + 2) { + var k = col - 2; + while (true) { + const d = t[(i - 1) * width + k]; + if (d > neg and d - gap_start - @as(i32, @intCast(col - 2 - k)) * gap_ext + own == here) { + found = k; + break; + } + if (k == lo) break; + k -= 1; + } + } + col = found; + } + } + } + if (marks_len) |count| { + if (marks) |out| std.mem.sort(u16, out[0..nmarks], {}, std.sort.asc(u16)); + count.* = nmarks; + } + return total; +} + +const test_paths = [_][]const u8{ + "src/layout.zig", "src/locations.zig", "src/Output.zig", "src/hunks.zig", + "src/pardes.zig", "src/pdf.zig", "src/look.zig", "src/syntax.zig", + "src/body_layer.zig", "build.zig", "src/ninep/ctl.zig", "docs/helix-keys.md", + "notes/helix-keys.md", "src/gui/Post.zig", "cmd/tool/ui_review.py", +}; + +fn topFor(q: []const u8) []const u8 { + var best: ?[]const u8 = null; + var best_score: i32 = std.math.minInt(i32); + for (test_paths) |path| { + var low: [256]u8 = undefined; + const s = match(q, path, std.ascii.lowerString(&low, path), baseOf(path), null, null, null) orelse continue; + if (s > best_score or (s == best_score and path.len < best.?.len)) { + best = path; + best_score = s; + } + } + return best orelse ""; +} + +test "Names ranks real paths as the pick prototype did" { + try std.testing.expectEqualStrings("src/layout.zig", topFor("layout")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("out")); + try std.testing.expectEqualStrings("src/pardes.zig", topFor("prz")); + try std.testing.expectEqualStrings("src/body_layer.zig", topFor("bl")); + try std.testing.expectEqualStrings("src/ninep/ctl.zig", topFor("ctl ninep")); + try std.testing.expectEqualStrings("docs/helix-keys.md", topFor("helkey")); + try std.testing.expectEqualStrings("src/gui/Post.zig", topFor("gui/po")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("Out")); +} diff --git a/src/Output.zig b/src/Output.zig index 9a11b2fc..1e62b04a 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -35,6 +35,9 @@ pub const Origin = union(enum) { unsaved, /// A directory's entries (Dir.zig), the pane named for it. dir, + /// A query pane's +Preview (Query.zig): a file's text shown, not yet + /// its pane; Enter promotes it to one where it stands. + preview, }; pub const max_arg = dump.max_origin_arg; @@ -259,6 +262,7 @@ pub fn traits(o: Origin) Traits { .errors => .{ .name = config.errors_buffer, .doc = true }, .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, + .preview => .{ .name = config.preview_buffer, .doc = true }, // Named for its directory, not a `+` name in it. .dir => .{ .name = "", .doc = true }, .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, @@ -324,6 +328,7 @@ pub fn word(o: Origin) []const u8 { .pdf_links => config.pdf_links_buffer, .unsaved => config.unsaved_buffer, .dir => dir_word, + .preview => config.preview_buffer, }; } @@ -337,6 +342,7 @@ pub fn fromWord(w: []const u8) ?Origin { if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; if (std.mem.eql(u8, w, config.unsaved_buffer)) return .unsaved; if (std.mem.eql(u8, w, dir_word)) return .dir; + if (std.mem.eql(u8, w, config.preview_buffer)) return .preview; if (std.meta.stringToEnum(Builtin, w)) |b| if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; @@ -399,7 +405,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u => {}, else => return anchor, }, - .errors, .pdf_links, .unsaved, .dir => return anchor, + .errors, .pdf_links, .unsaved, .dir, .preview => return anchor, } if (content.len == 0) return anchor; const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); diff --git a/src/Places.zig b/src/Places.zig index 435a138a..cff7c22e 100644 --- a/src/Places.zig +++ b/src/Places.zig @@ -207,7 +207,8 @@ pub fn search(set: *Places, p: *Pardes, pane: *Pane, provenance: Provenance, fro set.revision = f.revision +% 1; // `fill` starts it over for the text as it is set.seek = seek; set.seek_moves = moves; - set.fill(p, pane, frame_bytes, frame_steps); + // The keystroke's share: the view; the rest a frame's slice a tick. + set.fill(p, pane, 0, frame_steps); } /// A list's places in this text, as it gives them (sorted here), in place @@ -589,7 +590,7 @@ pub fn step(set: *Places, p: *Pardes, pane: *Pane, forward: bool, count: u32, ad /// Whether n and N in this pane are these places' to step: a list's or a /// query's always; a search's while it is what the register says (an `s`, /// a `/` elsewhere or `"a` since makes them helix's register search again). -pub fn answersN(set: *const Places, p: *Pardes, pane: *const Pane) bool { +pub fn answersN(set: *const Places, p: *Pardes, pane: *Pane) bool { if (!set.shows(pane) and !set.started) return false; if (set.provenance != .search) return p.register == 0; const name = if (p.register != 0) p.register else p.registers.last_search; @@ -634,10 +635,11 @@ pub fn forget(set: *Places, gpa: std.mem.Allocator) void { set.snap = &.{}; } -/// Where the query began: the primary selection's end when it was -/// remembered, else now. -pub fn origin(set: *const Places, pane: *const Pane) usize { - if (set.snap.len > 0) return @max(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); +/// Where the query began: the primary selection's start when it was +/// remembered, else now; a place there counts (helix's `/` from the +/// cursor). +pub fn origin(set: *const Places, pane: *Pane) usize { + if (set.snap.len > 0) return @min(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); const f = pane.file orelse return 0; const r = pane.body.primaryRange(f.content, 0); return @min(r.anchor, r.head); @@ -847,3 +849,28 @@ test "places: a big file costs a keystroke its view, the ticks find the rest, an if (std.c.getenv("PLACES_TIMES") != null) std.debug.print("places: first key {d} us, {d} ticks, an edit {d} us (the text's own splice {d} us)\n", .{ first_ns / 1000, ticks, edit_ns / 1000, text_ns / 1000 }); } + +test "zz stress analysis cost" { + const path = "/home/goblin/00-projects/0x4200.cafe/pardes-s-converge/.scratch/stress/src/layout.zig"; + if (std.c.getenv("PLACES_TIMES") == null) return error.SkipZigTest; + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(4 << 20)); + defer std.testing.allocator.free(bytes); + const syntax = @import("syntax.zig"); + syntax.start(std.testing.allocator); + defer syntax.stop(); + const tp = nowNs(); + const tree = syntax.parseTree(path, bytes); + const tq = nowNs(); + if (tree) |t| syntax.freeTree(t); + std.debug.print("parse alone {d} us\n", .{(tq - tp) / 1000}); + const t0 = nowNs(); + const d = try syntax.contextDeclarations(std.testing.allocator, path, bytes); + const t1 = nowNs(); + std.testing.allocator.free(d); + const a = try syntax.analyzeSource(std.testing.allocator, path, bytes, true, true); + const t2 = nowNs(); + std.testing.allocator.free(a.declarations); + std.testing.allocator.free(a.colors); + std.debug.print("decls {d} us ({d}), analysis with colours {d} us\n", .{ (t1 - t0) / 1000, d.len, (t2 - t1) / 1000 }); +} diff --git a/src/Query.zig b/src/Query.zig new file mode 100644 index 00000000..fbce95b2 --- /dev/null +++ b/src/Query.zig @@ -0,0 +1,2155 @@ +//! The query pane: the one pane search is. A +Search attached under the +//! pane that asked (its owner, layout.zig "Attached panes"), born at a +//! fixed height, whose body's line 1 is the query, editable text, and +//! whose rows below are made live from a source, read-only while live. +//! Line 1's first word names the source: `/pat` the owner's text (smart- +//! case regex), `Find pat` the files under its directory, `Grep pat` the +//! lines of those files, `Recent pat`, `Panes pat`, `Symbols pat` (the +//! owner's declarations), `All pat` (every open pane's text), and the +//! language server's `Refs`, `Def`, `Impl`, `Diagnostics`. Names are +//! matched fuzzy (Names.zig), text by regex. Editing the word changes +//! the source. +//! +//! The rows look like a Callstack's: the hit line with the match tinted +//! under a gutter line number, under the declaration it is in (when the +//! owner's parse exists: never made here on the loop), under its file +//! (Grep) or under `@pN name (count)` (All). They are addresses, all text: +//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into +//! an open pane's text, that pane's places (Places.zig) show the set: +//! tints, rail ticks, the current one selected. A row pointing at a file +//! no pane shows is shown in the +Preview attached under this pane; Enter +//! promotes the preview to the file's pane where it stands. +//! +//! Nothing moves while you type: the pane never closes, resizes or +//! rewrites line 1 on its own; zero hits is a state (`0` in the tag). +//! Enter lands on the current hit and freezes the rows into ordinary text; +//! Esc while typing puts every view back and closes the pane (or brings a +//! reused pane's frozen rows back); Del closes it. One per owner, reused +//! (SearchPane reuse|new). +const Query = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const edit = @import("edit.zig"); +const exec = @import("exec.zig"); +const layout = @import("layout.zig"); +const locations = @import("locations.zig"); +const look = @import("look.zig"); +const modal = @import("modal.zig"); +const normal = @import("normal.zig"); +const syntax = @import("syntax.zig"); +const tagline = @import("tagline.zig"); +const filesystem = @import("fs.zig"); +const colors = @import("colors.zig"); +const memory = @import("memory.zig"); +const Names = @import("Names.zig"); +const Places = @import("Places.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; +const Output = panes.Output; +const Key = pardes.Key; +const hit = pardes.hit; + +pub const Source = enum { text, find, grep, recent, panes, symbols, all, refs, defs, impls, diagnostics }; + +/// Line 1's words, each the source it names. `/` is vim's spelling, no +/// space after it; the others take one. +pub const words = [_]struct { word: []const u8, source: Source }{ + .{ .word = "Find", .source = .find }, + .{ .word = "Grep", .source = .grep }, + .{ .word = "Recent", .source = .recent }, + .{ .word = "Panes", .source = .panes }, + .{ .word = "Symbols", .source = .symbols }, + .{ .word = "All", .source = .all }, + .{ .word = "Refs", .source = .refs }, + .{ .word = "Def", .source = .defs }, + .{ .word = "Impl", .source = .impls }, + .{ .word = "Diagnostics", .source = .diagnostics }, +}; + +/// What a line 1 asks: its source and what follows its word. Null when it +/// starts with no word this knows (the user rewrote it): the rows say so. +pub fn parse(line: []const u8) ?struct { source: Source, pat: []const u8 } { + if (line.len > 0 and line[0] == '/') return .{ .source = .text, .pat = line[1..] }; + for (words) |w| { + if (std.mem.startsWith(u8, line, w.word) and (line.len == w.word.len or line[w.word.len] == ' ')) + return .{ .source = w.source, .pat = std.mem.trim(u8, line[w.word.len..], " \t") }; + } + return null; +} + +/// The word line 1 starts with for `source`, as typed after it. +pub fn wordOf(source: Source) []const u8 { + if (source == .text) return "/"; + for (words) |w| if (w.source == source) return w.word; + unreachable; +} + +/// A source whose rows can point at files no pane shows: its group is +/// made with a +Preview from the start, so nothing moves later. +fn previews(source: Source) bool { + return switch (source) { + .find, .grep, .recent, .refs, .defs, .impls, .diagnostics => true, + .text, .panes, .symbols, .all => false, + }; +} + +/// The most rows of hits a frozen list keeps: the rest are counted, and +/// said in a row. +pub const max_rows = 2000; +/// While typed, the rows are a window of this many around the current +/// place: the pane shows a few, and a row is two allocations a refill. +pub const live_rows = 100; + +/// One row's model, row `i + 1` of the pane (line 1 is the query): a hit, +/// a header (a declaration, a file, a pane) or a note. Where a row points +/// is in its locations.Row (path, at); a hit in an open pane's text also +/// knows its places there, `hit` and the `n` of them on its line. +pub const Item = struct { + kind: enum { hit, header, note }, + /// The pane whose text it is in (by serial), 0 when it is a file's. + serial: u32 = 0, + hit: usize = 0, + n: usize = 0, + /// A Panes row's pane, a Symbols row's line: Names.Cand.ref. + ref: u32 = 0, +}; + +/// A line a Grep found: its path and code in `found_bytes`. +pub const Found = struct { path: u32, path_len: u16, line: u32, col: u32, end: u32, code: u32, code_len: u32 }; + +/// The pane it answers for, by serial. +owner: u32, +/// Line 1 as the rows were last made for (gpa). +asked: []u8 = &.{}, +source: Source = .text, +/// Enter answered it: its rows are ordinary text from here, nothing remade. +frozen: bool = false, +items: std.ArrayList(Item) = .empty, +/// The current item, which Enter lands on and the places show. +current: ?usize = null, +/// The tag's `k/N`: how many places or names the rows are of, and where +/// the current one is among them (1-based; 0, none); `more` while counting. +total: usize = 0, +k: usize = 0, +more: bool = false, +/// What the rows were made of: the places' or names' generation and the +/// owner's text, so that a frame with nothing new makes nothing. +made_gen: u64 = std.math.maxInt(u64), +made_rev: u32 = 0, +/// The owner's revision seen last tick: rows follow an edit of the owner +/// once it has stood a frame (the rows refresh on idle frames). +seen_rev: u32 = 0, +/// The body cursor's row as last seen: B1, j or k on a row makes it current. +seen_row: i32 = 0, +/// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits. +window: struct { lo: usize = 0, hi: usize = 0 } = .{}, +/// Ticks the rows waited while the places are still being found: they are +/// made every third, the frame's time going to the finding. +waited: u8 = 0, +names: Names = .{}, +/// A Grep's lines, found a slice a frame (Query.grepSlice). +found: std.ArrayList(Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +grep_next: usize = 0, +grep_gen: u32 = 0, +/// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave +/// them (`path:line:col text`, gpa), filtered by what follows the word. +lsp_rows: []u8 = &.{}, +/// The +Preview under this pane, by serial; 0, none. +preview: u32 = 0, +/// A reused pane's frozen rows when a new query began in it: Esc brings +/// them back. +saved: ?Saved = null, + +pub const Saved = struct { + content: []u8, + rows: []locations.Row, + asked: []u8, + source: Source, + items: []Item, + current: ?usize, + total: usize, + k: usize, +}; + +pub fn deinit(q: *Query, gpa: std.mem.Allocator) void { + gpa.free(q.asked); + q.items.deinit(gpa); + q.names.deinit(gpa); + q.found.deinit(gpa); + q.found_bytes.deinit(gpa); + gpa.free(q.lsp_rows); + if (q.saved) |s| freeSaved(gpa, s); + q.* = undefined; +} + +fn freeSaved(gpa: std.mem.Allocator, s: Saved) void { + gpa.free(s.content); + locations.freeRows(gpa, s.rows); + gpa.free(s.asked); + gpa.free(s.items); +} + +/// The query pane `pane` is, if it is one. +pub fn of(pane: *Pane) ?*Query { + return pane.query; +} + +/// The owner's query pane (attached to it, or left where it was by +/// SearchPane new): the one a later search from it reuses. +pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize { + var found: ?usize = null; + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.owner != owner_serial) continue; + // the attached one first: an unattached one is a kept result + if (pane.attached_to == owner_serial) return i; + found = found orelse i; + } + return found; +} + +fn lineOne(content: []const u8) []const u8 { + return content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; +} + +// ---- opening ---- + +/// A search from pane `from`: its owner's query pane, made under the owner +/// (with a +Preview when `source` can need one) or reused, line 1 the +/// source's word and `arg`. With `focus` the keyboard goes to line 1's end +/// in insert mode, as to a prompt; without (`*`), it stays where it is. +pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: bool) void { + const asker = p.panes[from] orelse return; + // Asked from a query pane (`/` in it, its own SPC f g): its own line 1; + // from a +Preview, its query pane's. + var owner_id = from; + if (asker.query) |q| owner_id = p.paneBySerial(q.owner) orelse from else if (isPreview(p, asker)) |qid| { + owner_id = p.paneBySerial(p.panes[qid].?.query.?.owner) orelse from; + } + const owner = p.panes[owner_id] orelse return; + if (asker.query != null and arg.len == 0 and asker.query.?.source == source and !asker.query.?.frozen) { + // Back to typing the query it has. + if (focus) toLineOne(p, from); + return; + } + const line = std.mem.concat(p.scratch.allocator(), u8, &.{ wordOf(source), if (source == .text) "" else " ", arg }) catch return; + var id: usize = undefined; + const existing = ofOwner(p, owner.serial); + if (existing != null and (p.settings.search_pane == .reuse or existing.? == from)) { + id = existing.?; + const rp = p.panes[id].?; + const q = rp.query.?; + // Its frozen rows, kept for an Esc to bring back. + if (q.frozen and q.saved == null) q.saved = save(p, rp, q) catch null; + q.frozen = false; + const f = &rp.file.?; + const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return; + File.setContent(p, f, new); + q.reset(p); + if (rp.collapsed) layout.toggleCollapse(p, id); + } else { + if (existing) |old| { + // SearchPane new: the last one stays where it is, a result of + // its own; its places are the new one's to feed. + p.panes[old].?.attached_to = null; + } + id = create(p, owner_id, line, source) orelse return; + } + // Every view as the search found it, for Esc to put back. + owner.places.remember(p, owner); + // Before the first key: a names source lists every candidate at once. + produce(p, id, false); + // What a 9P exec reads back: the pane it filled (ninep/ctl.zig). + p.fs.refilled = p.panes[id].?.serial; + if (focus) toLineOne(p, id) else p.active = from; +} + +/// A new query pane under pane `owner_id`, `rows` of the owner's rows (the +/// SearchRows setting), its +Preview under it when `source` can need one. +fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize { + const owner = p.panes[owner_id] orelse return null; + const free = p.freeSlot() orelse { + p.reportError(owner_id, "search", error.NoPaneSlots); + return null; + }; + const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(owner); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return null; + const np = Output.open(p, free, dir, .search, "", content) catch |err| { + p.gpa.free(content); + p.reportError(owner_id, "search", err); + return null; + }; + const q = p.gpa.create(Query) catch { + p.reportError(owner_id, "search", error.OutOfMemory); + return null; + }; + q.* = .{ .owner = owner.serial }; + np.query = q; + const body: u16 = 1 + p.settings.search_rows; + const tag = @max(pardes.BOX_H, np.tag_rows); + const with_preview = previews(source); + // The preview, made right after, takes its own rows from the owner. + const want = tag + body; + if (p.settings.search_place == .column) { + // The finder column (phase 6): until it exists, under the owner. + if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + } else if (!layout.attach(p, owner_id, free, want)) { + // An owner too short to give a query pane its rows: placed as any + // new pane is, the one place a search moves another pane. + exec.placeNew(p, owner_id, owner_id, free, .doc); + } + if (with_preview) _ = makePreview(p, free); + return free; +} + +/// The keyboard to the end of line 1 of query pane `id`, in insert mode. +pub fn toLineOne(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + tagline.exitHeader(p); + p.active = id; + if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col); + rp.focus = .body; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + t.cur_row = 0; + t.cur_col = @intCast(lineOne(rp.file.?.content).len); + t.vsel.active = false; + t.nsel = 0; + t.cur_pinned = true; + rp.query.?.seen_row = 0; + edit.enterInsert(p, t, .line_end, 1); + showCurrent(rp); +} + +/// The rows' state for a new question: nothing found yet. +fn reset(q: *Query, p: *Pardes) void { + q.items.clearRetainingCapacity(); + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + q.made_gen = std.math.maxInt(u64); + p.gpa.free(q.asked); + q.asked = &.{}; +} + +fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { + const f = &rp.file.?; + const content = try p.gpa.dupe(u8, f.content); + errdefer p.gpa.free(content); + const rows = try p.gpa.alloc(locations.Row, f.location_rows.len); + var made: usize = 0; + errdefer { + for (rows[0..made]) |r| { + p.gpa.free(r.path); + p.gpa.free(r.colors); + } + p.gpa.free(rows); + } + for (f.location_rows, 0..) |r, i| { + rows[i] = r; + rows[i].path = try p.gpa.dupe(u8, r.path); + rows[i].colors = p.gpa.dupe(u8, r.colors) catch |err| { + p.gpa.free(rows[i].path); + return err; + }; + made += 1; + } + const asked = try p.gpa.dupe(u8, q.asked); + errdefer p.gpa.free(asked); + return .{ .content = content, .rows = rows, .asked = asked, .source = q.source, .items = try p.gpa.dupe(Item, q.items.items), .current = q.current, .total = q.total, .k = q.k }; +} + +// ---- making the rows ---- + +/// After every step: each live query pane whose line 1 changed, or whose +/// source has something new, has its rows made again. A walk takes a slice +/// on a tick. Nothing here is synchronous with an edit of the owner: its +/// places shift (Places.shift) and the rows follow once it stands a frame. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + if (pane.query == null) continue; + produce(p, id, tick); + } +} + +/// The frames a query pane still owes (a walk, scoring): nextWake's. +pub fn busy(p: *const Pardes) bool { + for (p.panes) |slot| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.frozen) continue; + if (q.names.busy() or (q.source == .grep and q.grep_next < q.names.cands.items.len) or q.made_rev != q.seen_rev) return true; + } + return false; +} + +fn produce(p: *Pardes, id: usize, tick: bool) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const f = if (rp.file) |*file| file else return; + const line = lineOne(f.content); + const changed = !std.mem.eql(u8, line, q.asked); + if (q.frozen and !changed) return; + if (q.frozen) { + // Line 1 of a frozen pane edited: it is a live query again. + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + q.frozen = false; + } + const owner_id = p.paneBySerial(q.owner); + const asked = parse(line); + if (changed) { + const was = q.source; + const new_asked = p.gpa.dupe(u8, line) catch return; + p.gpa.free(q.asked); + q.asked = new_asked; + q.made_gen = std.math.maxInt(u64); + if (asked) |a| { + if (a.source != was or q.names.cands.items.len == 0) startSource(p, id, q, a.source, owner_id); + q.source = a.source; + } + // The places this fed are another question's now. + if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked); + } + const a = asked orelse return noteRows(p, id, " line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n"); + // A row clicked or stepped onto (B1, j, k): current, and shown. + if (rp.body.cur_row != q.seen_row) { + q.seen_row = rp.body.cur_row; + if (rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { + const i: usize = @intCast(rp.body.cur_row - 1); + if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true); + } + } + switch (a.source) { + .text => { + const oid = owner_id orelse return noteRows(p, id, " the pane this searched is gone: Del, or / in another\n"); + const owner = p.panes[oid].?; + const of_ = owner.file orelse return noteRows(p, id, " a terminal's text is not searched here yet: / in a file\n"); + const set = &owner.places; + if (changed) { + if (a.pat.len == 0) { + if (set.from == rp.serial) set.clear(p.gpa); + set.restore(p, owner); + } else set.search(p, owner, .typed, rp.serial, a.pat, false, set.origin(owner), p.active == id); + } + // The owner edited: its places shifted at once; the rows follow + // once its text has stood a frame. + if (!changed and of_.revision != q.made_rev) { + if (!tick or of_.revision != q.seen_rev) { + q.seen_rev = of_.revision; + return; + } + } + q.seen_rev = of_.revision; + const gen: u64 = (@as(u64, set.hits_gen) << 32) | of_.revision; + if (gen == q.made_gen and !changed) return showPlacesCurrent(p, id); + if (a.pat.len > 0 and set.from != rp.serial) return; + if (!changed and !set.complete() and q.made_gen != std.math.maxInt(u64) and q.waited < 2) { + q.waited += 1; + return showPlacesCurrent(p, id); + } + q.waited = 0; + q.made_gen = gen; + q.made_rev = of_.revision; + makeTextRows(p, id, oid, false) catch |err| p.reportError(id, "search", err); + }, + .all => { + if (changed) for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (a.pat.len == 0) { + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + continue; + } + tp.places.search(p, tp, .list, rp.serial, a.pat, false, null, false); + }; + var gen: u64 = 0; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial) { + gen +%= tp.places.hits_gen +% (@as(u64, tp.serial) << 20); + }; + if (gen == q.made_gen and !changed) return; + if (!changed and !tick) return; + q.made_gen = gen; + makeAllRows(p, id) catch |err| p.reportError(id, "search", err); + }, + .find, .recent, .panes, .symbols => { + if (tick) q.names.walkSlice(p.gpa); + if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa); + if (q.names.gen == q.made_gen and !changed) return; + q.made_gen = q.names.gen; + makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + .grep => { + if (changed) { + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + q.grep_gen +%= 1; + } + if (a.pat.len == 0) { + if (changed) makeGrepRows(p, id) catch {}; + return; + } + if (tick or changed) { + q.names.walkSlice(p.gpa); + grepSlice(p, q, rp, a.pat); + } + const gen: u64 = (@as(u64, q.grep_gen) << 32) | q.found.items.len; + if (gen == q.made_gen and !changed and !(q.grep_next >= q.names.cands.items.len and q.more)) return; + q.made_gen = gen; + makeGrepRows(p, id) catch |err| p.reportError(id, "search", err); + if (changed or q.current == null) feedGrepPlaces(p, q, rp.serial, a.pat); + }, + .refs, .defs, .impls, .diagnostics => { + if (changed and q.lsp_rows.len == 0) { + // Typed, not answered: asked of the language server at the + // owner's cursor; its answer fills these rows (fillList). + // An answer opening the pane is no typing. + if (p.active != id) return; + if (owner_id) |oid| p.lspRequest(oid, switch (a.source) { + .refs => .references, + .defs => .definition, + .impls => .implementation, + else => .diagnostics, + }, ""); + return noteRows(p, id, " asked of the language server...\n"); + } + if (!changed) return; + makeListRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + } +} + +/// Whether pane `tp`'s text is one All searches: a file's or a list's, +/// not a query pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// A source begun: its candidates gathered (names), its walk started. +fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usize) void { + const rp = p.panes[id].?; + q.names.reset(); + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const gpa = p.gpa; + switch (source) { + .find, .grep => q.names.startWalk(gpa, dir) catch |err| p.reportError(id, "search", err), + .recent => { + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + Output.recentText(p, &out.writer, true) catch {}; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |ln| { + if (ln.len == 0) continue; + const rel = Names.relative(ln, dir); + const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len; + q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; + } + }, + .panes => for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + }, + .symbols => { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const f = if (owner.file) |*file| file else return; + const decls = ownerDecls(p, f, true) orelse return; + for (decls) |d| { + const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)]; + const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); + var buf: [256 + 16]u8 = undefined; + const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue; + q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; + } + }, + else => {}, + } +} + +/// The owner's declarations, from a parse that already exists: its sticky +/// headers' (TreeContext) at this revision, or the locations cache's. None +/// is made here, on the loop, unless `small` and the text is small: a +/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build. +/// ponytail: no grouping for a big file until the disk engine's worker +/// parses it (phase 4). +fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { + if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations; + const cache = &p.locations_cache; + for (cache.entries[0..cache.len]) |entry| { + if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; + } + if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null; + var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null; + if (got.owned) { + got.deinit(p.tree_sitter_gpa); + return null; + } + return got.analysis.declarations; +} + +/// A text this small is parsed on the loop for its declarations when a +/// Symbols query asks (about 40 ms in a Debug build). +const small_parse_bytes = 64 << 10; + +/// The rows as `note` says, and nothing else: no hits. +fn noteRows(p: *Pardes, id: usize, note: []const u8) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.items.append(p.gpa, .{ .kind = .note }) catch return; + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + writeRow(p, &out, &rows, note[0 .. note.len - 1], .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }) catch return; + setRows(p, rp, &out, &rows); +} + +/// One row: its text and its metadata, the path copied. +fn writeRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8, meta: locations.Row) !void { + try out.appendSlice(p.gpa, text); + try out.append(p.gpa, '\n'); + var m = meta; + m.path = try p.gpa.dupe(u8, meta.path); + errdefer p.gpa.free(m.path); + // Coloured whole (zeros where nothing coloured it): the pane's syntax + // pass then parses no fragment of it, per refill. + const code = text[@min(meta.code_start, text.len)..]; + m.colors = if (meta.colors.len >= code.len) try p.gpa.dupe(u8, meta.colors[0..code.len]) else blk: { + const c = try p.gpa.alloc(u8, code.len); + @memset(c, 0); + @memcpy(c[0..meta.colors.len], meta.colors); + break :blk c; + }; + rows.append(p.gpa, m) catch |err| { + p.gpa.free(m.path); + p.gpa.free(m.colors); + return err; + }; +} + +/// The rows made into the pane: line 1 as it is (the user's), then `out`, +/// with `rows` their metadata. The keyboard's place is left where it was. +fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) void { + defer locations.freeRowList(p.gpa, rows); + const f = &rp.file.?; + const line = lineOne(f.content); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n", out.items }) catch return; + const meta = p.gpa.alloc(locations.Row, rows.items.len + 1) catch { + p.gpa.free(content); + return; + }; + meta[0] = .{ .kind = .context, .path = p.gpa.dupe(u8, "") catch &.{}, .at = .{}, .location_end = 0, .code_start = 0 }; + @memcpy(meta[1..], rows.items); + rows.clearRetainingCapacity(); + const kept_row = rp.body.cur_row; + const kept_col = rp.body.cur_col; + if (std.mem.eql(u8, content, f.content)) { + // Same text: the metadata alone, no undo step, no syntax pass. + p.gpa.free(content); + if (locations.equalRows(f.location_rows, meta)) { + locations.freeRows(p.gpa, meta); + } else { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.syntax_dirty = true; + } + } else { + File.setContent(p, f, content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.saved_revision = f.revision; + } + gpa_free_pager(p, f); + // The cursor stays where it was typing; on a row that went, the last. + const last: i32 = @intCast(File.nlines(p.gpa, f) -| 1); + rp.body.cur_row = @min(kept_row, last); + rp.body.cur_col = if (rp.body.cur_row == kept_row) kept_col else 0; + if (rp.body.cur_row == 0 and rp.body.cur_col > line.len) rp.body.cur_col = @intCast(line.len); + rp.query.?.seen_row = rp.body.cur_row; +} + +fn gpa_free_pager(p: *Pardes, f: *File.State) void { + if (f.pager_spans.len == 0) return; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; +} + +/// The gutter a file of `nlines` lines numbers its rows in: two spaces, +/// the number right-aligned, two spaces. +fn gutterWidth(nlines: usize) usize { + var digits: usize = 1; + var n = nlines; + while (n >= 10) : (n /= 10) digits += 1; + return 2 + @max(3, digits) + 2; +} + +fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { + var lead: usize = 0; + while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1; + const code = std.mem.trimEnd(u8, whole[lead..], "\r"); + var buf: [4096 + 32]u8 = undefined; + var num: [24]u8 = undefined; + const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch ""; + const pad = width -| 2 -| number.len; + if (pad + number.len + 2 + code.len > buf.len) return; + @memset(buf[0..pad], ' '); + @memcpy(buf[pad..][0..number.len], number); + @memcpy(buf[pad + number.len ..][0..2], " "); + @memcpy(buf[pad + number.len + 2 ..][0..code.len], code); + const text = buf[0 .. pad + number.len + 2 + code.len]; + const gutter = pad + number.len + 2; + try writeRow(p, out, rows, text, .{ + .kind = .match, + .source_column = lead, + .path = @constCast(path), + .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, + .location_end = gutter, + .code_start = gutter, + .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}), + }); +} + +/// The path a row of pane `tp`'s text says: its file's, or `@pN` for a +/// text that is no file (a list, a scratch). +fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { + const f = tp.file orelse return ""; + if (f.output == null and !std.mem.startsWith(u8, std.fs.path.basename(f.path), "+")) return f.path; + return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch ""; +} + +/// Rows from pane `tp`'s places: one a line with any (two on a line are +/// one row: everywhere's bug), the declaration they are in over them when +/// its parse exists, from place `from` on, `budget` rows at most. The +/// place it stopped before. +fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize { + const f = &tp.file.?; + const set = &tp.places; + const hits = set.hits.items; + const index = try File.lineIndex(p.gpa, f); + const width = gutterWidth(index.len); + const path = addressOf(p.scratch.allocator(), tp); + const decls = ownerDecls(p, f, false) orelse &.{}; + var decl_now: ?usize = null; + var i: usize = @min(from, hits.len); + // the line of the first, found in the index + var line: usize = if (i < hits.len) blk: { + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= hits[i].start) lo = mid + 1 else hi = mid; + } + break :blk lo -| 1; + } else 0; + // a window begins at a line's first place + while (i > 0 and hits[i - 1].start >= index[line]) i -= 1; + while (i < hits.len) { + while (line + 1 < index.len and index[line + 1] <= hits[i].start) line += 1; + // the places on this line + var n: usize = 1; + const ls = index[line]; + const le = if (line + 1 < index.len) index[line + 1] - 1 else f.content.len; + while (i + n < hits.len and hits[i + n].start <= le) n += 1; + if (budget.* == 0) { + q.more = true; + break; + } + budget.* -= 1; + // the innermost declaration around it, its first line once + var inner: ?usize = null; + for (decls, 0..) |d, di| { + if (d.start_line > line) break; + if (d.end_line < line) continue; + inner = di; + } + if (inner != decl_now) { + decl_now = inner; + if (inner) |di| if (decls[di].start_line != line) { + const head_ls = index[decls[di].start_line]; + const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len; + const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r"); + var hb: [600]u8 = undefined; + const text = std.fmt.bufPrint(&hb, " {s}", .{head[0..@min(head.len, 560)]}) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 }); + }; + } + const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; + try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); + try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + i += n; + } + return i; +} + +/// The rows of a `/`: while typed, a window of `live_rows` around the +/// current place; `full` (frozen), the whole list up to `max_rows`. +fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[oid].?; + const set = &owner.places; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var budget: usize = if (full) max_rows else live_rows; + const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); + const from = if (full) 0 else at -| live_rows / 2; + q.window = .{ .lo = from, .hi = from }; + if (set.started and set.from == rp.serial) { + if (from > 0) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} places before these", .{from}) catch " ..."); + } + q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget); + q.window.lo = @min(from, q.window.hi); + } + if (q.more) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + showPlacesCurrent(p, id); +} + +fn noteRow(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8) !void { + try q.items.append(p.gpa, .{ .kind = .note }); + try writeRow(p, out, rows, text, .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }); +} + +/// The current row from the places of the pane its rows are in, the count +/// with them: for `/`, the owner's. +fn showPlacesCurrent(p: *Pardes, id: usize) void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; + const set = &owner.places; + q.total = if (set.from == rp.serial) set.hits.items.len else 0; + q.more = q.more or (set.from == rp.serial and !set.complete()); + q.k = if (set.current) |c| c + 1 else 0; + if (set.from != rp.serial) q.k = 0; + q.current = null; + // By line, not by the rows' place indices: the rows may lag the places + // a tick while they are still being found. + if (set.current) |c| if (c < set.hits.items.len) { + const at = lineOfOffset(p, &owner.file.?, set.hits.items[c].start) + 1; + const rows = rp.file.?.location_rows; + for (q.items.items, 0..) |it, i| { + if (it.kind != .hit or it.serial != owner.serial or i + 1 >= rows.len) continue; + if (rows[i + 1].at.line == at) { + q.current = i; + break; + } + } + }; + // Stepped out of the window the live rows are: made again around it. + if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); + showCurrent(rp); +} + +/// Every open pane's rows for All, grouped under `@pN name (count)` in +/// the order of the panes' serials (everywhere's other bug: it went by +/// column). +fn makeAllRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { + order[n] = i; + n += 1; + }; + std.mem.sort(usize, order[0..n], p, struct { + fn lt(pp: *Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + var budget: usize = max_rows; + q.total = 0; + for (order[0..n]) |tid| { + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp) or set.hits.items.len == 0) { + q.more = q.more or !set.complete(); + continue; + } + q.total += set.hits.items.len; + q.more = q.more or !set.complete(); + var hb: [600]u8 = undefined; + const name = if (tp.file) |f| Names.relative(f.path, std.fs.path.dirname(rp.file.?.path) orelse "") else ""; + const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); + _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget); + } + if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + // The current one: the first hit row, until a step moves it. + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +fn firstHit(q: *const Query) ?usize { + for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i; + return null; +} + +/// `k` from the current row: the hits on the rows before it, and its own. +fn countCurrent(q: *Query) void { + q.k = 0; + const c = q.current orelse return; + for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0; + q.k += 1; +} + +/// The names the query matches, best first, `Names.max_rows` of them: each +/// a row as its source has it, the matched bytes tinted. +fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { + _ = pat; + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const was_current: ?u32 = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].ref else null) else null; + _ = was_current; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var spans: std.ArrayList(pardes.pager.Span) = .empty; + errdefer spans.deinit(p.gpa); + const chrome = p.bodyChrome(); + const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; + const shown = @min(q.names.hits.items.len, Names.max_rows); + var marks: [Names.max_query * 4]u16 = undefined; + const base = lineOne(rp.file.?.content).len + 1; + for (0..shown) |i| { + var nmarks: usize = 0; + const row = q.names.row(i, &marks, &nmarks); + const cand = q.names.cands.items[q.names.hits.items[i].cand]; + const at = base + out.items.len; + // Where it points: a path (Find, Recent), a pane (Panes), a line + // of the owner (Symbols). + var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; + var pathbuf: [4096 + 32]u8 = undefined; + switch (q.source) { + .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .recent => { + const t = look.parsePathLine(row); + meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); + meta.at = t.at; + }, + .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch ""), + .symbols => { + const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; + meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); + meta.at = .{ .line = cand.ref }; + }, + else => {}, + } + try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); + try writeRow(p, &out, &rows, row, meta); + var k: usize = 0; + while (k < nmarks) { + var e = k + 1; + while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + k = e; + } + } + if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + setRows(p, rp, &out, &rows); + const f = &rp.file.?; + f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; + q.total = q.names.hits.items.len; + q.more = q.names.busy(); + // The best is current until a step or a click moves it. + q.current = if (shown > 0) 0 else null; + countCurrent(q); + showCurrent(rp); + showTarget(p, id); +} + +/// A slice of a Grep: the files the walk has found so far read and +/// searched, about 4 ms of them a frame, each line holding the pattern +/// (a literal, smart case: a capital makes it exact) kept. +/// ponytail: on the loop, a file a step; the disk engine's worker (phase +/// 4) takes this over. +fn grepSlice(p: *Pardes, q: *Query, rp: *Pane, pat: []const u8) void { + const started = Places.nowNs(); + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const fold = for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true; + var low_buf: [256]u8 = undefined; + const needle = if (fold) std.ascii.lowerString(low_buf[0..@min(pat.len, low_buf.len)], pat[0..@min(pat.len, low_buf.len)]) else pat; + while (q.grep_next < q.names.cands.items.len) { + if (q.found.items.len >= grep_cap) break; + const c = q.names.cands.items[q.grep_next]; + q.grep_next += 1; + const rel = q.names.bytes.items[c.start..][0..c.len]; + var pathbuf: [4096 + 8]u8 = undefined; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch continue; + }; + defer p.gpa.free(bytes); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) continue; + var line_no: u32 = 1; + var ls: usize = 0; + while (ls <= bytes.len) { + const le = std.mem.indexOfScalarPos(u8, bytes, ls, '\n') orelse bytes.len; + const ln = bytes[ls..le]; + const at = if (fold) std.ascii.findIgnoreCase(ln, needle) else std.mem.indexOf(u8, ln, needle); + if (at) |col| { + const path_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, rel) catch return; + const code_at: u32 = @intCast(q.found_bytes.items.len); + const code = ln[0..@min(ln.len, 400)]; + q.found_bytes.appendSlice(p.gpa, code) catch return; + q.found.append(p.gpa, .{ .path = path_at, .path_len = @intCast(rel.len), .line = line_no, .col = @intCast(col), .end = @intCast(col + needle.len), .code = code_at, .code_len = @intCast(code.len) }) catch return; + if (q.found.items.len >= grep_cap) break; + } + if (le == bytes.len) break; + ls = le + 1; + line_no += 1; + } + if (started != 0 and Places.nowNs() - started > Places.frame_ns) break; + } +} + +/// A Grep keeps this many lines: the rest wait (the disk engine's `More`). +pub const grep_cap = 2000; + +fn makeGrepRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + for (q.found.items, 0..) |fd, i| { + const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + if (!std.mem.eql(u8, rel, last_path)) { + last_path = rel; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); + try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); + } + const walking = q.names.walking() or q.grep_next < q.names.cands.items.len; + if (q.found.items.len >= grep_cap) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: type more of it"); + setRows(p, rp, &out, &rows); + q.total = q.found.items.len; + q.more = walking and q.found.items.len < grep_cap; + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +/// A Grep's hits in each open file are that pane's places: its tints, +/// ticks and n/N. +fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void { + _ = q; + for (p.panes) |slot| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output != null or tp.query != null) continue; + tp.places.search(p, tp, .list, serial, pat, true, null, false); + } +} + +/// The language server's answer for an owner's Refs, Def, Impl or +/// Diagnostics, into its query pane (made or reused) with line 1 the word: +/// what follows the word filters the rows; the places in the owner's text +/// are its places. `rows` are `path:line:col text`, as the server's +/// answer is written (lsp_client). +pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) void { + const owner = p.panes[owner_id] orelse return; + var id = ofOwner(p, owner.serial); + if (id == null or p.panes[id.?].?.query.?.source != source) { + open(p, owner_id, source, "", false); + id = ofOwner(p, owner.serial); + } + const qid = id orelse return; + const rp = p.panes[qid].?; + const q = rp.query.?; + const copy = p.gpa.dupe(u8, rows) catch return; + p.gpa.free(q.lsp_rows); + q.lsp_rows = copy; + const line = lineOne(rp.file.?.content); + const a = parse(line) orelse return; + makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); + toLineOne(p, qid); +} + +fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + const owner_id = p.paneBySerial(q.owner); + const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; + var feed: std.ArrayList(Places.Hit) = .empty; + defer feed.deinit(p.gpa); + // In order: by path, then place, as a list of places reads. + var sorted: std.ArrayList([]const u8) = .empty; + defer sorted.deinit(p.gpa); + var split = std.mem.splitScalar(u8, q.lsp_rows, '\n'); + while (split.next()) |ln| if (ln.len > 0) try sorted.append(p.gpa, ln); + std.mem.sort([]const u8, sorted.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + const ta = look.parsePathLine(a); + const tb = look.parsePathLine(b); + const order = std.mem.order(u8, ta.path, tb.path); + if (order != .eq) return order == .lt; + if (ta.at.line != tb.at.line) return ta.at.line < tb.at.line; + return ta.at.col < tb.at.col; + } + }.lt); + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + var n: usize = 0; + for (sorted.items) |ln| { + if (ln.len == 0) continue; + if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; + const t = look.parsePathLine(ln); + if (t.at.line == 0) continue; + const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + if (!std.mem.eql(u8, t.path, last_path)) { + last_path = t.path; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); + const col0 = t.at.col -| 1; + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); + // The row's text: the line in the owner when it is the owner's, + // else as the server said it. + var code: []const u8 = rest; + var col = col0; + var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; + if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { + const owner_f = &p.panes[oid].?.file.?; + if (t.at.line <= File.nlines(p.gpa, owner_f)) { + const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); + const nx = File.lineStart(p.gpa, owner_f, t.at.line); + const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; + code = owner_f.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + } + } else { + col = 0; + end = 0; + }; + try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); + n += 1; + } + if (n == 0) try noteRow(p, q, &out, &rows, " nothing"); + setRows(p, rp, &out, &rows); + q.total = n; + q.more = false; + q.current = firstHit(q); + if (owner_id) |oid| { + const owner = p.panes[oid].?; + // Current: the first place after where it was asked (the answer + // may come after the cursor moved), shown in the owner. + const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); + owner.places.feed(p, owner, rp.serial, feed.items, null); + const hits = owner.places.hits.items; + var next: ?usize = null; + for (hits, 0..) |h, i| if (h.start > asked_at) { + next = i; + break; + }; + if (next == null and hits.len > 0) next = 0; + if (next) |hi| { + owner.places.goTo(owner, hi, false); + for (q.items.items, 0..) |it, i| if (it.kind == .hit and i + 1 < rp.file.?.location_rows.len) { + const meta = rp.file.?.location_rows[i + 1]; + if (!std.mem.eql(u8, meta.path, owner_path)) continue; + const ls = File.lineStart(p.gpa, &owner.file.?, meta.at.line -| 1); + if (ls + meta.at.col -| 1 == hits[hi].start) { + q.current = i; + break; + } + }; + } + } + countCurrent(q); + showCurrent(rp); +} + +/// The places query `serial` fed in panes other than the owner, cleared +/// (a new source or pattern makes its own); the owner's too when the new +/// line is no `/`. +fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anytype) void { + _ = q; + _ = asked; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (tp.places.from != serial) continue; + if (owner_id != null and owner_id.? == i) tp.places.restore(p, tp); + tp.places.clear(p.gpa); + } +} + +// ---- the current row ---- + +/// The current row drawn as the visited row is (a line selection), while +/// the keyboard is on line 1 or elsewhere; on the rows, the cursor itself +/// is current. Scrolled into view, line 1 kept when it can be. +fn showCurrent(rp: *Pane) void { + const q = rp.query orelse return; + if (rp.body.cur_row != 0 and rp.focus == .body) return; + const c = q.current orelse { + rp.body.msel.active = false; + return; + }; + const r: i32 = @intCast(c + 1); + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + const off = rp.scroll(); + const shown = off + @as(i32, rp.rows) - 1; + if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); +} + +/// The line (0-based) of byte `at` of `f`'s text. +fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize { + const index = File.lineIndex(p.gpa, f) catch return 0; + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= at) lo = mid + 1 else hi = mid; + } + return lo -| 1; +} + +/// The first of pane `tp`'s places on line `line` (1-based), if any. +fn placeOnLine(p: *Pardes, tp: *Pane, line: usize) ?usize { + const f = &tp.file.?; + if (line == 0 or line > File.nlines(p.gpa, f)) return null; + const ls = File.lineStart(p.gpa, f, line - 1); + const next = File.lineStart(p.gpa, f, line); + const hits = tp.places.hits.items; + const i = Places.firstFrom(hits, ls); + if (i < hits.len and (hits[i].start < next or (next == ls))) return i; + return null; +} + +/// Item `i` current, and shown where it points (`show`). +fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.current = i; + const it = q.items.items[i]; + const rows = rp.file.?.location_rows; + if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { + const tp = p.panes[tid].?; + if (placeOnLine(p, tp, rows[i + 1].at.line)) |hi| { + tp.places.current = hi; + tp.places.gen +%= 1; + if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); + } else countCurrent(q); + } else countCurrent(q) else countCurrent(q); + showCurrent(rp); + if (show) showTarget(p, id); +} + +/// Step the current row `delta` hits on, round the end silently: Ctrl-n, +/// Ctrl-p, Down and Up on line 1, n and N in the pane. +pub fn step(p: *Pardes, id: usize, delta: i32) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + // A `/`: the owner's places step, the rows follow them. + if (q.source == .text) if (p.paneBySerial(q.owner)) |oid| { + const owner = p.panes[oid].?; + if (owner.places.from == rp.serial) { + const keyboard = p.active; + owner.places.step(p, owner, delta > 0, 1, false); + p.active = keyboard; + showPlacesCurrent(p, id); + return; + } + }; + const items = q.items.items; + if (items.len == 0) return; + var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); + for (0..items.len) |_| { + if (delta > 0) i = if (i + 1 >= items.len) 0 else i + 1 else i = if (i == 0) items.len - 1 else i - 1; + if (items[i].kind == .hit) break; + } else return; + setCurrent(p, id, i, true); +} + +/// Where the current row points, shown with the keyboard left where it is: +/// a place in an open pane's text selected there (its places' current), +/// in view; a file an open pane shows, its line there; any other file in +/// the +Preview under this pane. Every pane it moves remembers its view +/// first, for Esc. +fn showTarget(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const c = q.current orelse return; + const f = &rp.file.?; + if (c + 1 >= f.location_rows.len) return; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + const keyboard = p.active; + defer p.active = keyboard; + if (it.serial != 0) { + const tid = p.paneBySerial(it.serial) orelse return; + const tp = p.panes[tid].?; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + if (placeOnLine(p, tp, meta.at.line)) |hi| tp.places.goTo(tp, hi, false); + return; + } + if (q.source == .symbols) { + const oid = p.paneBySerial(q.owner) orelse return; + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + } + if (q.source == .panes) return; + if (meta.path.len == 0) return; + // A file open in a pane: shown there. + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, meta.path)) continue; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + const line0 = meta.at.line -| 1; + const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows; + if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center); + return; + } + displayPreview(p, id, meta.path, meta.at); +} + +// ---- the +Preview ---- + +/// The +Preview under query pane `qid`, if it has one: by serial. +fn previewOf(p: *Pardes, qid: usize) ?usize { + const q = p.panes[qid].?.query.?; + if (q.preview == 0) return null; + return p.paneBySerial(q.preview) orelse { + q.preview = 0; + return null; + }; +} + +/// Whether `pane` is a query pane's +Preview: that query pane's slot. +pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { + const f = pane.file orelse return null; + const o = f.output orelse return null; + if (o.from != .preview) return null; + for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; + return null; +} + +/// A +Preview made under query pane `qid`, out of its rows alone. +fn makePreview(p: *Pardes, qid: usize) ?usize { + const rp = p.panes[qid].?; + const free = p.freeSlot() orelse return null; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const content = p.gpa.dupe(u8, "") catch return null; + const np = Output.open(p, free, dir, .preview, "", content) catch { + p.gpa.free(content); + return null; + }; + layout.compute(p); + const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; + // Out of the group's root, the text that asked: the query pane keeps + // the rows it was typed into with (made later, for a reused pane). + if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + p.removePane(free, qid) catch {}; + return null; + } + rp.query.?.preview = np.serial; + return free; +} + +/// File `path` at `at` in the +Preview: its text read (once a file: a +/// file open in a pane would be shown there instead), the place centred +/// and selected. Made when the pane has none and its owner has the rows. +fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { + const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const pane = p.panes[id].?; + const f = &pane.file.?; + if (!std.mem.eql(u8, f.path, path)) { + if (exec.kindOf(path)) |kind| if (kind != .file) return; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch return; + }; + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const owned_path = p.gpa.dupe(u8, path) catch { + p.gpa.free(bytes); + return; + }; + p.gpa.free(f.path); + f.path = owned_path; + File.setContent(p, f, bytes); + f.saved_revision = f.revision; + f.scroll = 0; + f.syntax_dirty = true; + pane.hscroll = 0; + p.sync(); + } + look.clearNavigationSelection(p, pane); + if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { + f.scroll = 0; + f.syntax_dirty = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + return; + } + look.focusPaneLine(p, id, at, .center); + if (at.end_line == 0 or at.end_col <= at.col) + pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) }; +} + +/// The +Preview becomes the file's pane where it stands: same slot, same +/// serial, same rect, its scroll and selection as the preview left them. +/// It is a file pane from here: an empty undo history, the Recent entry, +/// the watch, a file's tag; and a pane of its own, no longer attached (it +/// stays when its query pane goes). +fn promote(p: *Pardes, qid: usize, id: usize) void { + const pane = p.panes[id] orelse return; + const f = &pane.file.?; + f.output = null; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; + f.saved_revision = f.revision; + f.saved_hash = null; + f.saved_len = null; + f.disk_gone = false; + f.syntax_dirty = true; + pane.attached_to = null; + if (Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path); + if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + pardes.ctlfs.events.noteLog(p, .rename, pane); + p.panes[qid].?.query.?.preview = 0; +} + +// ---- Enter, Esc ---- + +/// Enter on line 1 (or on a row, `row`): the keyboard to the current hit +/// in its pane (the +Preview promoted to the file's pane when it shows +/// it), a `/` into the register, and the rows frozen into ordinary text. +pub fn land(p: *Pardes, id: usize, row: ?usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true); + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + freeze(p, id); + const owner_id = p.paneBySerial(q.owner); + if (q.source == .text) { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const set = &owner.places; + // The whole list now, once, every place found: a result from here. + if (set.started and set.from == rp.serial) { + set.fill(p, owner, std.math.maxInt(usize), @import("regexp.zig").Regex.budget); + makeTextRows(p, id, oid, true) catch {}; + } + if (set.started and set.from == rp.serial) { + if (set.literal) { + var escaped: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&escaped, p.scratch.allocator(), set.pattern) catch {}; + p.registers.put(p.gpa, '/', escaped.items, 0, 1, true); + } else p.registers.put(p.gpa, '/', set.pattern, 0, 1, true); + p.registers.last_search = '/'; + set.provenance = .search; + } + p.jump_force = true; + p.active = oid; + return; + } + const c = q.current orelse { + if (owner_id) |oid| p.active = oid; + return; + }; + const f = &rp.file.?; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + p.jump_force = true; + if (it.serial != 0) { + if (p.paneBySerial(it.serial)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + } + return; + } + switch (q.source) { + .symbols => if (owner_id) |oid| { + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + }, + .panes => if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + }, + else => {}, + } + // The preview shows it: promoted where it stands. + if (previewOf(p, id)) |pid| if (std.mem.eql(u8, p.panes[pid].?.file.?.path, meta.path)) { + promote(p, id, pid); + p.active = pid; + if (q.source == .grep) { + const a = parse(q.asked) orelse return; + const pp = p.panes[pid].?; + pp.places.search(p, pp, .list, rp.serial, a.pat, true, null, false); + } + return; + }; + var buf: [4096 + 64]u8 = undefined; + const address = if (meta.at.line > 0) + std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path + else + meta.path; + look.lookAt(p, id, address); +} + +/// The rows frozen: ordinary text from here, Save works on them; the +/// places they fed stay, while the pane lives; every view stays where the +/// search left it; the preview, of no more use, goes. +fn freeze(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + q.frozen = true; + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial or tp.serial == q.owner) tp.places.forget(p.gpa); + if (previewOf(p, id)) |pid| { + const pv = p.panes[pid].?; + // A preview showing the current row is promoted by `land`: one + // showing another file goes. + _ = pv; + } +} + +/// Esc on line 1 while typing: every view as the search found it, the +/// places it fed gone, and the pane closed (nothing was answered); a +/// reused pane's frozen rows come back instead, and their places. +pub fn cancel(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + const owner_id = p.paneBySerial(q.owner); + for (p.panes) |slot| if (slot) |tp| { + if (tp.places.from != rp.serial and tp.serial != q.owner) continue; + tp.places.restore(p, tp); + tp.places.forget(p.gpa); + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; + if (q.saved) |s| { + q.saved = null; + // A preview made for the query Esc took back has no use: its rows + // go to the text whose rows they were. + if (previewOf(p, id)) |pid| { + p.panes[pid].?.attached_to = null; + p.removePane(pid, owner_id) catch {}; + q.preview = 0; + } + const f = &rp.file.?; + File.setContent(p, f, s.content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = s.rows; + p.gpa.free(q.asked); + q.asked = s.asked; + q.source = s.source; + q.items.clearRetainingCapacity(); + q.items.appendSlice(p.gpa, s.items) catch {}; + p.gpa.free(s.items); + q.current = s.current; + q.total = s.total; + q.k = s.k; + q.frozen = true; + rp.body.cur_row = 0; + rp.body.cur_col = 0; + showCurrent(rp); + // Its places again, as Enter left them. + if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { + const owner = p.panes[oid].?; + owner.places.search(p, owner, .search, rp.serial, a.pat, false, null, false); + }; + if (owner_id) |oid| p.active = oid; + return; + } + if (owner_id) |oid| { + p.removePane(id, oid) catch {}; + p.active = oid; + if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); + } else p.removePane(id, null) catch {}; +} + +/// The pane going (Del, its owner's Del): the places it fed go with it. +pub fn release(p: *Pardes, pane: *Pane) void { + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) { + tp.places.forget(p.gpa); + tp.places.clear(p.gpa); + }; +} + +// ---- keys, the mouse, edits ---- + +/// The keys a query pane answers itself, before its text has them. On +/// line 1, typing: Enter lands, Esc cancels, Ctrl-n, Ctrl-p, Down and Up +/// step the current row. In normal mode: Enter on a hit row lands on it, +/// n and N step. Anything else is ordinary text editing (line 1) or is +/// refused (the rows, while live: clampEdit). Tab stays the exec chord. +pub fn key(p: *Pardes, id: usize, k: Key) bool { + const rp = p.panes[id] orelse return false; + const q = rp.query orelse return false; + if (rp.focus != .body) return false; + const t = &rp.body; + if (q.frozen) return false; + if (t.mode == .normal) { + if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; + if (k.cp == 'n' or k.cp == 'N') { + step(p, id, if (k.cp == 'n') 1 else -1); + return true; + } + if (hit(k, config.look_key) and t.cur_row > 0) { + land(p, id, @intCast(t.cur_row - 1)); + return true; + } + return false; + } + if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false; + if (hit(k, config.escape)) { + cancel(p, id); + return true; + } + if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) { + land(p, id, null); + return true; + } + const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); + const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + if (down or up) { + step(p, id, if (down) 1 else -1); + return true; + } + return false; +} + +/// An edit of a live query pane's text (edit.setEditTextSpan): inside line +/// 1, as typed; one from line 1 into the rows, cut at line 1's end (and a +/// newline put in it, a blank); one wholly in the rows refused, as a tag's +/// prefix refuses one. Null: refused. Lifted from queryline. +pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { + const end = std.mem.indexOfScalar(u8, old, '\n') orelse old.len; + const span = File.spanOf(old, new); + const old_to = old.len - span.tail; + const put = new[span.head .. new.len - span.tail]; + const rows_same = old_to <= end and std.mem.indexOfScalar(u8, put, '\n') == null; + if (rows_same) return new; + if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) { + t.refused = true; + if (t.pane()) |pane| if (p.paneIdOf(pane)) |id| + p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)"); + return null; + } + // From inside line 1 into the rows: what it put in, flat, and what is + // left of line 1 after it; the rows as they were. + const kept = if (old_to < end) old[old_to..end] else ""; + const out = std.mem.concat(p.gpa, u8, &.{ old[0..span.head], put, kept, old[end..] }) catch return null; + for (out[0 .. span.head + put.len + kept.len]) |*c| if (c.* == '\n') { + c.* = ' '; + }; + return out; +} + +/// B3 on a row's gutter (its line number): the row's address, as a +Diff +/// line's prefix is its place (exec.operandAt). Null off a gutter. +pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 { + if (pane.query == null) return null; + const f = pane.file orelse return null; + if (row == 0 or row >= f.location_rows.len) return null; + const meta = f.location_rows[row]; + if (meta.kind != .match or meta.path.len == 0 or meta.location_end == 0 or col >= meta.location_end) return null; + if (meta.at.line == 0) return std.fmt.bufPrint(buf, "{s}", .{meta.path}) catch null; + return std.fmt.bufPrint(buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch null; +} + +/// The tag's start for a query pane: its name and where it is, `+Search +/// 3/27`, `0` with nothing found, `+` while it still counts. +pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![]const u8 { + const name = std.fs.path.basename(path); + const more = if (q.more and !q.frozen) "+" else ""; + if (q.total == 0) return std.fmt.allocPrint(arena, "{s} 0{s}", .{ name, more }); + if (q.k == 0) return std.fmt.allocPrint(arena, "{s} {d}{s}", .{ name, q.total, more }); + return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more }); +} + +/// The other places on a hit row's line tinted, from the pane its rows are +/// in (the first is the row's own mark, Output.decorateRow): the current +/// one strongest, as in that pane's text. +pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const q = pane.query orelse return; + const f = if (pane.file) |*file| file else return; + const th = p.theme(); + const strong = p.chromeTheme().search_bg; + const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + var vr: i32 = 0; + var last: i32 = -1; + while (vr < body_h) : (vr += 1) { + const row = pane.wrapAt(vr).line; + if (row == last or row < 1) continue; + last = row; + const i: usize = @intCast(row - 1); + if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue; + const it = q.items.items[i]; + if (it.kind != .hit or it.serial == 0) continue; + const tid = p.paneBySerial(it.serial) orelse continue; + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp)) continue; + const tf = &tp.file.?; + const meta = f.location_rows[@intCast(row)]; + // Its line's places as they are now, found by the line: the rows + // may be a tick behind the places. + if (meta.at.line == 0 or meta.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, meta.at.line - 1); + const next = File.lineStart(p.gpa, tf, meta.at.line); + const line = modal.lineSlice(f.content, @intCast(row)); + var hi = Places.firstFrom(set.hits.items, ls); + while (hi < set.hits.items.len and set.hits.items[hi].start < next) : (hi += 1) { + const h = set.hits.items[hi]; + if (h.start < ls + meta.source_column) continue; + const a = meta.code_start + (h.start - ls - meta.source_column); + const b = @min(line.len, meta.code_start + (@min(h.end, next) - ls - meta.source_column)); + if (b <= a or a >= line.len) continue; + const current = set.current != null and set.current.? == hi; + File.paintWordSelection(p, s, pane, r, row, @intCast(a), @intCast(b), if (current) strong else quiet); + } + } +} + +// ---- tests ---- + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn queryPane(p: *Pardes) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null) return i; + return null; +} + +test "parse: line 1's first word names the source" { + try std.testing.expectEqual(Source.text, parse("/alpha").?.source); + try std.testing.expectEqualStrings("alpha", parse("/alpha").?.pat); + try std.testing.expectEqual(Source.find, parse("Find lay").?.source); + try std.testing.expectEqualStrings("lay", parse("Find lay").?.pat); + try std.testing.expectEqual(Source.grep, parse("Grep").?.source); + try std.testing.expectEqual(Source.all, parse("All x y").?.source); + try std.testing.expectEqualStrings("x y", parse("All x y").?.pat); + try std.testing.expectEqual(Source.refs, parse("Refs").?.source); + try std.testing.expect(parse("Findx") == null); + try std.testing.expect(parse("grep x") == null); + try std.testing.expect(parse("") == null); +} + +test "a / query: keystroke by keystroke, the owner shows the set, rows from its own rows alone, zero hits a state, Esc puts all back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + p.newScratchBelow(0); + const below = p.col_panes[0][1]; + p.active = 0; + layout.compute(p); + const before = p.rects; + // cursor on line 3 (row 2) + pane.body.cur_row = 2; + pane.body.cur_col = 0; + typeKeys(p, "/"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid)); + try std.testing.expectEqual(qid, p.active); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + const born = p.rects[qid]; + try std.testing.expectEqualStrings("/", lineOne(qp.file.?.content)); + // keystroke 1 + typeKeys(p, "a"); + const q = qp.query.?; + try std.testing.expectEqual(Source.text, q.source); + try std.testing.expect(pane.places.started and pane.places.from == qp.serial); + try std.testing.expect(q.total > 0); + try std.testing.expectEqualDeep(born, p.rects[qid]); + // keystroke 2 .. `alph`: four places on four lines (rows), the + // current the first at or after the cursor (line 3's alphabet) + typeKeys(p, "lph"); + try std.testing.expectEqual(@as(usize, 4), q.total); + try std.testing.expectEqual(@as(usize, 2), q.k); + try std.testing.expectEqual(@as(?usize, 1), pane.places.current); + const sel = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 15), @min(sel.anchor, sel.head)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expectEqual(qid, p.active); + // Ctrl-n steps, the owner follows + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(usize, 3), q.k); + // drawn: rows, tints, ticks + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + try std.testing.expect(p.surface.nrail_ticks > 0); + // zero hits: a state, the pane stays where it was, line 1 as typed + typeKeys(p, "zz"); + try std.testing.expectEqual(@as(usize, 0), q.total); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expectEqualStrings("/alphzz", lineOne(qp.file.?.content)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + const tag = try tagline.pathPrefix(p, p.scratch.allocator(), qp); + try std.testing.expectEqualStrings("+Search 0", tag); + // Esc: the pane gone, its rows back to the owner, the owner as it was + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expectEqual(@as(usize, 0), p.active); + layout.compute(p); + try std.testing.expectEqualDeep(before[0], p.rects[0]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expect(!pane.places.started); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); +} + +test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + typeKeys(p, "/alpha"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(q.frozen); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("alpha", p.registers.value('/', 0).?); + try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance); + const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content); + defer std.testing.allocator.free(frozen); + // the rows: one a line (gamma alpha has one), a gutter number each + try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); + // n and N in the owner step the same set, round the end silently + const logged = p.messages.len; + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + typeKeys(p, "nnn"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + try std.testing.expect(pane.places.wrapped); + try std.testing.expectEqual(logged, p.messages.len); + typeKeys(p, "N"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + // a later `/` reuses the pane: line 1 fresh, the rows the new query's + typeKeys(p, "/"); + try std.testing.expectEqual(qid, queryPane(p).?); + try std.testing.expectEqual(qid, p.active); + try std.testing.expect(!q.frozen); + typeKeys(p, "beta"); + try std.testing.expectEqual(@as(usize, 1), q.total); + // Esc: the frozen rows of `/alpha` again, the owner's places with them + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expect(q.frozen); + try std.testing.expectEqualStrings(frozen, qp.file.?.content); + try std.testing.expectEqualStrings("alpha", pane.places.pattern); + // Del closes it, its places with it + exec.runBuiltin(p, .Del, qid, "", null); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!pane.places.started); +} + +/// A test's file pane in `tmp`, named `name`, holding `text`. +fn testFileIn(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) !*Pane { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, name }); + return pane; +} + +fn leader(p: *Pardes, keys: []const u8) void { + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + typeKeys(p, keys); +} + +fn settle(p: *Pardes) void { + var frames: usize = 0; + while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick); + p.update(.tick); +} + +test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "src"); + for ([_][]const u8{ "src/layout.zig", "src/look.zig", "notes.md" }) |name| + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "pub fn split() void {}\nconst x = 1;\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "x.txt", "x\n"); + p.newScratchBelow(0); + const other = p.col_panes[0][1]; + try std.testing.expect(layout.splitColumn(p, other, other, false)); + p.active = 0; + layout.compute(p); + const before = p.rects; + leader(p, "ff"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + try std.testing.expectEqual(Source.find, q.source); + try std.testing.expectEqualStrings("Find ", lineOne(p.panes[qid].?.file.?.content)); + // the group: owner, query pane, +Preview, out of the owner's rows alone + const pv = previewOf(p, qid).?; + try std.testing.expectEqual(@as(usize, 0), layout.groupRoot(p, pv)); + try std.testing.expectEqualDeep(before[other], p.rects[other]); + try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[qid].h + p.rects[pv].h); + settle(p); + // an empty query lists every name + try std.testing.expectEqual(@as(usize, 4), q.total); + const born = p.rects; + typeKeys(p, "lay"); + settle(p); + try std.testing.expectEqual(@as(usize, 1), q.total); + try std.testing.expectEqualDeep(born[qid], p.rects[qid]); + try std.testing.expectEqualDeep(born[pv], p.rects[pv]); + // the current one in the preview, never by the pointer + try std.testing.expect(std.mem.endsWith(u8, p.panes[pv].?.file.?.path, "src/layout.zig")); + try std.testing.expectEqual(qid, p.active); + const serial = p.panes[pv].?.serial; + const rect = p.rects[pv]; + p.update(.{ .key = .{ .cp = Key.enter } }); + // promoted where it stands: same slot, serial, rect; a file pane now + try std.testing.expectEqual(pv, p.active); + try std.testing.expectEqual(serial, p.panes[pv].?.serial); + try std.testing.expect(p.panes[pv].?.file.?.output == null); + try std.testing.expect(p.panes[pv].?.attached_to == null); + layout.compute(p); + try std.testing.expectEqualDeep(rect, p.rects[pv]); + try std.testing.expect(q.frozen); + try std.testing.expectEqualDeep(before[other], p.rects[other]); +} + +test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "one needle\ntwo\n"); + leader(p, "fg"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + typeKeys(p, "needle"); + settle(p); + // a.txt's one, b.zig's three lines + try std.testing.expectEqual(@as(usize, 3), q.total); + const body = p.panes[qid].?.file.?.content; + try std.testing.expect(std.mem.indexOf(u8, body, "\nb.zig\n") != null); + // the open file's hits are its places + try std.testing.expect(a.places.started and a.places.hits.items.len == 1); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!a.places.started); + + // All: a second pane, both searched, grouped by serial + p.newScratchBelow(0); + const s = p.active; + const sf = &p.panes[s].?.file.?; + File.setContent(p, sf, try p.gpa.dupe(u8, "needle needle twice\n")); + p.active = 0; + leader(p, "/"); + const aid = queryPane(p).?; + const aq = p.panes[aid].?.query.?; + try std.testing.expectEqual(Source.all, aq.source); + typeKeys(p, "needle"); + settle(p); + try std.testing.expectEqual(@as(usize, 3), aq.total); + const all = p.panes[aid].?.file.?.content; + var hb: [32]u8 = undefined; + const first = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{a.serial})).?; + const second = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{p.panes[s].?.serial})).?; + try std.testing.expect(a.serial < p.panes[s].?.serial and first < second); + try std.testing.expect(second < std.mem.indexOf(u8, all, "twice").?); + // two places on one line are one row + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all, "twice")); +} + +test "zz query timings on the 1.2 MB stress file (QUERY_TIMES=<path>)" { + const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(8 << 20)); + defer std.testing.allocator.free(bytes); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + pane.body.cur_row = 15000; + pane.ensureCursorVisible(); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const Clock = struct { + fn step(pp: *Pardes, fr: *std.heap.ArenaAllocator, ev: pardes.Event) !u64 { + const t0 = Places.nowNs(); + pp.update(ev); + _ = fr.reset(.retain_capacity); + _ = try pp.render(fr.allocator()); + return Places.nowNs() - t0; + } + }; + var report: std.ArrayList(u8) = .empty; + defer report.deinit(std.testing.allocator); + var base: u64 = 0; + for (0..10) |_| base += try Clock.step(p, &frame, .{ .key = .{ .cp = 'j', .text = "j" } }); + try report.print(std.testing.allocator, "a cursor move and its frame, no search: {d} us\n", .{base / 10 / 1000}); + const t_open = try Clock.step(p, &frame, .{ .key = .{ .cp = '/', .text = "/" } }); + try report.print(std.testing.allocator, "open / {d} us\n", .{t_open / 1000}); + for ("pane.v") |c| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + var ticks: usize = 0; + var worst: u64 = 0; + while (busy(p) or pane.places.busy(pane)) : (ticks += 1) { + if (ticks > 500) break; + worst = @max(worst, try Clock.step(p, &frame, .tick)); + } + const qid = queryPane(p).?; + try report.print(std.testing.allocator, "key '{c}': {d} us, then {d} ticks (worst {d} us), {d} places\n", .{ c, t / 1000, ticks, worst / 1000, p.panes[qid].?.query.?.total }); + } + // Enter: frozen; then edits in the owner with the pane open. + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = Key.enter } }); + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = 'i', .text = "i" } }); + var worst_edit: u64 = 0; + var sum: u64 = 0; + for (0..20) |_| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + worst_edit = @max(worst_edit, t); + sum += t; + const t2 = try Clock.step(p, &frame, .tick); + worst_edit = @max(worst_edit, t2); + } + try report.print(std.testing.allocator, "edit in the owner (insert x, then a tick): mean {d} us, worst {d} us\n", .{ sum / 20 / 1000, worst_edit / 1000 }); + // The same edits with no query pane at all, for the editor's own cost. + p.update(.{ .key = .{ .cp = Key.escape } }); + exec.runBuiltin(p, .Del, queryPane(p).?, "", null); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + sum = 0; + for (0..20) |_| sum += try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + try report.print(std.testing.allocator, "the same edit, no search: mean {d} us\n", .{sum / 20 / 1000}); + std.debug.print("{s}", .{report.items}); +} + +test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration; SearchPane new leaves the last where it is" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text + typeKeys(p, "e*"); + const qid = queryPane(p).?; + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/")); + try std.testing.expect(pane.places.started); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + // SPC b b: the open panes by name; Enter goes to the marked one + p.newScratchBelow(0); + const other = p.active; + p.active = 0; + leader(p, "bb"); + const bid = queryPane(p).?; + try std.testing.expectEqual(bid, qid); + try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source); + try std.testing.expect(p.panes[bid].?.query.?.total >= 1); + // SPC s s: the declarations, fuzzy; Enter lands on the line + p.update(.{ .key = .{ .cp = Key.escape } }); + p.active = 0; + leader(p, "ss"); + const sid = queryPane(p).?; + try std.testing.expectEqual(Source.symbols, p.panes[sid].?.query.?.source); + // (context declarations span lines: a one-line fn is none of them) + typeKeys(p, "bet"); + try std.testing.expectEqual(@as(usize, 1), p.panes[sid].?.query.?.total); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + _ = other; + // SearchPane new: the frozen one stays, unattached; a new one under the owner + p.settings.search_pane = .new; + typeKeys(p, "/"); + const nid = queryPane2(p, sid).?; + try std.testing.expect(nid != sid); + try std.testing.expect(p.panes[sid].?.attached_to == null); + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, nid)); +} + +fn queryPane2(p: *Pardes, not: usize) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i; + return null; +} diff --git a/src/Text.zig b/src/Text.zig index cef76b3b..88630f83 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -182,7 +182,10 @@ pub fn primaryRange(t: *Text, text: []const u8, row0: i32) modal.Selection { const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; } - if (t.vsel.active) return cellRange(text, t.vsel.row - row0, t.vsel.col, t.cur_row - row0, t.cur_col); + // Both ends through the line index, as the cursor's: cellRange counts + // lines from the top for each, a pass over a big file per call (the + // places' settle and every insert-mode key asked it). + if (t.vsel.active) return cellOffRange(text, File.textOffset(t, text, .{ .row = @intCast(@max(0, t.vsel.row - row0)), .col = @intCast(@max(0, t.vsel.col)) }), c); return .{ .anchor = c, .head = modal.nextGrapheme(text, c) }; } diff --git a/src/body_layer.zig b/src/body_layer.zig index d44045a6..e50b7e3e 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -275,6 +275,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); pane.places.paint(p, s, pane, r, body_h); + panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal() and p.settings.colors) { panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); diff --git a/src/builtins.zig b/src/builtins.zig index 1ec33d88..7cdee9de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -210,7 +210,7 @@ pub const registry = struct { .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, // bare, it says the current value (exec.applySettingBuiltin) - .tab, .callstack_depth => false, + .tab, .callstack_depth, .search_rows => false, }; return declOr(b, "requires_arg", false, false); } @@ -1721,7 +1721,8 @@ pub const Find = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.find_marker }); + // Bare (SPC f f): the query pane, line 1 `Find `, typed into. + panes.Query.open(c.p, c.id, .find, "", true); } }; @@ -1738,7 +1739,29 @@ pub const Grep = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.grep_marker }); + // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. + panes.Query.open(c.p, c.id, .grep, "", true); + } +}; + +/// Search in a query pane under this pane, line 1 the argument (`Panes`, +/// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. +pub const Search = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?; + panes.Query.open(c.p, c.id, asked.source, asked.pat, true); + } +}; + +/// Pick an open pane by its name in a query pane under this one (SPC b b). +pub const Panes = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; @@ -1866,9 +1889,13 @@ pub const Last = struct { /// List the files opened lately, closed ones too, each a place to open again. pub const Recent = struct { pub const scope: Scope = .session; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // From a pane: the query pane under it, line 1 `Recent `, typed + // into; from a header, which no pane owns, the +Recent list. + if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 06eec2d9..2fa4a55d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -26,6 +26,26 @@ pub const leader_help: u8 = '?'; const undecided: []const u8 = "<undecided>"; +/// Leader paths that run a builtin WITH an argument (the pick prototype's): +/// the query pane's sources that have no word of their own, `Search` and +/// line 1. `SPC s` is the session group (Dump, Restore, Attach), so the +/// declarations are `SPC s s`, a key from helix's. +pub const leader_args = [_]struct { path: []const u8, cmd: Builtin, arg: []const u8 }{ + .{ .path = "bb", .cmd = .Search, .arg = "Panes" }, + .{ .path = "ss", .cmd = .Search, .arg = "Symbols" }, + .{ .path = "/", .cmd = .Search, .arg = "All" }, +}; + +comptime { + @setEvalBranchQuota(20_000); + // A path here is a leaf: no builtin's path is it or runs past it, and + // none of it is a builtin's whole path. + for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) + @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); + }; +} + // null means word/chord-only. Every enabled builtin must explicitly choose a path. pub const leader_path = paths: { @setEvalBranchQuota(10_000); // a check per builtin, and they grow @@ -94,6 +114,11 @@ pub const leader_path = paths: { .Delcol = "cd", .Joincol = "cj", .Placement = "cp", + .SearchPlace = null, + .SearchPane = null, + .SearchRows = null, + .Search = null, + .Panes = null, .BootShell = null, .LookWord = null, .DirLook = null, @@ -517,6 +542,7 @@ pub const dump_config_buffer = "+DumpConfig"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; pub const recent_buffer = "+Recent"; +pub const preview_buffer = "+Preview"; pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; @@ -846,6 +872,15 @@ pub const Runtime = struct { callstack_layout: CallstackLayout = .stacked, callstack_corners: CallstackCorners = .rounded, callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, + /// Where a query pane goes (Query.zig): `attached`, under the pane that + /// asked, out of its rows alone; `column`, in the finder column. + search_place: SearchPlace = .attached, + /// A search from a pane that has a query pane: `reuse` it (its frozen + /// rows back on Esc), or open a `new` one, the last left where it is. + search_pane: SearchPane = .reuse, + /// The body rows a query pane is born with under its line 1 (and its + /// +Preview with): it never resizes itself after. + search_rows: u16 = 8, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; @@ -858,8 +893,10 @@ pub const Runtime = struct { pub const JumpScope = enum { file, all }; pub const CallstackLayout = enum { @"inline", stacked }; pub const CallstackCorners = @import("lsp/lsp.zig").CallstackCorners; + pub const SearchPlace = enum { attached, column }; + pub const SearchPane = enum { reuse, new }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners, search_place, search_pane }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1048,6 +1085,7 @@ pub const Runtime = struct { grip_width, tab, callstack_depth, + search_rows, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1137,6 +1175,9 @@ pub const Runtime = struct { .{ .word = "CallstackCorners", .action = .{ .choice = .callstack_corners }, .doc = "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query." }, .{ .word = "CallstackDepth", .action = .callstack_depth, .doc = "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit." }, .{ .word = "Tab", .action = .tab, .doc = "A tab's width in cells, 1 through 16, in every pane; bare, it says the width." }, + .{ .word = "SearchPlace", .action = .{ .choice = .search_place }, .doc = "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column." }, + .{ .word = "SearchPane", .action = .{ .choice = .search_pane }, .doc = "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is." }, + .{ .word = "SearchRows", .action = .search_rows, .doc = "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself." }, }; pub fn find(name: []const u8) ?Setting { @@ -1311,6 +1352,7 @@ pub const Runtime = struct { .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, + .search_rows => state.search_rows = number(u16, argument, " \t\r\n", 1, 100) orelse return false, .theme, .font => return false, } return true; @@ -1348,6 +1390,7 @@ pub const Runtime = struct { .grip_width => "50-300 (a percentage)", .tab => "1-16 (cells)", .callstack_depth => "1-64 (levels)", + .search_rows => "1-100 (rows)", .tagline_size => std.fmt.comptimePrint("{d}-{d} (a percentage)", .{ tagline_percent_min, tagline_percent_max }), .message_ms => std.fmt.comptimePrint("0-{d} (milliseconds)", .{message_ms_max}), .shell => "a path of at most 255 bytes; bare, $SHELL, else /bin/sh", @@ -1490,6 +1533,7 @@ pub const Runtime = struct { .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), + .search_rows => try out.print("{s} {d}\n", .{ setting.word, state.search_rows }), .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1773,6 +1817,8 @@ pub const Runtime = struct { .jump_scope => "all", .callstack_layout => "inline", .callstack_corners => "square", + .search_place => "column", + .search_pane => "new", }, .lift => "rim", .motion => "playful", @@ -1780,6 +1826,7 @@ pub const Runtime = struct { .grip_width => "200", .callstack_depth => "16", .tab => "8", + .search_rows => "12", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1853,6 +1900,8 @@ pub const Runtime = struct { .jump_scope => "JumpScope all\n", .callstack_layout => "CallstackLayout inline\n", .callstack_corners => "CallstackCorners square\n", + .search_place => "SearchPlace column\n", + .search_pane => "SearchPane new\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", @@ -1860,6 +1909,7 @@ pub const Runtime = struct { .grip_width => "GripWidth 200\n", .callstack_depth => "CallstackDepth 16\n", .tab => "Tab 8\n", + .search_rows => "SearchRows 12\n", .theme, .font => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, report, expected) != null); @@ -2212,6 +2262,7 @@ const doc_typ = struct { if (n == 0) return leader.len == 1 and leader[0].cp == ' '; for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.eql(u8, p, path[0..n])) return true; + for (leader_args) |la| if (std.mem.eql(u8, la.path, path[0..n])) return true; return false; } toks.reset(); @@ -2308,6 +2359,7 @@ const doc_tutor = struct { fn path(keys: []const u8) bool { for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.startsWith(u8, p, keys)) return true; + for (leader_args) |la| if (std.mem.startsWith(u8, la.path, keys)) return true; return false; } diff --git a/src/edit.zig b/src/edit.zig index c9477c29..a06f5f2d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -568,6 +568,26 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp return; } const pane = t.pane() orelse return retireEditText(p, new); + // A live query pane's rows are its line 1's (Query.zig): an edit there + // is refused, as a tag's prefix refuses one, and one from line 1 into + // them is cut at its end. The rows' metadata stays theirs across an + // edit of the line, which moves no row. + if (pane.file) |*f| if (pane.query) |q| if (!q.frozen) { + const kept = panes.Query.clampEdit(p, t, f.content, new) orelse return retireEditText(p, new); + if (kept.ptr != new.ptr) retireEditText(p, new); + const end = modal.positionAt(kept, kept.len - panes.File.spanOf(f.content, kept).tail); + t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; + const rows = f.location_rows; + const spans = f.pager_spans; + f.location_rows = &.{}; + f.pager_spans = &.{}; + panes.File.setContentSpan(p, f, kept, null); + if (f.location_rows.len > 0) @import("locations.zig").freeRows(p.gpa, f.location_rows); + p.gpa.free(f.pager_spans); + f.location_rows = rows; + f.pager_spans = spans; + return; + }; // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; // ponytail: O(file), for the edits that do not say what they changed diff --git a/src/exec.zig b/src/exec.zig index a9c11049..2bc1a3e5 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -194,6 +194,20 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l // the look is of the address it names (look.diffAddress), a regular // look from there. A hunk line's code is words, looked at as ever: // the code's, the prefix never one of them. + // A query pane's row pointed at on its gutter (its line number): the + // look is of the row's address (Query.rowAddress), as a +Diff line's + // prefix is its place; the row's code is words, looked at as ever. + if (for_look and pane.query != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and col >= 0) gutter: { + var address_buf: [4096 + 32]u8 = undefined; + const address = panes.Query.rowAddress(pane, @intCast(row), @intCast(col), &address_buf) orelse break :gutter; + const meta = pane.file.?.location_rows[@intCast(row)]; + result.text = p.scratch.allocator().dupe(u8, address) catch break :gutter; + result.file_word = .{ .row = row, .lo = 0, .hi = @intCast(meta.location_end) }; + const expanded = fileWordCells(pane, clicked, row, 0, @intCast(meta.location_end)) orelse return result; + result.preview = expanded; + result.expanded = expanded; + return result; + } var word_from: usize = 0; if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0) diff: { var address_buf: [4096 + 32]u8 = undefined; @@ -1118,6 +1132,12 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } else if (!p.settings.apply(setting, arg)) { p.reportFailure(p.active, "CallstackDepth: takes " ++ comptime config.Runtime.takes(.callstack_depth).?); }, + .search_rows => if (arg == null) { + var said: [40]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "SearchRows {d}", .{p.settings.search_rows}) catch "SearchRows"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "SearchRows: takes " ++ comptime config.Runtime.takes(.search_rows).?); + }, // Bare, it says the width, as acme's Tab does. .tab => if (arg == null) { var said: [32]u8 = undefined; @@ -1119,7 +1119,7 @@ const find_max_steps = 100_000; /// One root's Find or Grep rows at most: its hits, each a path and a line. pub const search_root_output_bytes = find_max_hits * (4096 + 320); -const find_skip = [_][]const u8{ +pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; diff --git a/src/layout.zig b/src/layout.zig index f0689b10..dac0aa7e 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1016,21 +1016,31 @@ pub fn keepGroups(p: *Pardes) void { /// False, `id` in no column, when the owner has not the rows for its tag /// and the attachment's minimum. pub fn attach(p: *Pardes, owner: usize, id: usize, rows: u16) bool { + return attachFrom(p, owner, id, rows, owner); +} + +/// attach, the rows given by `giver`: the owner itself or a pane of its +/// group (a +Preview added under a query pane later takes the text's rows, +/// so the query pane, typed into, keeps its own). +pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool { const o = p.panes[owner] orelse return false; + const g = p.panes[giver] orelse return false; const nw = p.panes[id] orelse return false; if (o.collapsed) toggleCollapse(p, owner); + if (g.collapsed) toggleCollapse(p, giver); compute(p); const f = findPane(p, owner) orelse return false; + if (giver != owner and groupRoot(p, owner) != groupRoot(p, giver)) return false; // Its tag wraps at the column's width: measured there. p.rects[id].w = p.col_w[f.col]; - const oh = p.rects[owner].h; + const oh = p.rects[giver].h; const least = minRows(p, id); if (oh < least + BOX_H) return false; - const owner_keeps = if (oh >= least + minRows(p, owner)) minRows(p, owner) else BOX_H; - const give = std.math.clamp(rows, least, oh - owner_keeps); + const giver_keeps = if (oh >= least + minRows(p, giver)) minRows(p, giver) else BOX_H; + const give = std.math.clamp(rows, least, oh - giver_keeps); snapColWeights(p, f.col); insert(p, f.col, groupEnd(p, f.col, f.idx), id); - o.vweight = @floatFromInt(oh - give); + g.vweight = @floatFromInt(oh - give); nw.vweight = @floatFromInt(give); nw.attached_to = o.serial; compute(p); diff --git a/src/look.zig b/src/look.zig index 2d97cb9f..eed3dbd9 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1719,6 +1719,8 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void { /// Whether `pane` is the +Recent or the Jumplist list, whose rows are /// remembered places: a look at one clamps to the file as it is now. fn isRecentList(pane: *const Pane) bool { + // A query pane over the recent files: its rows are remembered places. + if (pane.query) |q| if (q.source == .recent) return true; const f = pane.file orelse return false; const o = f.output orelse return false; return std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Recent }) or std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Jumplist }); diff --git a/src/mouse.zig b/src/mouse.zig index ec5560d0..3400afbe 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1083,6 +1083,15 @@ pub fn dispatchPointerBuiltin( // nothing, as acme's look3 and execute return on an empty expansion. const operand = text orelse return; if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg)) return; + // B2 anywhere on a query pane's line 1 is the line: run again, whatever + // word of it was clicked (Query.zig). + if (gesture) |g| if (!g.on_tag and g.operand.row == 0 and cmd == config.exec_cmd) if (p.panes[id]) |pane| if (pane.query) |q| { + p.gpa.free(q.asked); + q.asked = &.{}; + q.frozen = false; + panes.Query.produceAll(p, false); + return; + }; // A middle click on a body is the exec a bound REPL may take. exec.runBuiltinFrom(p, cmd, id, "", exec.withArg(p, operand, arg), gesture != null and !gesture.?.on_tag); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f9bec775..45336a1e 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -89,6 +89,8 @@ pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) vo const after = Serials.snapshot(p); var created = false; for (after.list[0..after.len]) |serial| if (std.mem.indexOfScalar(u32, before.list[0..before.len], serial) == null) { + // A query pane's +Preview is its query pane's: that answers. + if (p.paneBySerial(serial)) |made| if (p.panes[made].?.file) |f| if (f.output) |o| if (o.from == .preview) continue; // A look that made a +Search pane (LookWord list, a terminal) // answers it: that is where the places it found are. noteResult(p, serial); @@ -555,6 +557,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? // Bare, it says the width, as from a pane's exec. .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, + .search_rows => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 100, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -664,6 +667,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .inactive_dim => try w.print("{s} {d}\n", .{ word, s.inactive_dim }), .grip_width => try w.print("{s} {d}\n", .{ word, s.grip_width }), .callstack_depth => try w.print("{s} {d}\n", .{ word, s.callstack_depth }), + .search_rows => try w.print("{s} {d}\n", .{ word, s.search_rows }), .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } @@ -3890,8 +3894,10 @@ test "Recent's row for a file still open is where its dot is now, not where it l pane.body.cur_col = 2; try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}/a.txt:2:3 open\n", .{dir})) != null); + // A query pane under the file (line 1 `Recent `), its rows said from + // its directory. + try testing.expect(std.mem.startsWith(u8, rows.file.?.content, "Recent \n")); + try testing.expect(std.mem.indexOf(u8, rows.file.?.content, "\na.txt:2:3 open\n") != null); } test "a closed file is found again: Recent and /recent list it closed, a look at its row reopens it at its dot, and a jump back does too" { @@ -3924,7 +3930,8 @@ test "a closed file is found again: Recent and /recent list it closed, a look at // Recent lists it, closed, at its dot; a look at the row opens it there. try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - const at = std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}:3:", .{a})).?; + // Its query pane's rows are said from its directory, a.txt's. + const at = std.mem.indexOf(u8, rows.file.?.content, "\na.txt:3:").? + 1; const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; try testing.expect(std.mem.endsWith(u8, row, " (closed)")); try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), try std.fmt.bufPrint(&line, "{s}\n", .{row[0 .. row.len - " (closed)".len]})).reply.status); @@ -3939,6 +3946,9 @@ test "a closed file is found again: Recent and /recent list it closed, a look at var closed_entry = false; for (p.jumps[0..p.njumps]) |j| closed_entry = closed_entry or j.serial == 0; try testing.expect(closed_entry); + // Every entry in order (JumpScope all): which file has the focus after + // a Del is the layout's to choose, and Back keeps to it first. + p.settings.jump_scope = .all; var tries: usize = 0; while (tries < p.njumps) : (tries += 1) { p.jumpBy(-1); diff --git a/src/normal.zig b/src/normal.zig index 808ac886..ebace536 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -930,7 +930,12 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), - .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), + // `/` in a text is its query pane's line 1 (Query.zig); a + // terminal's still asks on the notice band. + .search => if (pane.file != null and t.what == .body) + panes.Query.open(p, p.active, .text, "", true) + else + return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for // the register (Places.answersN); else helix's search of the register. .search_step => |step| if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) @@ -939,12 +944,13 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void return searchStep(p, t, text, step.direction, step.count), .search_selection => |boundary| { searchSelection(p, t, text, boundary); - // The pattern's places: the selection is already on one of them. - if (t.what == .body and pane.file != null) { + // The pattern is line 1 of this text's query pane, made or + // reused, the keyboard staying here: n and N step its places. + if (t.what == .body and pane.file != null and !pane.hasPdf() and pane.query == null) { const name = if (p.register != 0) p.register else '/'; const pat = p.registers.value(name, 0) orelse return; - const r = pane.body.primaryRange(text, 0); - pane.places.search(p, pane, .search, 0, pat, false, @min(r.anchor, r.head), false); + panes.Query.open(p, p.active, .text, pat, false); + pane.places.provenance = .search; } }, .node => |walk| return nodeSelect(p, pane, t, walk), diff --git a/src/panes.zig b/src/panes.zig index 73794b91..e0eb3fec 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -108,6 +108,9 @@ pub const Pane = struct { /// gone, or a pane no longer right under its owner's group, leaves it /// an ordinary pane (layout.keepGroups). attached_to: ?u32 = null, + /// This pane is a query pane: its line 1 the query, its rows made live + /// from a source (Query.zig, gpa-owned). + query: ?*Query = null, cols: u16, rows: u16, greet: bool = false, @@ -463,6 +466,8 @@ pub const Pane = struct { if (f.mini != null) return .source; if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; if (f.output != null) { + // A +Preview is a file's text: coloured as the file. + if (f.output.?.from == .preview) return .source; const tr = Output.fileTraits(f.output); if (tr.locations) return .locations; if (!tr.saves) return .none; @@ -655,6 +660,8 @@ pub const Output = @import("Output.zig"); pub const Places = @import("Places.zig"); +pub const Query = @import("Query.zig"); + pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c4011f7d..1b4e9920 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -486,6 +486,8 @@ test { _ = @import("animation.zig"); _ = @import("pager.zig"); _ = @import("Places.zig"); + _ = @import("Query.zig"); + _ = @import("Names.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4402,6 +4404,9 @@ pub const Pardes = struct { jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, + /// The next place tracked is an entry of its own however near the last + /// (a query answered: Ctrl-o goes back to where it was asked). + jump_force: bool = false, look_src: [MAX_PANES]u32 = undefined, n_look_src: usize = 0, look_walk_owner: ?u32 = null, @@ -5049,6 +5054,8 @@ pub const Pardes = struct { // to it reopen it there. p.noteClosed(pane); panes.Output.dropUnsaved(p, pane); + // A query pane's places, in whatever panes it fed, go with it. + if (pane.query != null) panes.Query.release(p, pane); if (pane.file) |*file| panes.File.leaveTwins(p, file); const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { @@ -5084,6 +5091,11 @@ pub const Pardes = struct { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + if (pane.query) |q| { + q.deinit(p.gpa); + p.gpa.destroy(q); + pane.query = null; + } panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); @@ -6121,6 +6133,8 @@ pub const Pardes = struct { // Each pane's places find a frame's more on a tick, and on any other // step the ones an edit or a scroll left unfound in the view. for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); + // Each live query pane's rows, made from what changed this step. + panes.Query.produceAll(p, ev == .tick); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); @@ -6450,6 +6464,9 @@ pub const Pardes = struct { return; } if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); + // A query pane's line 1 answers Enter, Esc and the stepping keys + // itself (Query.zig). + if (t == &pane.body and header == null and pane.query != null and panes.Query.key(p, p.active, key)) return; if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) { // A header's words are the workspace's and column's commands, so // Enter runs them there, as the execute key does. @@ -6564,6 +6581,12 @@ pub const Pardes = struct { p.leader_keys[p.leader_n] = c; p.leader_n += 1; const pfx = p.leader_keys[0..p.leader_n]; + // A path that runs a builtin with its argument (the query pane's + // sources with no word of their own). + for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, p.active, "", la.arg); + for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) { + p.leader_on = true; + }; // a path-less builtin is a row here too (it is the same index Help // reads), and SPC cannot reach one — so both scans skip it for (builtin_rows) |row| { @@ -7017,6 +7040,21 @@ pub const Pardes = struct { return; } + // The lists of places: into the asking text's query pane (made or + // reused), line 1 their word, the places in that text its places. + const listed: ?panes.Query.Source = switch (w.kind) { + .references => .refs, + .definition => .defs, + .implementation => .impls, + .diagnostics => .diagnostics, + else => null, + }; + if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) { + p.fs.refilled = null; + panes.Query.fillList(p, w.pane, source, rows); + p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null; + return; + }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // A Callstack page that stops short ends in its marker: said as a // row naming the word that shows the next page, and kept. @@ -7285,6 +7323,11 @@ pub const Pardes = struct { p.jcur = @min(cur, w -| 1); const pane = p.panes[p.active] orelse return; + // A query being typed moves the owner's selection to show, never a + // jump; its pane is no place to come back to either. + if (pane.query) |q| if (!q.frozen) return; + const force = p.jump_force; + p.jump_force = false; const now: Loc = .{ .pane = @intCast(p.active), .serial = pane.serial, @@ -7292,14 +7335,14 @@ pub const Pardes = struct { .col = if (pane.pdfPage() != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0, .path_hash = if (recentDot(pane)) |d| std.hash.Wyhash.hash(0, d.path) else 0, }; - if (p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { + if (!force and p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { p.jumps[p.jcur] = now; // same visit; the entry IS where you are return; } // a new jump made from the middle of the list drops everything ahead of // it, the way vim's does: the future you did not take is not history. if (p.njumps > 0) p.njumps = p.jcur + 1; - if (p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { + if (!force and p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { p.jumps[p.njumps - 2] = p.jumps[p.njumps - 1]; p.jumps[p.njumps - 1] = now; p.jcur = p.njumps - 1; @@ -7588,6 +7631,7 @@ pub const Pardes = struct { if (p.chrome_animation.isActive() or p.presentation.animating()) return next; // Places still to find resume on the next frame. for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; + if (panes.Query.busy(p)) return next; var frames: ?u64 = null; if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames orelse return next; @@ -8003,11 +8047,13 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); defer std.testing.allocator.free(tag_before); - p.update(.{ .key = .{ .cp = '/' } }); + // `s` keeps a prompt on the band (a text's `/` is its query pane's + // line 1 now, Query.zig). + p.update(.{ .key = .{ .cp = 's' } }); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); try std.testing.expect(pane.prompt == .search and pane.focus == .body); - try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); + try std.testing.expectEqualStrings(config.select_marker ++ "tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); // The tagline is exactly what it was: nothing of the prompt is in it. diff --git a/src/tagline.zig b/src/tagline.zig index e668419d..89152a3a 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -35,6 +35,10 @@ pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; +/// A query pane's while its rows are made (Query.zig), and once Enter froze +/// them into text a Save keeps; Unattach leaves it where it stands. +pub const query_live_tail = " Del"; +pub const query_frozen_tail = " Save Unattach Del"; /// A file with changes it has not saved. pub fn dirty(pane: *const panes.Pane) bool { const f = pane.file orelse return false; @@ -135,6 +139,9 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co var idbuf: [48]u8 = undefined; return std.fmt.allocPrint(arena, "{s} {s}", .{ (try shownDir(arena, pane)), exec.replId(&idbuf, pane) }); } + // A query pane: its name and where it is among its hits, `+Search + // 3/27` (Query.zig): its owner is right above it. + if (pane.query) |q| if (pane.file) |f| if (pane.prompt != .name) return panes.Query.tagPrefix(q, arena, f.path); // Unsaved text shows on the grip, as acme's modbutton does, not as a // mark in the text: the prefix is the name alone. if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; @@ -174,6 +181,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; + if (pane.query) |q| return if (q.frozen) query_frozen_tail else query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; |
