diff options
Diffstat (limited to 'core')
| -rw-r--r-- | core/Names.zig | 92 | ||||
| -rw-r--r-- | core/Pick.zig | 297 | ||||
| -rw-r--r-- | core/Trail.zig | 19 | ||||
| -rw-r--r-- | core/body_layer.zig | 37 | ||||
| -rw-r--r-- | core/builtins.zig | 6 | ||||
| -rw-r--r-- | core/fs.zig | 6 | ||||
| -rw-r--r-- | core/look.zig | 28 | ||||
| -rw-r--r-- | core/lsp/Ask.zig | 47 | ||||
| -rw-r--r-- | core/ninep/ctl.zig | 4 | ||||
| -rw-r--r-- | core/normal.zig | 4 | ||||
| -rw-r--r-- | core/panes.zig | 13 | ||||
| -rw-r--r-- | core/root.zig | 1 | ||||
| -rw-r--r-- | core/syntax.zig | 39 |
13 files changed, 512 insertions, 81 deletions
diff --git a/core/Names.zig b/core/Names.zig index 47165f52..d063bd17 100644 --- a/core/Names.zig +++ b/core/Names.zig @@ -29,6 +29,10 @@ query_buf: [max_query]u8 = undefined, query_len: u8 = 0, /// Bumped whenever `hits` change: the rows are made again only then. gen: u32 = 0, +/// How many of `hits` are in order, best first: as many as a list shows +/// (`max_rows`), or as far as its cursor went (`reachTo`); the matches after +/// them are counted, in no order. +reach: u32 = max_rows, /// The query is `query_buf[0..query_len]`: what lies past it is undefined /// (0xAA in Debug, not in a release build), so no digest reads it. @@ -81,6 +85,7 @@ pub fn reset(n: *Names) void { n.pending.clearRetainingCapacity(); n.pending_at = 0; n.scored = 0; + n.reach = max_rows; n.gen +%= 1; } @@ -124,6 +129,7 @@ pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void { 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); + n.reach = max_rows; if (grew) { const pending = n.pending.items[n.pending_at..]; std.mem.copyForwards(u32, n.pending.items[0..pending.len], pending); @@ -165,19 +171,65 @@ pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { if (!empty and left == 0) 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); + // row moves as the walk goes on, it only grows at the foot. Else the + // best `reach` first: a sort of every hit was most of a first key's + // 8 ms over 50,000 paths. + if (!empty) bestFirst(n.hits.items, n.cands.items, n.reach); if (n.hits.items.len != had or n.scored != was_scored or count > 0) n.gen +%= 1; } +/// Hits sorted as far as row `rows`, for a cursor gone past the ones that +/// were (an empty query's are in the source's order already). +pub fn reachTo(n: *Names, rows: usize) void { + if (rows <= n.reach or std.mem.trim(u8, n.queryText(), " ").len == 0) return; + n.reach = @intCast(@min(rows, max_cands)); + bestFirst(n.hits.items, n.cands.items, n.reach); + n.gen +%= 1; +} + +/// Hit `a` goes before `b`: the higher score, then the shorter key, then +/// the candidate added first. +fn before(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; +} + +/// `hits`' best `k` to the front, in order, the rest after them in no +/// order: the best so far kept as a heap whose root is the worst of them, +/// then sorted. O(n log k). +fn bestFirst(hits: []Hit, cands: []const Cand, k_in: usize) void { + const k = @min(k_in, hits.len); + if (k == 0) return; + const heap = hits[0..k]; + var i = k / 2; + while (i > 0) { + i -= 1; + sink(heap, cands, i); + } + for (hits[k..]) |*h| if (before(cands, h.*, heap[0])) { + std.mem.swap(Hit, h, &heap[0]); + sink(heap, cands, 0); + }; + std.sort.pdq(Hit, heap, cands, before); +} + +/// Heap entry `at` taken down past the worse of its children while it is +/// better than that child. +fn sink(heap: []Hit, cands: []const Cand, from: usize) void { + var at = from; + while (true) { + const l = 2 * at + 1; + if (l >= heap.len) return; + const c = if (l + 1 < heap.len and before(cands, heap[l], heap[l + 1])) l + 1 else l; + if (!before(cands, heap[at], heap[c])) return; + std.mem.swap(Hit, &heap[at], &heap[c]); + at = c; + } +} + /// 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]; @@ -363,3 +415,23 @@ test "Names ranks real paths as the pick prototype did" { try std.testing.expectEqualStrings("src/gui/Post.zig", topFor("gui/po")); try std.testing.expectEqualStrings("src/Output.zig", topFor("Out")); } + +test "Names keeps its best `reach` hits first in a full sort's order, the rest after them, and sorts further as a cursor goes past them" { + const gpa = std.testing.allocator; + var n: Names = .{}; + defer n.deinit(gpa); + var buf: [64]u8 = undefined; + for (0..3000) |i| { + const path = try std.fmt.bufPrint(&buf, "dir{d}/sub{d}/file_{d}.zig", .{ i % 7, i % 13, i }); + try n.add(gpa, path, 0, path.len, baseOf(path), 0); + } + n.typed(gpa, "f1"); + while (n.busy()) n.rescore(gpa); + const all = try gpa.dupe(Hit, n.hits.items); + defer gpa.free(all); + std.sort.pdq(Hit, all, n.cands.items, before); + try std.testing.expect(all.len > max_rows); + try std.testing.expectEqualSlices(Hit, all[0..max_rows], n.hits.items[0..max_rows]); + n.reachTo(max_rows + 500); + try std.testing.expectEqualSlices(Hit, all[0 .. max_rows + 500], n.hits.items[0 .. max_rows + 500]); +} diff --git a/core/Pick.zig b/core/Pick.zig index efadc881..3bc8c858 100644 --- a/core/Pick.zig +++ b/core/Pick.zig @@ -35,6 +35,10 @@ const Stream = @import("Stream.zig"); const Trail = @import("Trail.zig"); const TagState = @import("TagState.zig"); const Band = @import("Band.zig"); +const Places = @import("Places.zig"); +const colors = @import("colors.zig"); +const Surface = @import("surface.zig").Surface; +const Cell = @import("surface.zig").Cell; const Query = panes.Query; const File = panes.File; const Output = panes.Output; @@ -48,9 +52,10 @@ const Key = pardes.Key; /// declarations, the lines holding the query in every open pane (All, its /// places in each), the jump list, rows handed over (a language server's /// answer, SPC e's places), titled by their word, the messages' history -/// (SPC h m), and the themes (SPC t t, the window wearing the one under -/// the cursor). -pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, messages, themes }; +/// (SPC h m), the themes (SPC t t, the window wearing the one under +/// the cursor), and a language server's code actions for the caret's place +/// (SPC l a, the body showing the one under the cursor as its edit). +pub const Source = enum { find, grep, recent, panes, symbols, all, jumplist, list, messages, themes, actions }; /// Each source's word in the tag and the leader keys of the builtin that /// opens it, its key cells (`␣ f Find`). @@ -65,6 +70,7 @@ const words = std.EnumArray(Source, struct { word: []const u8, keys: []const u8 .list = .{ .word = "List", .keys = "l" }, .messages = .{ .word = "Messages", .keys = "hm" }, .themes = .{ .word = "Themes", .keys = "t" }, + .actions = .{ .word = "Actions", .keys = "la" }, }); /// The pickers kept after they roll up, for their list words and Resume. @@ -94,8 +100,11 @@ names: Names = .{}, /// A Grep's lines, as the disk engine sends them (Query.take). found: std.ArrayList(Query.Found) = .empty, found_bytes: std.ArrayList(u8) = .empty, -/// A list's rows, as they were handed over (`path:line:col text`). +/// A list's rows, as they were handed over (`path:line:col text`); code +/// actions' each followed by its edit's records (lsp_client actionEdits). rows: []u8 = &.{}, +/// The revision of the asking text its actions' edits are of. +revision: u32 = 0, /// The query and the cursor as it rolled up (live, they are its view's /// field and cursor). query: Kind.Buf(256) = .{}, @@ -149,10 +158,11 @@ pub fn deinit(pk: *Pick, gpa: std.mem.Allocator) void { /// Whether a search a builtin asks for from pane `id` is a picker in the /// tag (SPEC §14.3 phase 4): in a session whose jumps walk, from the -/// keyboard or a click, never a script's (a 9P write's: the query pane, -/// whose rows it reads back, and whose `not found` it hears). +/// keyboard or a click (kbdin's and mousein's too), never a script's word +/// (a 9P exec's: the query pane, whose rows it reads back, and whose `not +/// found` it hears). pub fn asked(p: *const Pardes) bool { - return p.settings.jumps == .walk and !p.fs.serving; + return p.settings.jumps == .walk and (!p.fs.serving or p.fs.typed); } /// Picker `id`, kept or live. @@ -224,8 +234,8 @@ fn hostIn(p: *Pardes, pk: *Pick, from: usize) !void { pk.owner = asker.serial; pk.made = false; // A theme is no place: its list is the asking pane's own tag (§3.5), - // and its preview the whole window. - if (pk.source == .themes) { + // and its preview the whole window; an action's is that text's edit. + if (pk.source == .themes or pk.source == .actions) { pk.landing = asker.serial; p.view().active = from; return; @@ -302,6 +312,21 @@ fn start(p: *Pardes, pk: *Pick) void { .themes => for (pardes.colors.themes, 0..) |t, i| { pk.names.add(p.gpa, t.name, 0, t.name.len, 0, @intCast(i)) catch return; }, + // Each action by its title, its digit before it (the first nine, + // which `1`-`9` apply), the title what the query matches. + .actions => { + var lines = std.mem.splitScalar(u8, pk.rows, '\n'); + var i: u32 = 0; + while (lines.next()) |ln| { + if (ln.len == 0 or ln[0] == '@') continue; + const title = std.mem.trimStart(u8, ln[Output.location(ln).end..], " "); + var buf: [2 + 512]u8 = undefined; + const cut = title[0..@min(title.len, 512)]; + const text = if (i < 9) std.fmt.bufPrint(&buf, "{d} {s}", .{ i + 1, cut }) catch unreachable else cut; // 2 + 512 fit + pk.names.add(p.gpa, text, text.len - cut.len, cut.len, 0, i) catch return; + i += 1; + } + }, } } @@ -400,7 +425,7 @@ pub fn produceAll(p: *Pardes, tick: bool) void { for (p.picks) |slot| if (slot) |pk| if (pk.unrolled) { if (pk.names.busy()) pk.names.rescore(p.gpa); // A theme's preview in the step of the key that moved to it. - if (pk.source == .themes) pardes.colors.previewTheme(p, themeAt(p, pk)); + if (pk.source == .themes) pardes.colors.previewTheme(p, refAt(p, pk)); if (tick) preview(p, pk); }; } @@ -415,8 +440,9 @@ pub fn busy(p: *const Pardes) bool { // ---- the rows ---- -/// The theme the cursor of a themes picker is on. -fn themeAt(p: *const Pardes, pk: *const Pick) ?usize { +/// What the row under the cursor is of: a themes picker's theme, an +/// actions picker's action. +fn refAt(p: *const Pardes, pk: *const Pick) ?usize { const n = pk.names.hits.items.len; if (n == 0) return null; const at = @min(p.view().tag_state.rows.at, n - 1); @@ -458,7 +484,7 @@ const Target = union(enum) { none, place: struct { path: []const u8, at: look.Sp /// Row `i` as the band shows it and what it points at, its text in /// `arena`. -const Row = struct { text: []const u8, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" }; +const Row = struct { text: []const u8, key: u8 = 0, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none, meta: []const u8 = "" }; fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { const dir = pk.dir.slice(); @@ -530,6 +556,19 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row { .themes => if (p.custom_theme == null and cand.ref == p.settings.theme) { row.meta = "in use"; }, + // An action: its digit a key; its place the first line its edit + // changes, which the body is moved to while it is previewed. + .actions => { + row.key = @intFromBool(cand.ref < 9); + const owner = p.panes[p.paneBySerial(pk.landing) orelse return row].?; + // With the `Changes` layer's lines shown the body stays where it is. + const f = if (owner.file) |*file| file else return row; + if (f.layer.lines.len > 0 or f.revision != pk.revision) return row; + const edits = pardes.lsp.Ask.parseLspEdits(arena, (action(pk, cand.ref) orelse return row).records, null) orelse return row; + if (edits[0].start > f.content.len) return row; + const line = @import("Places.zig").lineOf(try File.lineIndex(p.gpa, f), edits[0].start); + row.target = .{ .place = .{ .path = f.path, .at = .{ .line = line + 1 } } }; + }, .recent, .jumplist, .list, .grep, .all => { const t = look.parsePathLine(text); row.pre = @intCast(t.end); @@ -590,10 +629,10 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { try text.print(arena, " {d}/{d}", .{ if (n == 0) 0 else s.rows.at + 1, n }); if (pk.marks.items.len > 0) try text.print(arena, " •{d}", .{pk.marks.items.len}); if (pk.names.busy() or p.stream.busyFor(pk.id)) try text.appendSlice(arena, " ⋯"); - // Themes have no acts and no other sources: no second row. - if (pk.source == .themes) { + // Themes and actions have no acts and no other sources: no second row. + if (pk.source == .themes or pk.source == .actions) { const hint: u32 = @intCast(text.items.len); - try text.appendSlice(arena, " ⏎ wear it · esc"); + try text.appendSlice(arena, if (pk.source == .themes) " ⏎ wear it · esc" else " ⏎ or 1-9 apply it · esc"); try spans.append(arena, .{ .lo = hint, .hi = @intCast(text.items.len), .style = .dim }); for (cells[0..ncells]) |c| try spans.append(arena, .{ .lo = c[0], .hi = c[1], .style = .key }); return .{ .text = text.items, .spans = spans.items, .cells = @intCast(ncells), .caret = caret }; @@ -619,7 +658,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head { const sources: u32 = @intCast(text.items.len); try text.appendSlice(arena, "|"); var first = false; - inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .messages and src != .themes) { + inline for (comptime std.enums.values(Source)) |src| if (src != .list and src != .messages and src != .themes and src != .actions) { if (src != pk.source) { if (!first) try text.append(arena, ' '); first = false; @@ -672,7 +711,7 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { const rows = try arena.alloc(Band.Row, w.hi - w.lo); for (rows, w.lo..) |*row, i| { const r = try rowAt(p, pk, arena, i); - row.* = .{ .text = r.text, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i), .meta = r.meta }; + row.* = .{ .text = r.text, .key = r.key, .on = i == s.rows.at, .mark = marked(pk, idOf(pk, i)) != null, .dim = r.dim, .pre = r.pre, .faint = r.faint, .marks = r.marks, .index = @intCast(i), .meta = r.meta }; } out[0] = .{ .rows = rows }; return out; @@ -685,7 +724,9 @@ pub fn steps(p: *Pardes, arena: std.mem.Allocator) ![]Band.Step { /// (UX D7: drawn on the hit ground, body_layer.zig); null else. pub fn landingLine(p: *Pardes, arena: std.mem.Allocator, pane: *const Pane) ?usize { const pk = live(p) orelse return null; - if (!pk.previews or pk.landing != pane.serial or pk.source == .themes) return null; + // A theme or an action lands nowhere: the window wearing it, its + // edit on the Changes grounds are their previews. + if (!pk.previews or pk.landing != pane.serial or pk.source == .themes or pk.source == .actions) return null; const s = &p.view().tag_state; if (pk.shown != s.rows.at or count(p, pk) == 0) return null; const row = rowAt(p, pk, arena, s.rows.at) catch return null; @@ -705,7 +746,7 @@ pub fn landingLine(p: *Pardes, arena: std.mem.Allocator, pane: *const Pane) ?usi /// previewing. pub fn sentence(p: *const Pardes, w: *std.Io.Writer) ?[2]usize { const pk = live(p) orelse return null; - if (!pk.previews or pk.source == .themes) return null; + if (!pk.previews or pk.source == .themes or pk.source == .actions) return null; if (pk.landing == pk.owner) { w.writeAll("⏎ lands here") catch return null; } else { @@ -869,6 +910,128 @@ pub fn deinitAll(p: *Pardes) void { }; } +// ---- code actions ---- + +/// Action `index` of a code actions picker's rows: its title and its edit's +/// records (the `@put` lines after its row, `@elsewhere` for an edit that +/// reaches other files, none for a command's); null past the last. +fn action(pk: *const Pick, index: usize) ?struct { title: []const u8, records: []const u8 } { + var lines = std.mem.splitScalar(u8, pk.rows, '\n'); + var n: usize = 0; + while (lines.next()) |ln| { + if (ln.len == 0 or ln[0] == '@') continue; + if (n < index) { + n += 1; + continue; + } + const from = lines.index orelse pk.rows.len; + var to = from; + while (lines.peek()) |next| { + if (next.len == 0 or next[0] != '@') break; + _ = lines.next(); + to = lines.index orelse pk.rows.len; + } + return .{ .title = std.mem.trimStart(u8, ln[Output.location(ln).end..], " "), .records = pk.rows[from..to] }; + } + return null; +} + +/// Action `index` of the live actions picker applied to the text it was +/// asked of as one undo step, the tag put to rest first (its caret back +/// where it was, then moved with the edit); one with no edit here (a +/// command's, or one reaching other files) said and not applied. +fn apply(p: *Pardes, pk: *Pick, index: usize) void { + const act = action(pk, index) orelse return; + const id = p.paneBySerial(pk.landing) orelse return TagState.toRest(p); + TagState.toRest(p); + var said: Kind.Buf(256) = .{}; + if (std.mem.eql(u8, act.records, "@elsewhere\n")) return p.reportFailure(id, said.print("Actions: {s}: its edit reaches other files, not applied", .{act.title})); + if (act.records.len == 0) return p.reportFailure(id, said.print("Actions: {s}: no edit to apply", .{act.title})); + if (!pardes.lsp.Ask.applyAction(p, p.panes[id].?, pk.revision, act.records)) return p.reportFailure(id, said.print("Actions: {s}: not applied, the text is not what it was asked of", .{act.title})); + p.setMessage(.at(id), said.print("Actions: {s}", .{act.title})); +} + +/// The live code actions picker's preview in its body (SPEC §5.1, the +/// coordinator's R3): the edit of the action under the cursor, the lines it +/// changes on the deleted ground and what they become after them as ghost +/// rows on the added ground, the rows below pushed down and the last off +/// the view. Drawn, never written; the rows shown alone. +pub fn ghosts(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: pardes.Rect, body_h: u16) !void { + const pk = live(p) orelse return; + if (pk.source != .actions or !pk.previews or pk.landing != pane.serial) return; + const f = if (pane.file) |*file| file else return; + if (f.revision != pk.revision) return; + const records = (action(pk, refAt(p, pk) orelse return) orelse return).records; + const edits = pardes.lsp.Ask.parseLspEdits(arena, records, null) orelse return; + const text = f.content; + const index = try File.lineIndex(p.gpa, f); + // The edits by the lines they touch: each run of them its old lines + // [lo, hi) and their new text, which goes before line hi. + const Group = struct { lo: usize, hi: usize, new: []const u8 }; + var groups: std.ArrayList(Group) = .empty; + var k: usize = 0; + while (k < edits.len) { + const begin = File.bufferOffset(f, edits[k].start, false); + if (begin > text.len) return; + const lo = Places.lineOf(index, begin); + var new: std.ArrayList(u8) = .empty; + try new.appendSlice(arena, text[index[lo]..begin]); + var hi = lo; + var at = begin; + while (k < edits.len) : (k += 1) { + const from = File.bufferOffset(f, edits[k].start, false); + const to = File.bufferOffset(f, edits[k].end, edits[k].end > edits[k].start); + if (from < at or to < from or to > text.len) return; + if (from > begin and Places.lineOf(index, from) >= hi) break; + try new.appendSlice(arena, text[at..from]); + try new.appendSlice(arena, edits[k].text); + at = to; + const line = Places.lineOf(index, to); + // Up to a line's start, from one or past its own text: that + // line is not changed. + hi = if (to == index[line] and (to > begin or begin == index[lo])) line else line + 1; + } + try new.appendSlice(arena, text[at..if (hi < index.len) index[hi] else text.len]); + try groups.append(arena, .{ .lo = lo, .hi = hi, .new = new.items }); + } + const tab = p.settings.tab; + const y0 = p.bodyTop(pane, r); + const rows: usize = @min(body_h, s.rows -| y0); + const first: usize = pane.context_rows; + if (rows <= first) return; + const w: usize = s.cols; + const old = try arena.dupe(Cell, s.cells[(y0 + first) * w .. (y0 + rows) * w]); + const grounds = colors.Grounds.of(p.theme()); + const ink = p.theme().fg orelse p.theme().tag_fg; + const x0 = r.x + config.GUTTER + File.gutterWidth(pane); + const width = r.w -| (x0 - r.x); + var out: usize = first; + var g: usize = 0; + var vr: usize = first; + while (vr < rows and out < rows) : (vr += 1) { + const shown = pane.wrapAt(tab, @intCast(vr)).line; + const line: usize = if (shown < 0) index.len else @intCast(shown); + if (vr == first or pane.wrapAt(tab, @intCast(vr - 1)).line != shown) { + while (g < groups.items.len and groups.items[g].hi < line) g += 1; + while (g < groups.items.len and groups.items[g].hi == line) : (g += 1) { + var news = std.mem.splitScalar(u8, std.mem.trimEnd(u8, groups.items[g].new, "\n"), '\n'); + if (groups.items[g].new.len > 0) while (news.next()) |l| { + if (out >= rows) break; + const y: u16 = @intCast(y0 + out); + s.fill(0, y, @intCast(s.cols), 1, .{}); + s.fill(x0, y, width, 1, .{ .bg = .{ .rgb = grounds.add.row } }); + _ = s.print(x0, y, width, l, .{ .fg = .{ .rgb = ink }, .bg = .{ .rgb = grounds.add.row } }); + out += 1; + }; + } + } + if (out >= rows) break; + @memcpy(s.cells[(y0 + out) * w ..][0..w], old[(vr - first) * w ..][0..w]); + if (g < groups.items.len and line >= groups.items[g].lo and line < groups.items[g].hi) s.tint(x0, @intCast(y0 + out), width, grounds.del.row, null); + out += 1; + } +} + // ---- keys ---- /// A key in the live picker (keys.zig tagStateKey, SPEC §5.4). Esc is @@ -886,15 +1049,22 @@ pub fn key(p: *Pardes, k: Key) void { return; } if (pk.spine == .acts) return actKey(p, pk, k); - // Themes: Enter wears the one under the cursor; the rows and the field. - if (pk.source == .themes) { - if (plain and k.cp == Key.enter) { - const at = themeAt(p, pk) orelse return; + // Themes: Enter wears the one under the cursor; actions: Enter, or an + // action's digit with the field empty, applies it; the rows and the + // field. + if (pk.source == .themes or pk.source == .actions) { + if (plain and k.cp == Key.enter and pk.source == .themes) { + const at = refAt(p, pk) orelse return; TagState.toRest(p); pardes.colors.setThemeIndex(p, at); return; } - if (s.rows.key(k, n)) return; + if (plain and k.cp == Key.enter) return apply(p, pk, refAt(p, pk) orelse return); + if (pk.source == .actions and plain and s.field.len == 0 and k.cp >= '1' and k.cp <= '9') return apply(p, pk, k.cp - '1'); + if (s.rows.key(k, n)) { + pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown); + return; + } if (s.field.key(k)) filter(p, pk); return; } @@ -936,7 +1106,11 @@ pub fn key(p: *Pardes, k: Key) void { return; } if (plain and k.cp == Key.backspace and s.field.len == 0) return back(p, pk); - if (s.rows.key(k, n)) return; + // A cursor gone past the rows sorted sorts as far (Names.reach). + if (s.rows.key(k, n)) { + if (fuzzy(pk)) pk.names.reachTo(@as(usize, s.rows.at) + Band.Cursor.shown); + return; + } if (s.field.key(k)) filter(p, pk); } @@ -1092,6 +1266,7 @@ fn keep(p: *Pardes, pk: *Pick) void { out.writer.print("{s} ", .{pk.word.slice()}) catch return; for (pk.refined[0..pk.nrefined]) |r| out.writer.print("{s} | ", .{r.query.slice()}) catch return; out.writer.print("{s}\n", .{s.field.text()}) catch return; + if (fuzzy(pk)) pk.names.reachTo(Query.max_rows); var kept: usize = 0; for (0..count(p, pk)) |i| { if (kept == Query.max_rows) break; @@ -1973,6 +2148,76 @@ test "n and N walk the newest list or search word, or the one Looked at (SPEC § try std.testing.expect(pane.places.current != null and !std.meta.eql(was, pane.places.current)); } +test "code actions: a picker in the asking pane's tag, the one under the cursor its edit in the body (the lines it changes on the deleted ground, what they become after them), Enter or its digit applies it as one undo step, a command's said" { + const Key_ = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + p.settings.jumps = .walk; + const pane = try p.setTestFile("one\ntwo add\nthree\n"); + const id = p.view().active; + // `add` is bytes 8..11. + const rows = "x:1:1 extract\nx:1:1 add a line\n@put 0 0 //%20top%0A\nx:1:1 rename add to sum\n@put 8 11 sum\n"; + open(p, id, .actions, "", "", rows); + live(p).?.revision = pane.file.?.revision; + const s = &p.view().tag_state; + try std.testing.expectEqual(Source.actions, live(p).?.source); + try std.testing.expectEqual(pane.serial, s.host); + try std.testing.expectEqual(@as(usize, 3), count(p, live(p).?)); + // The rename: `two add` on the deleted ground, `two sum` after it. + p.update(.{ .key = .{ .cp = Key_.down } }); + p.update(.{ .key = .{ .cp = Key_.down } }); + settle(p); + p.sync(); + var shot = try p.render(frame.allocator()); + const r = p.view().rects[id]; + const x = r.x + config.GUTTER + File.gutterWidth(pane); + const y = p.bodyTop(pane, r); + const grounds = colors.Grounds.of(p.theme()); + for ([_][]const u8{ "o", "t", "t", "t" }, [_][]const u8{ "n", "w", "w", "h" }, 0..) |c0, c1, row| { + try std.testing.expectEqualStrings(c0, shot.at(x, y + @as(u16, @intCast(row))).grapheme()); + try std.testing.expectEqualStrings(c1, shot.at(x + 1, y + @as(u16, @intCast(row))).grapheme()); + } + try std.testing.expectEqualStrings("a", shot.at(x + 4, y + 1).grapheme()); + try std.testing.expectEqualStrings("s", shot.at(x + 4, y + 2).grapheme()); + try std.testing.expectEqual(pardes.Color{ .rgb = grounds.del.row }, shot.at(x, y + 1).style.bg); + try std.testing.expectEqual(pardes.Color{ .rgb = grounds.add.row }, shot.at(x, y + 2).style.bg); + try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content); + // An action lands nowhere: no landing line, no `▸` before the line it + // changes, no sentence of where Enter lands (UX D7's are a jump's; an + // action's preview is its edit on the Changes grounds). + try std.testing.expect(landingLine(p, frame.allocator(), pane) == null); + try std.testing.expect(!std.mem.eql(u8, "▸", shot.at(x - 1, y + 1).grapheme())); + var notice: [pardes.Messages.notice_row_cap]u8 = undefined; + try std.testing.expect(!pardes.Messages.noticeRow(p, 100, ¬ice).quiet_left); + // Up: the line put in at the top, before line 1, nothing deleted. + p.update(.{ .key = .{ .cp = Key_.up } }); + settle(p); + p.sync(); + frame.deinit(); + frame = std.heap.ArenaAllocator.init(std.testing.allocator); + shot = try p.render(frame.allocator()); + try std.testing.expectEqualStrings("/", shot.at(x, y).grapheme()); + try std.testing.expectEqual(pardes.Color{ .rgb = grounds.add.row }, shot.at(x, y).style.bg); + try std.testing.expectEqualStrings("o", shot.at(x, y + 1).grapheme()); + try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = grounds.del.row }, shot.at(x, y + 1).style.bg)); + try std.testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.chromeTheme().roles.hit }, shot.at(x, y + 1).style.bg)); + // `3`: the rename applied, the tag at rest; one undo takes it back. + p.update(.{ .key = .{ .cp = '3', .text = "3" } }); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expectEqualStrings("one\ntwo sum\nthree\n", pane.file.?.content); + p.update(.{ .key = .{ .cp = 'u', .text = "u" } }); + try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content); + // Enter on a command's: said, nothing changed. + open(p, id, .actions, "", "", rows); + live(p).?.revision = pane.file.?.revision; + p.update(.{ .key = .{ .cp = Key_.enter } }); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expectEqualStrings("one\ntwo add\nthree\n", pane.file.?.content); + try std.testing.expectEqualStrings("Actions: extract: no edit to apply", p.messages.saidBy(pane)); +} + test "the themes picker marks the theme in use: `in use` at its row's right end in the dim ink, the cursor on it when it opens, the mark staying on it while the window wears another (POLISH 12, UX A15)" { const Key_ = pardes.Key; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); diff --git a/core/Trail.zig b/core/Trail.zig index f3ea542a..1cd14091 100644 --- a/core/Trail.zig +++ b/core/Trail.zig @@ -192,8 +192,11 @@ pub fn replaceStep(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { } /// Pane `id` showing `path` at `at`, the keyboard on it: its caret moved -/// in the file it shows, or a new pane on `path` in its place, its walk -/// with it. A line past the new file's end is a miss that changes nothing. +/// in the file it shows, or `path` opened in its place as the same pane, as +/// acme's Get keeps a window's id: its walk, its serial (`@pN`, a script's +/// `/pane/N`), the 9P state its scripts hold and its /log record (a rename), +/// the file it left closed as any (Recent keeps its place). A line past the +/// new file's end is a miss that changes nothing. fn show(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { const pane = p.panes[id].?; if (pane.file) |f| if (std.mem.eql(u8, f.path, path)) { @@ -211,11 +214,23 @@ fn show(p: *Pardes, id: usize, path: []const u8, at: Spot) !usize { } if (at.line > panes.File.nlines(p.gpa, &nt.file.?)) return error.LineMissing; nt.trail = pane.trail; + // What jj answered for the file it leaves goes with that file; its + // text a revision on from the one it leaves, so nothing a worker was + // asked of that text (a parse, a paint, both by serial and revision) + // lands on this one. + @import("jj.zig").forget(p, pane.serial); + nt.serial = pane.serial; + nt.file.?.revision = if (pane.file) |f| f.revision +% 1 else 0; + nt.file.?.saved_revision = nt.file.?.revision; + // Its 9P state: the one never announced leaves with no record. + std.mem.swap(@TypeOf(pane.fs), &nt.fs, &pane.fs); // Before the layout gives its place away: its file is told closed // while it is still in its slot. try panes.deinitPane(p, pane); layout.replacePane(p, id, free); p.panes[id] = null; + pardes.ctlfs.events.noteLog(p, .rename, nt); + if (pardes.Pardes.onDisk(nt)) p.recent.opened(p.recentGpa(), path); lift(p, free); look.focusPaneLine(p, free, at, .keep); // Its line half the body's rows down, as a look's new pane has it. diff --git a/core/body_layer.zig b/core/body_layer.zig index 7bff3c31..0107b3e0 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -561,6 +561,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // A pipe prompt's live run, as ghost lines over what is painted // (Prompt.zig). if (pane.file != null) try pardes.Prompt.ghosts(p, s, arena, pane, r, body_h); + // A code action's edit, previewed (Pick.zig). + if (pane.file != null) try pardes.Pick.ghosts(p, s, arena, pane, r, body_h); if (rail) |bar| if (bar.rect.h > 0) { // The rail covers the notice bands too: nothing else paints those // two gutter columns, so a gap there keeps the frame-wide border @@ -939,21 +941,34 @@ fn targetLine(p: *Pardes, pane: *Pane, f: *panes.File.State, role: modal.Normal. if (forward) return if (a < hits.len) lineOf(f, hits[a].start) else null; return if (a > 0) lineOf(f, hits[a - 1].start) else null; }, - inline .goto_function, .goto_comment, .goto_test => |r| { - // The tree as the motion reads it, made once a revision; with - // the Changes layer's lines in the buffer its offsets are not the - // buffer's: not painted then. - if (f.layer.lines.len > 0) return null; - const tree = normal.fileTree(p, f) orelse return null; - const object = @field(modal.Normal.Object, @tagName(r)["goto_".len..]); - const at = lineStart(f, caret) + @as(usize, @intCast(@max(0, pane.body.cur_col))); - const span = @import("syntax.zig").objectNext(f.path, tree, f.content, object, forward, @min(at, f.content.len), .{ lineStart(f, lo), lineStart(f, hi + 1) }) orelse return null; - return lineOf(f, span.from); - }, + // With the Changes layer's lines in the buffer the tree's offsets + // are not the buffer's: not painted then. + .goto_function => return if (f.layer.lines.len > 0) null else treeTargets(p, pane, f, forward, lo, hi)[0], + .goto_comment => return if (f.layer.lines.len > 0) null else treeTargets(p, pane, f, forward, lo, hi)[1], + .goto_test => return if (f.layer.lines.len > 0) null else treeTargets(p, pane, f, forward, lo, hi)[2], else => return null, } } +/// The lines `]f`, `]c` and `]T` (or `[`'s) go to from the caret, in lines +/// `lo` to `hi` (the rows shown): one pass of the grammar's query over the +/// tree the motions read (made once a revision), kept on the pane while +/// its text, its caret and those lines stay (`Pane.targets`), so a frame +/// that paints them again asks nothing. +fn treeTargets(p: *Pardes, pane: *Pane, f: *panes.File.State, forward: bool, lo: usize, hi: usize) [3]?usize { + const at = lineStart(f, @intCast(@max(0, pane.body.cur_row))) + @as(usize, @intCast(@max(0, pane.body.cur_col))); + const key: panes.TargetsKey = .{ .revision = f.revision, .at = at, .lo = lo, .hi = hi, .forward = forward }; + if (pane.targets.key) |was| if (std.meta.eql(was, key)) return pane.targets.lines; + var lines: [3]?usize = @splat(null); + if (normal.fileTree(p, f)) |tree| { + var spans: [3]?@import("syntax.zig").Span = undefined; + @import("syntax.zig").objectNext(f.path, tree, f.content, &.{ .function, .comment, .@"test" }, forward, @min(at, f.content.len), .{ lineStart(f, lo), lineStart(f, hi + 1) }, &spans); + for (spans, &lines) |span, *line| line.* = if (span) |s| lineOf(f, s.from) else null; + } + pane.targets = .{ .key = key, .lines = lines }; + return lines; +} + fn blank(pane: *const Pane, line: usize) bool { return std.mem.trim(u8, File.sourceLine(pane, @intCast(line)), " \t\r").len == 0; } diff --git a/core/builtins.zig b/core/builtins.zig index 32af63f7..33f5824f 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -2188,7 +2188,11 @@ pub const Hover = struct { } }; -/// List the language server's code actions for the cursor, in a +Lsp. +/// List the language server's code actions for the cursor, to apply one. +/// +/// Typed where jumps walk, they are a picker in the pane's tag, the one +/// under the cursor shown as its edit, applied by Enter or its digit; else +/// a +Lsp lists them. pub const CodeAction = struct { pub fn run(c: Ctx) void { c.p.lspRequest(c.id, .code_action, ""); diff --git a/core/fs.zig b/core/fs.zig index 6b43ba67..594c89cf 100644 --- a/core/fs.zig +++ b/core/fs.zig @@ -868,7 +868,7 @@ pub const Namespace = struct { .authority = .{ "socket_path", "tcp_address", "mounts", "node_name", "os_paths", "out", "listeners", "origin", "no_prompt", "session_write", "unlogged", "capturing", - "serving", "refused", "failure", "failure_len", "no_pane_slot", "no_pane_slot_len", + "serving", "typed", "refused", "failure", "failure_len", "no_pane_slot", "no_pane_slot_len", "said", "said_len", "said_at", "late_failure", "late_failure_len", "lsp_answer_at", "edit_started", "edit_hold", "edit_said", "lsp_result", "write_room", "write_waits", "log_full_hash", "pages", "closed_lines", "ran_at", "refilled", @@ -910,6 +910,10 @@ pub const Namespace = struct { /// A 9P request is being served (Pardes.serveFs): a prompt it opens is /// a question for the log (`ask`), answered with `answer`. serving: bool = false, + /// The request is keys or a mouse written to `kbdin` or `mousein`: + /// the user's own, so a builtin they reach routes as typed + /// (Pick.asked), though their write is served as any other. + typed: bool = false, refused: bool = false, failure: [256]u8 = undefined, failure_len: u16 = 0, diff --git a/core/look.zig b/core/look.zig index b3354a5c..f9dcfbc3 100644 --- a/core/look.zig +++ b/core/look.zig @@ -1611,6 +1611,9 @@ fn lookOpenFailed(p: *Pardes, id: usize, path: []const u8, err: anyerror) void { pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const v = p.view(); const pane = p.panes[id] orelse return; + // A question's answer word on the pane it waits on, Looked at (a click, + // B3 on `Reload` in its tag): answered, as Exec answers it. + if (pardes.Messages.answerWord(p, id, operand_raw)) return; // `~/x`, `~/x:12`, `~/x:/re/`: home, before anything reads the text. // Anything else as written: a look of ` return x` is of those blanks // too (the path, address and command readings below trim for @@ -2962,3 +2965,28 @@ test "Plumb: a commit hash looked at in a git work tree is git show's, paged; ou }; try std.testing.expect(paged); } + +test "a Look at a question's answer word in its pane answers it, as an Exec does: B3 on Reload reads the file again" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20 }); + defer p.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "c.zig", .data = "one\n" }); + var dir: [4096]u8 = undefined; + const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/c.zig", .{dir[0..try tmp.dir.realPath(std.testing.io, &dir)]}); + defer std.testing.allocator.free(path); + const pane = try p.setTestFile("one\n"); + const id = p.view().active; + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + pane.file.?.saved_hash = panes.File.fileHash(&pane.file.?); + for ([_]u21{ 'G', 'o', 't', 'w', 'o', Key.escape }) |cp| p.update(.{ .key = .{ .cp = cp } }); + const disk = "zero\none\n"; + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "c.zig", .data = disk }); + p.update(.{ .file_changed = .{ .pane = .at(id), .bytes = disk } }); + try std.testing.expect(p.messages.waiting(pane) != null); + lookAt(p, id, "Reload"); + while (p.nextEffect()) |_| {} + try std.testing.expect(p.messages.waiting(pane) == null); + try std.testing.expectEqualStrings(disk, p.panes[id].?.file.?.content); +} diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index bb1eccb6..f10ddf26 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -38,9 +38,10 @@ wait: ?struct { arg: Effect.Buf(128), row: i32 = 0, col: i32 = 0, - /// A hover asked from the keyboard where jumps walk (Pick.asked, when - /// asked: a 9P script's answer comes after its write): drawn as ghost - /// lines, no +Hover pane. + /// A hover or code actions asked from the keyboard where jumps walk + /// (Pick.asked, when asked: a 9P script's answer comes after its write): + /// a hover drawn as ghost lines, no +Hover pane; the actions a picker + /// in the pane's tag, no +Lsp. ghost: bool = false, } = null, /// A hover asked from the keyboard (where the walk is on), drawn as ghost @@ -125,7 +126,7 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) .arg = .from(arg), .row = pane.body.cur_row, .col = pane.body.cur_col, - .ghost = kind == .hover and pardes.Pick.asked(p), + .ghost = (kind == .hover or kind == .code_action) and pardes.Pick.asked(p), }; p.emit(.{ .lsp = .{ .id = p.lsp_ask.seq, @@ -136,11 +137,12 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) } }); } -const LspEdit = struct { start: usize, end: usize, text: []const u8 }; +pub const LspEdit = struct { start: usize, end: usize, text: []const u8 }; -fn parseLspEdits(p: *Pardes, bytes: []const u8, fallback: ?[]const u8) ?[]LspEdit { +/// The client's edit records (`@put`, or `@edit` with `fallback`'s text), +/// in `a`; null for anything else or a malformed one. +pub fn parseLspEdits(a: std.mem.Allocator, bytes: []const u8, fallback: ?[]const u8) ?[]LspEdit { if (bytes.len == 0 or bytes[bytes.len - 1] != '\n') return null; - const a = p.scratch.allocator(); const edits = a.alloc(LspEdit, std.mem.count(u8, bytes, "\n")) catch return null; var lines = std.mem.splitScalar(u8, bytes, '\n'); var n: usize = 0; @@ -205,6 +207,14 @@ fn mapLspEditOffset(edits: []const LspEdit, old: usize) usize { return new_at + (old - old_at); } +/// A code action's edit records (Pick.zig's actions) made in pane `pane`, +/// whose text they are of at `revision`: one undo step; false when they +/// are not (malformed, of another revision, changing nothing). +pub fn applyAction(p: *Pardes, pane: *Pane, revision: u32, records: []const u8) bool { + const edits = parseLspEdits(p.scratch.allocator(), records, null) orelse return false; + return applyLspEdits(p, pane, revision, edits); +} + /// The server's edits, of the file's text (its offsets; the `Changes` /// layer's lines are none of it), made as the file's new text (File.load). fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) bool { @@ -357,7 +367,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { } if (w.kind == .rename or w.kind == .format) { const fallback: ?[]const u8 = if (w.kind == .rename) w.arg.slice() else null; - if (parseLspEdits(p, rows, fallback)) |edits| { + if (parseLspEdits(p.scratch.allocator(), rows, fallback)) |edits| { if (applyLspEdits(p, pane, w.revision, edits)) { var buf: pardes.Kind.Buf(64) = .{}; const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted"; @@ -397,8 +407,25 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { p.lsp_ask.hover = .{ .serial = pane.serial, .row = w.row, .revision = w.revision, .text = .from(rows[0..cut]) }; return; } + // Code actions asked from the keyboard: a picker of them in the pane's + // own tag, each previewed as its edit and applied by Enter or its digit. + if (w.kind == .code_action and w.ghost) { + pardes.Pick.open(p, asked, .actions, "", "", rows); + if (pardes.Pick.live(p)) |pk| pk.revision = w.revision; + return; + } + // Anyone else's: their titles alone, in a +Lsp. + const listed_rows = if (w.kind == .code_action) titles: { + var kept: std.ArrayList(u8) = .empty; + var lines = std.mem.splitScalar(u8, rows, '\n'); + while (lines.next()) |ln| if (ln.len > 0 and ln[0] != '@') { + kept.appendSlice(p.scratch.allocator(), ln) catch |err| return p.reportError(w.pane, lspWord(w.kind), err); + kept.append(p.scratch.allocator(), '\n') catch |err| return p.reportError(w.pane, lspWord(w.kind), err); + }; + break :titles kept.items; + } else rows; const from: panes.Output.Origin = .{ .query = w.kind }; - const nrows = std.mem.count(u8, rows, "\n"); + const nrows = std.mem.count(u8, listed_rows, "\n"); if ((panes.Output.traits(from).jumps or w.kind == .diagnostics) and nrows == 1) { const ln = std.mem.trimEnd(u8, rows, "\n"); const place = ln[0..panes.Output.location(ln).end]; @@ -452,7 +479,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { return; }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - const content = p.gpa.dupe(u8, rows) catch |err| return p.reportError(w.pane, lspWord(w.kind), err); + const content = p.gpa.dupe(u8, listed_rows) catch |err| return p.reportError(w.pane, lspWord(w.kind), err); const serial_before = p.next_serial; p.fs.refilled = null; panes.Output.fillResults(p, asked, dir, from, w.arg.slice(), content, null) catch |err| { diff --git a/core/ninep/ctl.zig b/core/ninep/ctl.zig index 637999c2..2411b20f 100644 --- a/core/ninep/ctl.zig +++ b/core/ninep/ctl.zig @@ -890,6 +890,8 @@ const e_no_pane = "no such pane"; /// or Ctrl to the key after them. pub fn writeKbdin(p: *Pardes, req: Req) Reply { const view = std.unicode.Utf8View.init(req.data) catch return tree.failText(req.tag, E.INVAL, "invalid UTF-8"); + p.fs.typed = true; + defer p.fs.typed = false; var it = view.iterator(); var mods: pardes.Key = .{ .cp = 0 }; while (it.nextCodepointSlice()) |rune| { @@ -944,6 +946,8 @@ fn kbdKey(rune: []const u8) pardes.Key { /// changed since the last line is pressed or released there, in that order /// of buttons; a move with one held drags, with none moves. pub fn writeMousein(p: *Pardes, req: Req) Reply { + p.fs.typed = true; + defer p.fs.typed = false; var lines = std.mem.tokenizeScalar(u8, req.data, '\n'); while (lines.next()) |line| { var words = std.mem.tokenizeAny(u8, line, " \t\r"); diff --git a/core/normal.zig b/core/normal.zig index 2579fab6..3aad765d 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -260,7 +260,9 @@ fn objectJump(e: Editor, t: *Text, text: []const u8, range: modal.Selection, obj const tree = nodeTree(e, t, text) orelse return; var last = range; for (0..count) |_| { - const s = syntax.objectNext(tree.path, tree.root, tree.text, object, forward, tree.in(modal.selectionCursor(text, last)), null) orelse break; + var found: [1]?syntax.Span = undefined; + syntax.objectNext(tree.path, tree.root, tree.text, &.{object}, forward, tree.in(modal.selectionCursor(text, last)), null, &found); + const s = found[0] orelse break; const next: modal.Selection = .{ .anchor = tree.out(s.from, false), .head = tree.out(s.to, s.to > s.from) }; if (std.meta.eql(next, last)) break; last = next; diff --git a/core/panes.zig b/core/panes.zig index e4ed3e9d..c984a73e 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -26,13 +26,17 @@ const effect_path_cap = pardes.effect_path_cap; /// Files use row zero; terminal overlays may begin anywhere in scrollback. pub const EditText = struct { text: []u8, row0: i32 }; +/// What a pane's `]` and `[` tree targets were found for (Pane.targets): +/// its text's revision, the caret's byte, the lines shown, the way. +pub const TargetsKey = struct { revision: u32, at: usize, lo: usize, hi: usize, forward: bool }; + pub const Pane = struct { /// What the replay digest leaves out (core/walk.zig): the view's geometry, /// made again from the rest (File.geometry); the other views' share of /// it (views.zig). (The 9P server's part of `fs` says so in its type.) pub const replica = .{ .local = .{ "pv", "pv_known" }, - .derived = .{ "band_rows", "ghost_at", "ghost_rows", "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan" }, + .derived = .{ "band_rows", "ghost_at", "ghost_rows", "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "top_skip", "notices", "pan", "targets" }, .len = .{ .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, // A picture's memory is its own allocator's (a dump loaded makes // it there). @@ -367,6 +371,9 @@ pub const Pane = struct { /// `ghost_at` (its line's last), the rows below drawn that many lower. /// The mouse reads it, so that a click lands on what is drawn under it. ghost_at: u16 = 0, + /// `]`'s and `[`'s tree targets as the body drawn last found them + /// (body_layer.treeTargets), and what for. + targets: struct { key: ?TargetsKey = null, lines: [3]?usize = @splat(null) } = .{}, ghost_rows: u16 = 0, /// Each other view's share of this pane, while it is not live /// (views.zig): its cursor, scroll and place in that view's layout. @@ -1254,7 +1261,9 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); p.gpa.free(pane.recipe_sels); - @import("jj.zig").forget(p, pane.serial); + // A pane that walked on (Trail.show) is the same pane on another file: + // what jj answers now is its own. + if (p.paneBySerial(pane.serial) == null) @import("jj.zig").forget(p, pane.serial); if (pane.query) |q| { q.deinit(p.gpa); p.gpa.destroy(q); diff --git a/core/root.zig b/core/root.zig index d1a25d21..66e9e0e8 100644 --- a/core/root.zig +++ b/core/root.zig @@ -779,6 +779,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig", "ghost_at", "where a message's detail is drawn under the caret's line (Messages.detailUnder), made again from the step's state with the notices (Messages.collectNotices: at the top of update, presented, sync, place); a frame's are its own" }, .{ "panes.zig", "ghost_rows", "the detail's rows there, made again with ghost_at" }, + .{ "panes.zig", "targets", "`]`'s and `[`'s tree targets as the body drawn last found them (body_layer.treeTargets), keyed by the text's revision, the caret, the lines shown and the way, so a frame asks again only when one moved; the draw's alone, no step reads it" }, .{ "panes.zig views.zig", "band_rows", "the band's rows under a tag (Band.takes), made again from the view's tag state at every sync before anything reads them (layout.floorRows reads the last sync's, as it reads tag_rows)" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap widest", "the text's line index, of its bytes, and the widest line it found (an upper bound: which walk answers, never what)" }, diff --git a/core/syntax.zig b/core/syntax.zig index a388573b..5c05300e 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -566,34 +566,39 @@ pub fn objectAt(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object /// `]f`/`[f` and kin: the next object starting after byte `at`, or the /// previous one ending before it (helix goto_treesitter_object), from the /// first of `.movement`, `.around`, `.inside` the query names. -pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, object: Object, forward: bool, at: usize, within: ?[2]usize) ?Span { - const q = objectQuery(path) orelse return null; - var buf: [32]u8 = undefined; - const capture = for ([_][]const u8{ "movement", "around", "inside" }) |kind| { - const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), kind }) catch return null; - if (captureId(q, want)) |id| break id; - } else return null; +pub fn objectNext(path: []const u8, tree_ptr: *anyopaque, text: []const u8, objects: []const Object, forward: bool, at: usize, within: ?[2]usize, out: []?Span) void { + @memset(out, null); + const q = objectQuery(path) orelse return; + // Each object's capture; one pass of the query finds them all (`]`'s + // three painted targets, body_layer.treeTargets). + var captures: [8]?u32 = @splat(null); + for (objects, captures[0..objects.len]) |object, *capture| { + var buf: [32]u8 = undefined; + capture.* = for ([_][]const u8{ "movement", "around", "inside" }) |kind| { + const want = std.fmt.bufPrint(&buf, "{s}.{s}", .{ objectName(object), kind }) catch break null; + if (captureId(q, want)) |id| break id; + } else null; + } const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr)); const cursor = ts.QueryCursor.create(); defer cursor.destroy(); // Only the objects these bytes hold (a body's rows shown): its painted // targets (body_layer.paintTargets). - if (within) |w| cursor.setByteRange(@intCast(w[0]), @intCast(w[1])) catch return null; + if (within) |w| cursor.setByteRange(@intCast(w[0]), @intCast(w[1])) catch return; cursor.exec(q, tree.rootNode()); - var best: ?Span = null; - while (cursor.nextMatch()) |match| { - const s = matchSpan(q, match, capture, text) orelse continue; + while (cursor.nextMatch()) |match| for (captures[0..objects.len], out) |capture, *best| { + const s = matchSpan(q, match, capture orelse continue, text) orelse continue; if (forward) { if (s.from <= at) continue; - if (best == null or s.from < best.?.from or (s.from == best.?.from and s.to > best.?.to)) best = s; + if (best.* == null or s.from < best.*.?.from or (s.from == best.*.?.from and s.to > best.*.?.to)) best.* = s; } else { if (s.to >= at) continue; - if (best == null or s.to > best.?.to or (s.to == best.?.to and s.from < best.?.from)) best = s; + if (best.* == null or s.to > best.*.?.to or (s.to == best.*.?.to and s.from < best.*.?.from)) best.* = s; } - } - const s = best orelse return null; - if (s.from >= text.len or s.to >= text.len) return null; - return s; + }; + for (out) |*best| if (best.*) |s| if (s.from >= text.len or s.to >= text.len) { + best.* = null; + }; } /// Owned source analysis. Both slices use the allocator passed to analyzeSource. |
