diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/Output.zig | 31 | ||||
| -rw-r--r-- | src/Query.zig | 176 | ||||
| -rw-r--r-- | src/builtins.zig | 41 | ||||
| -rw-r--r-- | src/config.zig | 7 | ||||
| -rw-r--r-- | src/fs.zig | 285 | ||||
| -rw-r--r-- | src/look.zig | 83 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 50 | ||||
| -rw-r--r-- | src/normal.zig | 28 | ||||
| -rw-r--r-- | src/tagline.zig | 1 | ||||
| -rw-r--r-- | src/tutor.txt | 16 |
10 files changed, 242 insertions, 476 deletions
diff --git a/src/Output.zig b/src/Output.zig index 1e62b04a..01e3e0f1 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -857,15 +857,6 @@ pub fn dropUnsaved(p: *Pardes, gone: *const Pane) void { } } -/// Recent: the one +Recent, filled again when it is there (as Find and -/// Grep's +Search is), else opened below the asking pane. -pub fn openRecent(p: *Pardes, id: usize) !void { - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try recentText(p, &out.writer, true); - try refillOrOpen(p, id, .{ .cmd = .Recent }, try out.toOwnedSlice()); -} - /// The one stepped output from `from`, filled again with `content` when it /// is there (Recent, Jumplist), or opened when it is not. fn refillOrOpen(p: *Pardes, id: usize, from: Origin, content: []u8) !void { @@ -971,6 +962,28 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { } if (show_calls_help) try w.writeAll(calls_help); if (prefix.len == 0) try w.writeAll(language_footer); + // The paths that run a builtin with a word (config.leader_args), and how + // a query pane is driven: under SPC f, b, s and in the whole listing. + const search_group = for (config.leader_args) |la| { + if (std.mem.startsWith(u8, la.path, prefix)) break true; + } else std.mem.eql(u8, prefix, "f"); + if (prefix.len == 0 or search_group) { + try w.writeAll("\nsearch: a query pane under the text,\nits line 1 the query, its first word\nthe source (/ Find Grep Recent Panes\nSymbols All Refs Def Impl Diagnostics)\n"); + for (config.leader_args) |la| { + if (!std.mem.startsWith(u8, la.path, prefix)) continue; + var keys: [16]u8 = @splat(' '); + for (la.path, 0..) |c, i| keys[2 * i] = c; + try w.print("{s} {s} {s}\n", .{ keys[0..8], @tagName(la.cmd), la.arg }); + } + if (prefix.len == 0) try w.writeAll( + "/ * the text (* seeds it)\n" ++ + "C-n C-p Up Down step, typing on line 1\n" ++ + "n N step the text's places\n" ++ + "Enter land there, keep the rows\n" ++ + "Esc put every view back\n" ++ + "More a Grep past 2000 lines\n", + ); + } return out.toOwnedSlice(); } diff --git a/src/Query.zig b/src/Query.zig index 48378a18..3a75a7f5 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -153,8 +153,10 @@ window: struct { lo: usize = 0, hi: usize = 0 } = .{}, /// made every third, the frame's time going to the finding. waited: u8 = 0, names: Names = .{}, -/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`). +/// A Grep's lines, as the disk engine sends them (Stream.zig, `take`), and +/// the current one's index among them. found: std.ArrayList(Found) = .empty, +grep_at: usize = 0, found_bytes: std.ArrayList(u8) = .empty, grep_gen: u32 = 0, /// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave @@ -256,6 +258,10 @@ pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: boo File.setContent(p, f, new); q.reset(p); if (rp.collapsed) layout.toggleCollapse(p, id); + // A source that previews gets its +Preview now, at the key that + // asked, not under the typing later. + if (previews(source) and previewOf(p, id) == null) + _ = makePreview(p, id, @max(pardes.BOX_H, rp.tag_rows) + p.settings.search_rows, layout.groupRoot(p, id)); } else { if (existing) |old| { // SearchPane new: the last one stays where it is, a result of @@ -297,8 +303,20 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize const body: u16 = 1 + p.settings.search_rows; const tag = @max(pardes.BOX_H, np.tag_rows); const with_preview = previews(source); - // The preview, made right after, takes its own rows from the owner. - const want = tag + body; + // The preview, made right after, takes its own rows from the owner: + // when the owner has not the rows for both, they share what it has, so + // the group is whole from the first key and nothing moves later. + var want: u16 = tag + body; + var preview_rows: u16 = tag + p.settings.search_rows; + if (with_preview) { + layout.compute(p); + const spare = p.rects[owner_id].h -| layout.minRows(p, owner_id); + if (spare < want + preview_rows) { + const both = want + preview_rows; + want = @max(tag + 2, @as(u16, @intCast(@as(u32, spare) * want / both))); + preview_rows = spare -| want; + } + } if (p.settings.search_place == .column) { // The finder column (phase 6): until it exists, under the owner. if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); @@ -307,7 +325,7 @@ fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize // new pane is, the one place a search moves another pane. exec.placeNew(p, owner_id, owner_id, free, .doc); } - if (with_preview) _ = makePreview(p, free); + if (with_preview) _ = makePreview(p, free, preview_rows, owner_id); return free; } @@ -495,9 +513,14 @@ fn produce(p: *Pardes, id: usize, tick: bool) void { q.found.clearRetainingCapacity(); q.found_bytes.clearRetainingCapacity(); q.grep_gen +%= 1; + q.grep_at = 0; q.current = null; // On the disk engine's worker, once the typing pauses. - if (a.pat.len > 0) Stream.query(p, rp.serial, .grep, a.pat, dir, .typed) else if (p.stream.target == rp.serial) { + // A script's (a 9P write): run to its end before it answers. + if (a.pat.len > 0) { + Stream.query(p, rp.serial, .grep, a.pat, dir, if (p.fs.serving) .now else .typed); + if (p.fs.serving) Stream.step(p); + } else if (p.stream.target == rp.serial) { _ = p.stream.stop(); } feedGrepPlaces(p, q, rp.serial, a.pat); @@ -548,7 +571,10 @@ fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usiz switch (source) { // The files under the directory, listed once on the disk engine's // worker (rg --files, else the walk); each keystroke scores them. - .find => Stream.query(p, rp.serial, .files, "", dir, .now), + .find => { + Stream.query(p, rp.serial, .files, "", dir, .now); + if (p.fs.serving) Stream.step(p); + }, .recent => { var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); @@ -828,7 +854,9 @@ fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { // Grouped once a parse of the text exists: asked of the worker now. if (ownerDecls(p, &owner.file.?, false) == null) Stream.parseFor(p, oid); const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); - const from = if (full) 0 else at -| live_rows / 2; + // While typed, a window of rows from just before the current place, so + // it sits under line 1. + const from = if (full) 0 else at -| 2; q.window = .{ .lo = from, .hi = from }; if (set.started and set.from == rp.serial) { if (from > 0) { @@ -856,7 +884,9 @@ fn showPlacesCurrent(p: *Pardes, id: usize) void { const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; const set = &owner.places; q.total = if (set.from == rp.serial) set.hits.items.len else 0; - q.more = q.more or (set.from == rp.serial and !set.complete()); + // still counting: the places not all found yet (the rows' own cut is + // said in a row of theirs) + q.more = set.from == rp.serial and !set.complete(); q.k = if (set.current) |c| c + 1 else 0; if (set.from != rp.serial) q.k = 0; q.current = null; @@ -995,6 +1025,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { } } if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + if (q.source == .find) try skippedRow(p, q, rp, &out, &rows); setRows(p, rp, &out, &rows); const f = &rp.file.?; f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; @@ -1004,7 +1035,7 @@ fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { q.current = if (shown > 0) 0 else null; countCurrent(q); showCurrent(rp); - showTarget(p, id); + if (q.current == null) blankPreview(p, id) else showTarget(p, id); } /// A Grep keeps this many lines: the rest wait (the disk engine's `More`). @@ -1016,14 +1047,14 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { const rp = p.panes[id].?; const q = rp.query.?; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; - const at: usize = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].hit else 0) else 0; + const at: usize = @min(q.grep_at, q.found.items.len -| 1); q.items.clearRetainingCapacity(); var out: std.ArrayList(u8) = .empty; defer out.deinit(p.gpa); var rows: std.ArrayList(locations.Row) = .empty; var last_path: []const u8 = ""; var pathbuf: [4096 + 8]u8 = undefined; - const lo = if (full) 0 else at -| live_rows / 2; + const lo = if (full) 0 else at -| 2; const hi = if (full) q.found.items.len else @min(q.found.items.len, lo + live_rows); if (lo > 0) { var hb: [64]u8 = undefined; @@ -1048,12 +1079,23 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} lines after these", .{q.found.items.len - hi}) catch " ..."); } if (p.stream.target == rp.serial and p.stream.state == .capped) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: More in the tag goes on"); + try skippedRow(p, q, rp, &out, &rows); setRows(p, rp, &out, &rows); q.total = q.found.items.len; q.more = p.stream.busyFor(rp.serial); q.current = current orelse firstHit(q); countGrepCurrent(q); showCurrent(rp); + if (q.current == null) blankPreview(p, id); +} + +/// What the disk walk passed over, said under the rows: a search that +/// found nothing where it could not look says so, never just nothing. +fn skippedRow(p: *Pardes, q: *Query, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) !void { + const n = p.stream.skipped; + if (p.stream.target != rp.serial or n == 0) return; + var hb: [96]u8 = undefined; + try noteRow(p, q, out, rows, std.fmt.bufPrint(&hb, " {d} director{s} skipped: permission denied", .{ n, if (n == 1) "y" else "ies" }) catch " directories skipped"); } /// `k` for a Grep: the current row's line among all the lines sent. @@ -1128,7 +1170,9 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v const line = lineOne(rp.file.?.content); const a = parse(line) orelse return; makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); - toLineOne(p, qid); + // A list to pick from, typed into; diagnostics are a jump (]d): the + // keyboard stays on the place in the text. + if (source != .diagnostics) toLineOne(p, qid) else p.active = owner_id; } fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { @@ -1141,8 +1185,10 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { var rows: std.ArrayList(locations.Row) = .empty; const owner_id = p.paneBySerial(q.owner); const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; - var feed: std.ArrayList(Places.Hit) = .empty; - defer feed.deinit(p.gpa); + // Each open file's places in the list, its tints and n/N: the owner's + // and any other pane's the rows land in. + var feeds: [pardes.MAX_PANES]std.ArrayList(Places.Hit) = @splat(.empty); + defer for (&feeds) |*f| f.deinit(p.gpa); // In order: by path, then place, as a list of places reads. var sorted: std.ArrayList([]const u8) = .empty; defer sorted.deinit(p.gpa); @@ -1174,27 +1220,28 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { } const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); const col0 = t.at.col -| 1; - try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); - // The row's text: the line in the owner when it is the owner's, - // else as the server said it. + // The row's text: the line as an open pane has it, when one shows + // the file, else as the server said it. var code: []const u8 = rest; - var col = col0; - var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; - if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { - const owner_f = &p.panes[oid].?.file.?; - if (t.at.line <= File.nlines(p.gpa, owner_f)) { - const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); - const nx = File.lineStart(p.gpa, owner_f, t.at.line); - const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; - code = owner_f.content[ls..le]; - col = @min(col0, code.len); - end = @min(@max(end, col + 1), code.len); - feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; - } - } else { - col = 0; - end = 0; - }; + var col = @min(col0, rest.len); + var end = @min(if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1, rest.len); + var shown_in: u32 = 0; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + const tf = &tp.file.?; + if (tf.output != null or !std.mem.eql(u8, tf.path, path) or t.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, t.at.line - 1); + const nx = File.lineStart(p.gpa, tf, t.at.line); + const le = if (nx > ls and tf.content[nx - 1] == '\n') nx - 1 else nx; + code = tf.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feeds[i].append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + shown_in = tp.serial; + break; + } + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1, .serial = shown_in }); try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); n += 1; } @@ -1203,12 +1250,14 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { q.total = n; q.more = false; q.current = firstHit(q); + for (p.panes, 0..) |slot, i| if (slot) |tp| { + if (feeds[i].items.len > 0) tp.places.feed(p, tp, rp.serial, feeds[i].items, null) else if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; if (owner_id) |oid| { const owner = p.panes[oid].?; // Current: the first place after where it was asked (the answer // may come after the cursor moved), shown in the owner. const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); - owner.places.feed(p, owner, rp.serial, feed.items, null); const hits = owner.places.hits.items; var next: ?usize = null; for (hits, 0..) |h, i| if (h.start > asked_at) { @@ -1261,6 +1310,13 @@ fn showCurrent(rp: *Pane) void { }; const r: i32 = @intCast(c + 1); rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + // Typed into, line 1 stays in view whatever the current row: what you + // type is never scrolled away (the live rows start just before the + // current one, so it sits under line 1). Frozen, the row is scrolled to. + if (!q.frozen) { + if (rp.scroll() != 0) rp.scrollBy(-rp.scroll()); + return; + } const off = rp.scroll(); const shown = off + @as(i32, rp.rows) - 1; if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); @@ -1296,6 +1352,7 @@ fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { const q = rp.query.?; q.current = i; const it = q.items.items[i]; + if (q.source == .grep and it.kind == .hit) q.grep_at = it.hit; const rows = rp.file.?.location_rows; if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { const tp = p.panes[tid].?; @@ -1325,6 +1382,17 @@ pub fn step(p: *Pardes, id: usize, delta: i32) void { return; } }; + // A Grep: by its lines, the window made again when the next is past it. + if (q.source == .grep and q.found.items.len > 0) { + const n = q.found.items.len; + q.grep_at = if (delta > 0) (q.grep_at + 1) % n else (q.grep_at + n - 1) % n; + const in_window = for (q.items.items) |it| { + if (it.kind == .hit and it.hit == q.grep_at) break true; + } else false; + if (!in_window) makeGrepRows(p, id, q.frozen) catch {}; + for (q.items.items, 0..) |it, i| if (it.kind == .hit and it.hit == q.grep_at) return setCurrent(p, id, i, true); + return; + } const items = q.items.items; if (items.len == 0) return; var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); @@ -1335,6 +1403,26 @@ pub fn step(p: *Pardes, id: usize, delta: i32) void { setCurrent(p, id, i, true); } +/// Nothing current (a query that matches nothing): the +Preview shows +/// nothing, rather than a file the query no longer names. +fn blankPreview(p: *Pardes, qid: usize) void { + const pid = previewOf(p, qid) orelse return; + const pane = p.panes[pid].?; + const f = &pane.file.?; + if (f.content.len == 0) return; + const dir = std.fs.path.dirname(p.panes[qid].?.file.?.path) orelse "/"; + const path = std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ dir, config.preview_buffer }) catch return; + const empty = p.gpa.alloc(u8, 0) catch { + p.gpa.free(path); + return; + }; + p.gpa.free(f.path); + f.path = path; + File.setContent(p, f, empty); + f.saved_revision = f.revision; + f.scroll = 0; +} + /// Where the current row points, shown with the keyboard left where it is: /// a place in an open pane's text selected there (its places' current), /// in view; a file an open pane shows, its line there; any other file in @@ -1399,8 +1487,11 @@ pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { return null; } -/// A +Preview made under query pane `qid`, out of its rows alone. -fn makePreview(p: *Pardes, qid: usize) ?usize { +/// A +Preview made under query pane `qid`, `rows` tall, out of `giver`'s +/// rows: the text that asked, at the key that asked; the query pane itself +/// when its source word was edited to one that previews while typing (its +/// line 1 stays where it is). +fn makePreview(p: *Pardes, qid: usize, rows: u16, giver: usize) ?usize { const rp = p.panes[qid].?; const free = p.freeSlot() orelse return null; const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; @@ -1410,10 +1501,7 @@ fn makePreview(p: *Pardes, qid: usize) ?usize { return null; }; layout.compute(p); - const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; - // Out of the group's root, the text that asked: the query pane keeps - // the rows it was typed into with (made later, for a reused pane). - if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + if (!layout.attachFrom(p, qid, free, rows, giver)) { p.removePane(free, qid) catch {}; return null; } @@ -1425,7 +1513,7 @@ fn makePreview(p: *Pardes, qid: usize) ?usize { /// file open in a pane would be shown there instead), the place centred /// and selected. Made when the pane has none and its owner has the rows. fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { - const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const id = previewOf(p, qid) orelse makePreview(p, qid, p.rects[qid].h / 2, qid) orelse return; const pane = p.panes[id].?; const f = &pane.file.?; if (!std.mem.eql(u8, f.path, path)) { @@ -1706,8 +1794,8 @@ pub fn key(p: *Pardes, id: usize, k: Key) bool { land(p, id, null); return true; } - const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); - const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + const down = hit(k, config.query_next); + const up = hit(k, config.query_prev); if (down or up) { step(p, id, if (down) 1 else -1); return true; diff --git a/src/builtins.zig b/src/builtins.zig index c8909e66..cda962de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1712,38 +1712,42 @@ const e_search_miss_grep = "Grep: text not found"; /// List the files below this pane's directory whose names hold its argument, in a +Search. pub const Find = struct { pub const takes_arg = true; + // A script's Find names what to find (bare, it is a key's prompt). pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true }; pub fn run(c: Ctx) void { + // A query pane under this pane, line 1 `Find ` and the word: bare + // (SPC f f) typed into; with a word (B2, a script) listed, the + // keyboard left where it was, a script told of a miss. const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) { - const rows = look.runSearch(c.p, c.id, pat, .find, .top, false) catch |err| return c.p.reportError(c.id, "Find", err); - if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); - return; - } - // Bare (SPC f f): the query pane, line 1 `Find `, typed into. - panes.Query.open(c.p, c.id, .find, "", true); + panes.Query.open(c.p, c.id, .find, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_find); } }; /// Find's sibling: Find matches file NAMES under this pane's directory, Grep -/// matches file CONTENTS under every pane's directory at once. +/// matches the LINES of those files, on the disk engine's worker. pub const Grep = struct { pub const takes_arg = true; pub const requires_arg = true; pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (pat.len > 0) { - const rows = look.runSearch(c.p, c.id, pat, .grep, .top, false) catch |err| return c.p.reportError(c.id, "Grep", err); - if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); - return; - } - // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. - panes.Query.open(c.p, c.id, .grep, "", true); + panes.Query.open(c.p, c.id, .grep, pat, pat.len == 0); + if (pat.len > 0) missed(c, e_search_miss_grep); } }; +/// A script's Find or Grep (a 9P write runs it to its end before it +/// answers) that found nothing fails as one: the query pane stays, its +/// count 0, and the write hears `not found`. +fn missed(c: Ctx, text: []const u8) void { + if (!c.p.fs.serving) return; + const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return; + const q = c.p.panes[qid].?.query.?; + if (q.total == 0) c.p.reportFailure(c.id, text); +} + /// Search in a query pane under this pane, line 1 the argument (`Panes`, /// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. pub const Search = struct { @@ -1898,11 +1902,10 @@ pub const Last = struct { pub const Recent = struct { pub const scope: Scope = .session; pub const takes_arg = true; - pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - // From a pane: the query pane under it, line 1 `Recent `, typed - // into; from a header, which no pane owns, the +Recent list. - if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // The query pane under the pane the keyboard is in, line 1 + // `Recent `, typed into; what follows the word narrows the files. + if (c.p.panes[c.id] == null) return c.p.reportFailure(c.id, "Recent: open a pane to search from"); panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 25c9dc5a..fff99ad2 100644 --- a/src/config.zig +++ b/src/config.zig @@ -365,6 +365,11 @@ pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; pub const search_next: []const Chord = &.{.{ .cp = 'n' }}; pub const search_prev: []const Chord = &.{.{ .cp = 'N' }}; +/// Typing on a query pane's line 1 (Query.zig): the next and the previous +/// hit current, the text following (helix's prompt walks its history with +/// these; a query has none). Tab stays the exec chord. +pub const query_next: []const Chord = &.{ .{ .cp = 'n', .ctrl = true }, .{ .cp = Key.down } }; +pub const query_prev: []const Chord = &.{ .{ .cp = 'p', .ctrl = true }, .{ .cp = Key.up } }; pub const search_selection: []const Chord = &.{.{ .cp = '*', .alt = true }}; pub const search_selection_word: []const Chord = &.{.{ .cp = '*' }}; pub const pipe_selection: []const Chord = &.{.{ .cp = '|' }}; @@ -526,8 +531,6 @@ pub const comment_tokens: []const struct { exts: []const []const u8, token: []co }; pub const search_marker = " /"; -pub const find_marker = " Find /"; -pub const grep_marker = " Grep /"; pub const rename_marker = " Rename /"; pub const symbol_marker = " WsSymbols /"; pub const save_marker = " Save "; @@ -1115,297 +1115,16 @@ pub const WalkNotes = struct { } }; const find_max_depth = 16; -const find_max_steps = 100_000; -/// One root's Find or Grep rows at most: its hits, each a path and a line. -pub const search_root_output_bytes = find_max_hits * (4096 + 320); pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; -/// A directory the walk may not open or read is passed over and counted in -/// `notes.skipped`, its siblings' hits kept: one locked directory is not -/// every search's failure. A cap the walk hit is noted too. -pub fn find(arena: std.mem.Allocator, dir: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { - var hits: [find_max_hits][]const u8 = undefined; - var hits_len: usize = 0; - if (platform_has_fs) { - pardes.turn.yield(); - defer pardes.turn.back(); - const io = std.Io.Threaded.global_single_threaded.io(); - var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer root.close(io); - var w = try root.walkSelectively(arena); - defer w.deinit(); - var steps: usize = 0; - walk: while (steps < find_max_steps and hits_len < hits.len) { - steps += 1; // an unreadable dir burns a step too, so it cannot spin - const e = (w.next(io) catch { - notes.skipped += 1; - continue; - }) orelse break; - if (std.ascii.findIgnoreCase(e.basename, pat) != null) { - hits[hits_len] = try arena.dupe(u8, e.path); - hits_len += 1; - } - if (e.kind != .directory or e.depth() >= find_max_depth) continue; - for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.enter(io, e) catch { - notes.skipped += 1; - }; - } - if (hits_len >= hits.len) notes.hits_cut = true; - if (steps >= find_max_steps) notes.walk_cut = find_max_steps; - } else { - for (sources) |s| { - if (hits_len >= hits.len) break; - if (std.ascii.findIgnoreCase(std.fs.path.basename(s.path), pat) != null) { - hits[hits_len] = s.path; - hits_len += 1; - } - } - } - std.mem.sort([]const u8, hits[0..hits_len], {}, struct { - fn lt(_: void, a: []const u8, b: []const u8) bool { - return std.mem.lessThan(u8, a, b); - } - }.lt); - var written: usize = 0; - for (hits[0..hits_len]) |h| { - if (h.len + 1 > out.len - written) break; - @memcpy(out[written..][0..h.len], h); - written += h.len; - out[written] = '\n'; - written += 1; - } - return written; -} - -const grep_max_bytes = 256 * 1024; +// Find and Grep walk on the disk engine's worker now (Stream.zig); what is +// left here is what their notes and skips were. const grep_max_files = 20_000; -const GrepResult = struct { bytes: usize, hits: usize }; - -/// `text` starts at line `first_line` + 1 of its file. -fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize, first_line: usize) GrepResult { - var result: GrepResult = .{ .bytes = 0, .hits = 0 }; - var line: usize = first_line; - var it = std.mem.splitScalar(u8, text, '\n'); - while (it.next()) |raw| { - line += 1; - if (result.hits >= budget) break; - const at = std.ascii.findIgnoreCase(raw, pat) orelse continue; - const ln = std.mem.trimEnd(u8, raw, " \t\r"); - var cut = @min(ln.len, 200); - while (cut > 0 and cut < ln.len and ln[cut] & 0xc0 == 0x80) cut -= 1; - const row = std.fmt.bufPrint(out[result.bytes..], "{s}:{d}:{d}{c}{d} {s}\n", .{ - path, line, at + 1, config.range_sep, at + pat.len, ln[0..cut], - }) catch break; - result.bytes += row.len; - result.hits += 1; - } - return result; -} - -pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, base: []const u8, pat: []const u8, out: []u8, notes: *WalkNotes) !usize { - var hits: usize = 0; - var written: usize = 0; - if (!platform_has_fs) { - for (sources) |s| { - if (hits >= find_max_hits or written == out.len) break; - const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits, 0); - hits += result.hits; - written += result.bytes; - } - return written; - } - const root_path = std.mem.trimEnd(u8, dir, "/"); - const home = std.mem.trimEnd(u8, base, "/"); - const files = try arena.alloc([]const u8, grep_max_files); - var files_len: usize = 0; - // A walk and thousands of reads: the turn goes out for all of it. - pardes.turn.yield(); - defer pardes.turn.back(); - { - const io = std.Io.Threaded.global_single_threaded.io(); - var root = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer root.close(io); - var w = try root.walkSelectively(arena); - defer w.deinit(); - var steps: usize = 0; - walk: while (steps < find_max_steps and files_len < files.len) { - steps += 1; - const e = (w.next(io) catch { - notes.skipped += 1; - continue; - }) orelse break; - if (e.kind == .directory) { - if (e.depth() >= find_max_depth) continue; - for (find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; - w.enter(io, e) catch { - notes.skipped += 1; - }; - continue; - } - if (e.kind != .file) continue; - files[files_len] = try std.fmt.allocPrint(arena, "{s}/{s}", .{ root_path, e.path }); - files_len += 1; - } - if (files_len >= files.len) notes.walk_cut = grep_max_files else if (steps >= find_max_steps) notes.walk_cut = find_max_steps; - } - std.mem.sort([]const u8, files[0..files_len], {}, struct { - fn lt(_: void, a: []const u8, b: []const u8) bool { - return std.mem.lessThan(u8, a, b); - } - }.lt); - const buf = try gpa.alloc(u8, grep_max_bytes); - defer gpa.free(buf); - for (files[0..files_len]) |path| { - if (hits >= find_max_hits or written == out.len) { - notes.hits_cut = true; - break; - } - var pathbuf: [4096]u8 = undefined; - const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; - const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); - if (fd < 0) continue; - defer _ = libc.close(fd); - // The whole file, a buffer at a time: each searched through its last - // whole line, the rest carried into the next. - const shown = lsp.rel(home, path); - var len: usize = 0; - var lines_before: usize = 0; - var first = true; - file: while (true) { - var eof = false; - while (len < buf.len) { - const n = libc.read(fd, buf[len..].ptr, buf.len - len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - break :file; - } - if (n == 0) { - eof = true; - break; - } - len += @intCast(n); - } - if (first and std.mem.indexOfScalar(u8, buf[0..@min(len, 1024)], 0) != null) break; - first = false; - // A line longer than the buffer is searched in buffer-sized parts. - const end = if (eof) len else if (std.mem.lastIndexOfScalar(u8, buf[0..len], '\n')) |nl| nl + 1 else len; - const result = grepText(shown, buf[0..end], pat, out[written..], find_max_hits - hits, lines_before); - hits += result.hits; - written += result.bytes; - if (eof or hits >= find_max_hits or written == out.len) break; - lines_before += std.mem.count(u8, buf[0..end], "\n"); - std.mem.copyForwards(u8, buf[0 .. len - end], buf[end..len]); - len -= end; - } - if (hits >= find_max_hits) notes.hits_cut = true; - } - return written; -} - -test "grep skips a file it cannot read instead of abandoning the search" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a-locked.txt", .data = "needle here\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b-open.txt", .data = "needle here\n" }); - var locked_buf: [std.fs.max_path_bytes]u8 = undefined; - const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/a-locked.txt", .{dir}, 0); - if (libc.chmod(locked, 0) != 0) return; - const probe = libc.open(locked, .{ .ACCMODE = .RDONLY }); - if (probe >= 0) { - _ = libc.close(probe); - _ = libc.chmod(locked, 0o644); - return error.SkipZigTest; - } - - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 64 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - const n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - _ = libc.chmod(locked, 0o644); // so `tmp.cleanup` can remove it - - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "b-open.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "a-locked.txt") == null); -} - -test "a directory the walk may not open is skipped and counted: Grep and Find keep every other hit" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - try tmp.dir.createDirPath(std.testing.io, "locked"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "locked/needle-in.txt", .data = "needle\n" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "needle-out.txt", .data = "needle\n" }); - var locked_buf: [std.fs.max_path_bytes]u8 = undefined; - const locked = try std.fmt.bufPrintSentinel(&locked_buf, "{s}/locked", .{dir}, 0); - if (libc.chmod(locked, 0) != 0) return; - defer _ = libc.chmod(locked, 0o755); // so `tmp.cleanup` can remove it - if (isDir(locked)) return error.SkipZigTest; // root reads it anyway - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 64 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt:1:") != null); - try std.testing.expectEqual(@as(usize, 1), notes.skipped); - notes = .{}; - n = try find(arena.allocator(), dir, "needle", out, ¬es); - try std.testing.expect(std.mem.indexOf(u8, out[0..n], "needle-out.txt") != null); - try std.testing.expectEqual(@as(usize, 1), notes.skipped); -} - -test "Grep reads a long file to its end, and says when its hits were cut" { - if (!platform_has_fs) return; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var base_buf: [std.fs.max_path_bytes]u8 = undefined; - const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - // A match past the first buffer of a long file, on its own line number. - const long = try gpa.alloc(u8, grep_max_bytes + 64); - defer gpa.free(long); - @memset(long, 'x'); - for (0..long.len / 64) |i| long[i * 64] = '\n'; - @memcpy(long[long.len - 8 ..][0..7], "needle\n"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "long.txt", .data = long }); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const out = try gpa.alloc(u8, 256 * 1024); - defer gpa.free(out); - var notes: WalkNotes = .{}; - var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - var want_buf: [64]u8 = undefined; - const want = try std.fmt.bufPrint(&want_buf, "long.txt:{d}:", .{std.mem.count(u8, long, "\n")}); - try std.testing.expect(std.mem.startsWith(u8, out[0..n], want)); - // More hits than the cap. - var many: std.ArrayList(u8) = .empty; - defer many.deinit(gpa); - for (0..find_max_hits + 10) |_| try many.appendSlice(gpa, "needle\n"); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "many.txt", .data = many.items }); - notes = .{}; - n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expect(notes.hits_cut); - var said: [256]u8 = undefined; - const lines = said[0..notes.write(&said)]; - try std.testing.expectEqualStrings("cut at 512 hits\n", lines); - try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); -} - fn isDir(path: [*:0]const u8) bool { const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }); if (fd < 0) return false; diff --git a/src/look.zig b/src/look.zig index eed3dbd9..cd8df4fc 100644 --- a/src/look.zig +++ b/src/look.zig @@ -532,7 +532,6 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow }; } -const Search = enum { text, find, grep }; const SearchStart = enum { top, cursor }; @@ -550,20 +549,13 @@ pub fn submitSearch(p: *Pardes, id: usize) void { const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return; if (std.mem.startsWith(u8, armed, config.rename_marker)) return p.lspRequest(id, .rename, armed[slash + 1 ..]); if (std.mem.startsWith(u8, armed, config.symbol_marker)) return p.lspRequest(id, .workspace_symbols, armed[slash + 1 ..]); - const kind: Search = if (std.mem.startsWith(u8, armed, config.find_marker)) - .find - else if (std.mem.startsWith(u8, armed, config.grep_marker)) - .grep - else - .text; - _ = runSearch(p, id, armed[slash + 1 ..], kind, .top, true) catch |err| return p.reportError(id, "search", err); - if (kind == .text) { - var pattern: std.ArrayList(u8) = .empty; - normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; - p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); - p.registers.last_search = '/'; - lookFirstHit(p, id); - } + // A PDF's `/` and a terminal's: a text's is its query pane (Query.zig). + _ = runSearch(p, id, armed[slash + 1 ..], .top, true) catch |err| return p.reportError(id, "search", err); + var pattern: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; + p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); + p.registers.last_search = '/'; + lookFirstHit(p, id); } fn lookFirstHit(p: *Pardes, id: usize) void { @@ -589,7 +581,7 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// of rows: past it, the rows stop and say where. pub const search_text_output_bytes = 16 << 20; -pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { +pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; // Blanks at either end are the pattern's (a look of an indented line); // a builtin's argument comes trimmed already. @@ -607,49 +599,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start var nrows: usize = 0; var anchor: ?usize = null; var notes: filesystem.WalkNotes = .{}; - if (kind == .grep) { - var roots: [MAX_PANES][]const u8 = undefined; - var nroots: usize = 0; - for (p.panes) |slot| { - const pp = slot orelse continue; - // A pane of the served tree (/virtual/, /n/<peer>/) has no - // directory on this host to walk, and one that named `/` would - // swallow every other root: passed over. - const d = filesystem.localPath(Pardes.paneDir(pp)) orelse continue; - if (filesystem.isVirtual(if (pp.file) |f| f.path else d)) continue; - var covered = false; - var k: usize = 0; - while (k < nroots) { - if (pathUnder(d, roots[k])) { - covered = true; - break; - } - if (pathUnder(roots[k], d)) { // this one swallows a root already kept - nroots -= 1; - roots[k] = roots[nroots]; - continue; - } - k += 1; - } - if (covered) continue; - roots[nroots] = d; - nroots += 1; - } - out = try @import("memory.zig").unfilled(arena, @max(1, nroots) * filesystem.search_root_output_bytes); - // A pane's directory that is not there (a scratch named into one - // not made yet, a peer's) has nothing to grep: passed over, not the - // search's failure. - for (roots[0..nroots]) |r| - out_len += filesystem.grep(arena, p.gpa, r, dir, pat, out[out_len..], ¬es) catch |err| switch (err) { - error.FileNotFound, error.NotDir, error.AccessDenied => continue, - else => return err, - }; - nrows = std.mem.count(u8, out[0..out_len], "\n"); - } else if (kind == .find) { - out = try @import("memory.zig").unfilled(arena, filesystem.search_root_output_bytes); - out_len = try filesystem.find(arena, dir, pat, out, ¬es); - nrows = std.mem.count(u8, out[0..out_len], "\n"); - } else if (pane.hasPdf()) { + if (pane.hasPdf()) { out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); if (comptime pdf_enabled) { const found = try panes.Pdf.searchRows( @@ -700,19 +650,10 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const noted = notes.write(out[out_len..]); out_len += noted; nrows += std.mem.count(u8, out[out_len - noted .. out_len], "\n"); - // A Find or Grep that finds nothing leaves its directory's +Search as - // it was: the failure says why, and the last search's rows are still - // that search's (its tag names it). + // A word looked for that is nowhere opens nothing. if (!open_empty and nrows == 0) return 0; const content = try p.gpa.dupe(u8, out[0..out_len]); - // the buffer records WHICH search filled it, pattern and all: Find and - // Grep are builtins (words you can execute), the bare `/` is a key - const from: panes.Output.Origin = switch (kind) { - .text => .search, - .find => .{ .cmd = .Find }, - .grep => .{ .cmd = .Grep }, - }; - try panes.Output.fillResults(p, id, dir, from, pat, content, anchor); + try panes.Output.fillResults(p, id, dir, .search, pat, content, anchor); return nrows; } @@ -1466,7 +1407,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; - const rows = runSearch(p, id, text, .text, .cursor, false) catch |err| { + const rows = runSearch(p, id, text, .cursor, false) catch |err| { p.reportError(id, "search", err); return; }; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 45336a1e..635e03a6 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -3017,7 +3017,7 @@ test "a builtin that needs its argument, written bare to an exec, is EINVAL as t } } -test "Grep with no hit says grep: no match and opens nothing, a missing pane directory passed over" { +test "a script's Grep and Find fill the pane's one query pane, a row a line under its file; a miss says not found and opens nothing" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); var tmp = testing.tmpDir(.{}); @@ -3028,22 +3028,26 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; _ = wr(p, Node.of(serialOf(p), .name), try std.fmt.bufPrint(&line, "{s}/a.txt\n", .{dir})); - // A hit opens its +Search, a row a line: exec reads it back. Find and - // Grep share it, a directory's one +Search, each run replacing it. + // A hit fills the pane's query pane, line 1 the command, its rows under + // the file they are in: exec reads it back. Find and Grep share it, the + // pane's one query pane, each run replacing it. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Grep bravo\n").reply.status); const grepped = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - try testing.expectEqual(@as(usize, 2), std.mem.count(u8, grepped.file.?.content, "other.txt:")); - try testing.expect(std.mem.indexOf(u8, grepped.file.?.content, "other.txt:2") != null); - try testing.expect(std.mem.indexOf(u8, grepped.file.?.content, "other.txt:3") != null); + const rows = grepped.file.?.content; + try testing.expect(std.mem.startsWith(u8, rows, "Grep bravo\n")); + try testing.expect(std.mem.indexOf(u8, rows, "\nother.txt\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "2 bravo here\n") != null); + try testing.expect(std.mem.indexOf(u8, rows, "3 three bravo\n") != null); + try testing.expectEqual(@as(usize, 2), grepped.query.?.total); try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); const found = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - try testing.expect(std.mem.indexOf(u8, found.file.?.content, "other.txt") != null); try testing.expectEqual(grepped.serial, found.serial); + try testing.expect(std.mem.indexOf(u8, found.file.?.content, "\nother.txt\n") != null); try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") == null); - // The same Find again reads back the +Search, not the pane it ran in. + // The same Find again reads back the query pane, not the pane it ran in. try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find other\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes); - // A Grep run from the +Search itself fills that one, never a second. + // A Grep run from the query pane itself fills that one, never a second. try testing.expectEqual(Status.ok, wr(p, Node.of(found.serial, .exec), "Grep bravo\n").reply.status); try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{found.serial}), rd(p, root_exec, 0, 64).bytes); var searches: usize = 0; @@ -3052,23 +3056,19 @@ test "Grep with no hit says grep: no match and opens nothing, a missing pane dir }; try testing.expectEqual(@as(usize, 1), searches); try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); - // A second pane in a directory that is not there. - const other = try th.newPane(p); - _ = wr(p, Node.of(other, .name), "/tmp/pardes-no-such-dir-zz/b.txt\n"); var count: usize = 0; for (p.panes) |slot| count += @intFromBool(slot != null); + // A miss: said to the script, the query pane's count 0, nothing opened. const missed = wr(p, Node.of(serialOf(p), .exec), "Grep zzqqnomatchzz\n"); try testing.expectEqual(E.NOENT, missed.errno()); try testing.expectEqualStrings("Grep: text not found", missed.reply.ename); + try testing.expectEqual(@as(usize, 0), found.query.?.total); const unfound = wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n"); try testing.expectEqual(E.NOENT, unfound.errno()); try testing.expectEqualStrings("Find: name not found", unfound.reply.ename); var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); - // The +Search a miss would have filled keeps the last search's rows: - // the miss is said, and its tag names what they are of. - try testing.expect(std.mem.indexOf(u8, found.file.?.content, "bravo here") != null); } test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { @@ -4911,7 +4911,7 @@ test "a Rename the server answered for this file alone, with other open files sa try testing.expect(th.logHas(p, "Rename: previewed, not applied: the server renamed in this file only, and 1 other open file(s) say the name")); } -test "Find ends with what it skipped, and a Find or Grep that finds nothing leaves the +Search as it was" { +test "Find says what it skipped under its names, and a script's Find that finds nothing is told so" { if (comptime !pardes.hosted) return; const gpa = testing.allocator; var tmp = testing.tmpDir(.{}); @@ -4928,18 +4928,18 @@ test "Find ends with what it skipped, and a Find or Grep that finds nothing leav const path = try std.fmt.bufPrint(&path_buf, "{s}/zz-needle.txt", .{dir}); const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); - try testing.expect(p.executeBuiltinLine(0, "Find needle")); - const search = p.panes[p.panes[0].?.search_pane.?].?; + // the walk's own skips are what is said (rg would pass over in silence) + p.stream.engine = .walk; + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .exec), "Find needle\n").reply.status); + const search = p.panes[pardes.panes.Query.ofOwner(p, p.panes[0].?.serial).?].?; const listed = search.file.?.content; try testing.expect(std.mem.endsWith(u8, listed, "1 directory skipped: permission denied\n")); - try testing.expect(std.mem.startsWith(u8, listed, "zz-needle.txt\n")); - // Nothing found where it looked, and nothing passed over: the miss is - // said, and the +Search keeps the last search's rows. + try testing.expect(std.mem.startsWith(u8, listed, "Find needle\nzz-needle.txt\n")); + // Nothing found: the miss is said, the query pane's count 0. _ = std.c.chmod(locked, 0o755); - const before = try gpa.dupe(u8, listed); - defer gpa.free(before); - try testing.expect(p.executeBuiltinLine(0, "Find nosuchname")); - try testing.expectEqualStrings(before, search.file.?.content); + const missed = wr(p, Node.of(serialOf(p), .exec), "Find nosuchname\n"); + try testing.expectEqual(E.NOENT, missed.errno()); + try testing.expectEqual(@as(usize, 0), search.query.?.total); try testing.expect(th.logHas(p, "Find: name not found")); } diff --git a/src/normal.zig b/src/normal.zig index ebace536..f5bdb9dc 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -757,22 +757,18 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .add_newline => |newline| return edit.addNewline(p, t, newline.direction == .forward, newline.count), .diagnostic => |diagnostic| { const fwd = diagnostic.direction == .forward; - if (!diagnostic.endpoint) { - if (panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics }) and - look.searchStep(p, p.active, if (fwd) 1 else -1)) return; - return p.lspRequest(p.active, .diagnostics, ""); - } - if (!panes.Output.resultsFrom(p, pane, .{ .query = .diagnostics })) - return p.lspRequest(p.active, .diagnostics, ""); - if (!fwd) { - pane.search_row = null; - _ = look.searchStep(p, p.active, 1); - return; - } - const rp = p.panes[pane.search_pane orelse return] orelse return; - const rf = rp.file orelse return; - pane.search_row = std.mem.count(u8, rf.content, "\n"); - _ = look.searchStep(p, p.active, -1); + // Once a Diagnostics query fed them, the diagnostics are this + // text's places: ]d and [d step them as n and N do, ]D and [D + // go to the last and the first. Until then, asked for. + const set = &pane.places; + const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid| + (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false) + else + false; + if (!fed) return p.lspRequest(p.active, .diagnostics, ""); + if (!diagnostic.endpoint) return set.step(p, pane, fwd, 1, false); + if (set.hits.items.len == 0) return; + set.goTo(pane, if (fwd) set.hits.items.len - 1 else 0, false); }, .move => |move| switch (move.motion) { .left => { diff --git a/src/tagline.zig b/src/tagline.zig index 3c8dd3e1..c057772d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -184,6 +184,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; if (pane.query) |q| return if (q.frozen) query_frozen_tail else if (q.capped) query_capped_tail else query_live_tail; + if (pane.file) |file| if (file.output) |out| if (out.from == .preview) return query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; diff --git a/src/tutor.txt b/src/tutor.txt index 083a5028..188a485d 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -101,8 +101,10 @@ 1. `Look` :20 here: the cursor goes to line 20 of this pane. 2. Drag across :/^=.*UNSAVED/ with B3 held: `Look` takes exactly what you swept, a regex here, and goes to Part 7's heading. - 3. Press /, type keys, press Enter: a +Search lists the lines with - keys and the cursor goes to the first. n and N select search matches. + 3. Press / and type keys: a +Search opens under this pane, its first + line the query; each match lights up and is listed as you type, and + Ctrl-n steps. Enter puts the cursor on it and keeps the list; n and N + step them. Esc while typing puts everything back. -> Guide: Look @@ -259,9 +261,9 @@ typed ] p, [ p step by paragraph; ] d, [ d by diagnostic ] space a blank line below; [ space above | filter every selection through the shell - / case-insensitive SUBSTRING search, one hit a line; the - regex lives on s and S - n / N next/previous search match (Helix); v adds matches + / search in a query pane under the text: a regex, any + case unless it has a capital; line 1 is the query + n / N next/previous match, round the end; v adds matches SPC j n/p `LookNext`/`LookPrev`: select locations; Enter opens Ctrl-c comment or uncomment the lines @@ -344,11 +346,11 @@ typed ; collapses first bare G does nothing; ge is the START of the last line s / S regex cursors; m i/a textobjects; m s/r/d surround - / is a case-insensitive SUBSTRING search, not a regex + / opens a query pane: line 1 the query, Enter lands SPC is the leader (SPC ? is `Help`) vs HELIX selection is LINE-first (x), v for characters; / is a - substring search; n/N repeat it in the current text. + pane: Find, Grep, Recent are its line 1's first word. vs VIM no verb+noun: the motion already selected, so wd is what dw was; Esc goes back a pane; bare G does nothing. vs BOTH a terminal is just a pane, and the session can outlive |
