summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/Names.zig92
-rw-r--r--core/Pick.zig297
-rw-r--r--core/Trail.zig19
-rw-r--r--core/body_layer.zig37
-rw-r--r--core/builtins.zig6
-rw-r--r--core/fs.zig6
-rw-r--r--core/look.zig28
-rw-r--r--core/lsp/Ask.zig47
-rw-r--r--core/ninep/ctl.zig4
-rw-r--r--core/normal.zig4
-rw-r--r--core/panes.zig13
-rw-r--r--core/root.zig1
-rw-r--r--core/syntax.zig39
-rw-r--r--dev/gui/gui.zig7
-rw-r--r--dev/lsp/lsp_client.zig85
-rw-r--r--dev/tui/tui.zig39
-rw-r--r--docs/typ/builtins-gui.json2
-rw-r--r--docs/typ/builtins-tui.json2
-rw-r--r--test/behaviour/language_servers.zig25
-rw-r--r--test/behaviour/look_and_exec.zig23
-rw-r--r--test/behaviour/other_files.zig16
-rw-r--r--test/lspmock.zig11
-rw-r--r--test/process/window.zig31
-rw-r--r--test/snapshots/find.golden6
-rw-r--r--test/snapshots/leader.golden38
25 files changed, 742 insertions, 136 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, &notice).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.
diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig
index 6cd97b69..9f6e4876 100644
--- a/dev/gui/gui.zig
+++ b/dev/gui/gui.zig
@@ -1555,10 +1555,13 @@ const StdinFeed = struct {
// finger;<kind>;<id>;<x>;<y>;<pressure>
// close: the window's close button
// One the read cut short, or what may yet begin one, waits for
- // the next read.
+ // the next read; but a read that ends in a lone ESC ends in the
+ // Escape key, as the tty's reader has a read of one ESC (a driver
+ // writes each key and event whole): held, it waited for the next
+ // write, which then came as Alt on its first key.
const rest = f.buf[seq_start..len];
const osc = "\x1b]777;";
- if (std.mem.startsWith(u8, rest, osc) or std.mem.startsWith(u8, osc, rest)) {
+ if (std.mem.startsWith(u8, rest, osc) or (rest.len > 1 and std.mem.startsWith(u8, osc, rest))) {
const bel = std.mem.indexOfScalar(u8, rest, 0x07) orelse {
std.mem.copyForwards(u8, f.buf[0..rest.len], rest);
f.fill = rest.len;
diff --git a/dev/lsp/lsp_client.zig b/dev/lsp/lsp_client.zig
index fdd4af55..a53ff57f 100644
--- a/dev/lsp/lsp_client.zig
+++ b/dev/lsp/lsp_client.zig
@@ -247,6 +247,8 @@ const Caps = struct {
pull_workspace: bool = false,
call_hier: bool = false,
type_hier: bool = false,
+ /// codeAction/resolve: an action that came without its edit is asked for it
+ resolve_actions: bool = false,
/// workspace/didChangeWorkspaceFolders is worth sending
folders: bool = false,
};
@@ -1038,10 +1040,19 @@ fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req,
var b = try docParams(arena, uri.items);
try b.print(arena, ",\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch });
const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return;
- for (items(result)) |ca| {
- const title = str(get(ca, "title")) orelse continue;
+ // Each action a row, its edit of this file after it as `@put`
+ // records (the core's picker previews and applies them, Pick.zig);
+ // one the server left to resolve asked for its edit first.
+ for (items(result)) |listed| {
+ const title = str(get(listed, "title")) orelse continue;
try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title));
cx.rows += 1;
+ var ca = listed;
+ if (get(ca, "edit") == null and get(ca, "data") != null and c.caps.resolve_actions and ca == .object) {
+ const whole = try std.json.Stringify.valueAlloc(arena, ca, .{});
+ if (try call(c, io, arena, "codeAction/resolve", whole[1 .. whole.len - 1], deadline)) |resolved| ca = resolved;
+ }
+ try actionEdits(&cx, c.caps.enc, uri.items, get(ca, "edit"), req.source);
}
},
.completion => {
@@ -1246,24 +1257,8 @@ fn byteSpan(src: []const u8, range: ?std.json.Value, enc: Enc) ?struct { start:
/// applying a fraction of a workspace rename would be worse than either.
fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value, src: []const u8, old: []const u8, also: []const []const u8) Err!void {
var edits: std.ArrayList(PutEdit) = .empty;
- var foreign = false;
-
- // (uri, edits) per file, from either shape of a WorkspaceEdit
- var files: std.ArrayList(struct { []const u8, ?std.json.Value }) = .empty;
- if (get(result, "documentChanges")) |dcs| {
- for (items(dcs)) |dc| {
- if (get(dc, "kind") != null) {
- foreign = true; // create/rename/delete file operations
- continue;
- }
- const u = str(get(get(dc, "textDocument"), "uri")) orelse continue;
- try files.append(cx.arena, .{ u, get(dc, "edits") });
- }
- } else if (get(result, "changes")) |ch| if (ch == .object) {
- var it = ch.object.iterator();
- while (it.next()) |e| try files.append(cx.arena, .{ e.key_ptr.*, e.value_ptr.* });
- };
- for (files.items) |f| {
+ const files, var foreign = try editFiles(cx.arena, result);
+ for (files) |f| {
const in_self = std.mem.eql(u8, f[0], self_uri);
if (!in_self) foreign = true;
for (items(f[1])) |ed| {
@@ -1299,6 +1294,55 @@ fn renameEdits(cx: *Cx, enc: Enc, self_uri: []const u8, result: std.json.Value,
for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text);
}
+/// A file a WorkspaceEdit edits: its uri and its TextEdit[].
+const EditFile = struct { []const u8, ?std.json.Value };
+
+/// A WorkspaceEdit's files, from either of its shapes, and whether it also
+/// creates, renames or deletes a file.
+fn editFiles(arena: std.mem.Allocator, we: std.json.Value) Err!struct { []const EditFile, bool } {
+ var files: std.ArrayList(EditFile) = .empty;
+ var ops = false;
+ if (get(we, "documentChanges")) |dcs| {
+ for (items(dcs)) |dc| {
+ if (get(dc, "kind") != null) {
+ ops = true;
+ continue;
+ }
+ const u = str(get(get(dc, "textDocument"), "uri")) orelse continue;
+ try files.append(arena, .{ u, get(dc, "edits") });
+ }
+ } else if (get(we, "changes")) |ch| if (ch == .object) {
+ var it = ch.object.iterator();
+ while (it.next()) |e| try files.append(arena, .{ e.key_ptr.*, e.value_ptr.* });
+ };
+ return .{ files.items, ops };
+}
+
+/// A code action's WorkspaceEdit (none for a command's): its edits of this
+/// file as sorted `@put` records; one that reaches another file or makes
+/// one is `@elsewhere`, never a part of it applied; a malformed edit leaves
+/// the action none.
+fn actionEdits(cx: *Cx, enc: Enc, self_uri: []const u8, we: ?std.json.Value, src: []const u8) Err!void {
+ const v = we orelse return;
+ const files, const ops = try editFiles(cx.arena, v);
+ var edits: std.ArrayList(PutEdit) = .empty;
+ var elsewhere = ops;
+ for (files) |f| {
+ if (!std.mem.eql(u8, f[0], self_uri)) {
+ elsewhere = true;
+ continue;
+ }
+ for (items(f[1])) |ed| {
+ const span = byteSpan(src, get(ed, "range"), enc) orelse return;
+ const text = str(get(ed, "newText")) orelse return;
+ try edits.append(cx.arena, .{ .start = span.start, .end = span.end, .text = text });
+ }
+ }
+ if (elsewhere) return cx.out.writeAll("@elsewhere\n");
+ sortEdits(edits.items);
+ for (edits.items) |ed| try lsp.put(cx.out, ed.start, ed.end, ed.text);
+}
+
/// TextEdit[] from formatting is by definition about the current document:
/// straight to sorted `@put` records.
fn formatEdits(cx: *Cx, enc: Enc, result: std.json.Value, src: []const u8) Err!void {
@@ -2111,6 +2155,7 @@ fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) E
}
c.caps.call_hier = provider(get(caps, "callHierarchyProvider"));
c.caps.type_hier = provider(get(caps, "typeHierarchyProvider"));
+ c.caps.resolve_actions = if (get(get(caps, "codeActionProvider"), "resolveProvider")) |r| r == .bool and r.bool else false;
c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false;
try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline);
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index 542ef59a..aa1f8849 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -179,6 +179,9 @@ fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void {
var carried: usize = 0;
// The sequence carried is past max_sequence, and said so.
var dropping = false;
+ // The ESC the last read ended in, carried because more came while it
+ // waited for a sequence's rest.
+ var esc_held = false;
while (true) { // stopInput cancels the task; the read then fails with Canceled
if (carried == buf.len and buf.len < max_sequence) {
if (gpa.realloc(buf, @min(2 * buf.len, max_sequence))) |grown| buf = grown else |_| {}
@@ -227,6 +230,12 @@ fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void {
if (scalar_len > end - (lead - 1)) parse_end = lead - 1;
}
var consumed: usize = 0;
+ // That ESC is the Escape key unless this read goes on with a
+ // sequence's rest (an ssh packet cut it after its ESC): its
+ // introducer, CSI's `[`, SS3's `O`, a string's, or another ESC. A
+ // key typed just after Escape is its own, not Alt on it.
+ const lone_esc = esc_held and end > 1 and buf[0] == 0x1b and std.mem.indexOfScalar(u8, "[O]P_^\\\x1b", buf[1]) == null;
+ esc_held = false;
// A read that is one ESC and nothing else is the Escape key: a
// terminal writes each key's sequence whole and ssh carries each of
// its writes whole, so no sequence arrives cut right after its ESC.
@@ -247,9 +256,12 @@ fn readInput(loop: *Loop, tty: anytype, vx: *vaxis.Vaxis, feed: *Feed) !void {
std.mem.startsWith(u8, FrameAck.answer, rest)) break;
if (!waited and parse_end == end and rest[0] == 0x1b and (rest.len == 1 or (rest.len == 2 and rest[1] == 0x1b))) {
waited = true;
- if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) break;
+ if (try inputFollows(tty, loop.io, if (vx.caps.kitty_keyboard) 1000 else 50)) {
+ esc_held = rest.len == 1;
+ break;
+ }
}
- const result = try parser.parse(buf[consumed..parse_end], vx.opts.system_clipboard_allocator);
+ const result = try parser.parse(buf[consumed..if (lone_esc and consumed == 0) 1 else parse_end], vx.opts.system_clipboard_allocator);
if (result.n == 0) break;
consumed += result.n;
// A modifier pressed on its own, which the kitty keyboard
@@ -2668,6 +2680,29 @@ test "an ESC read by itself is the Escape key at once" {
t.vx.caps.kitty_keyboard = false;
}
+test "an ESC that ends a read, a key read after it within the wait, is the Escape key and then that key" {
+ var t: TestInput = undefined;
+ try t.init();
+ defer t.deinit();
+ // Typed faster than read (a burst over a link): `x` and Escape in one
+ // read, `A` in the next while the ESC waits for a sequence's rest. Joined
+ // to it, it was Alt-A and the Escape was lost (insert mode kept, `A`
+ // typed nothing). A sequence cut after its ESC still joins (the test
+ // above: `[`, `O` and the strings' introducers, another ESC).
+ var reader: TestReader = .{ .parts = &.{ "x\x1b", "A" } };
+ try readInput(&t.loop, &reader, &t.vx, &t.feed);
+ try std.testing.expect(reader.asked);
+ try std.testing.expectEqual(.winsize, std.meta.activeTag((try t.loop.tryEvent()).?));
+ try std.testing.expectEqual(@as(u21, 'x'), (try t.loop.tryEvent()).?.key_press.codepoint);
+ const escape = (try t.loop.tryEvent()).?.key_press;
+ try std.testing.expectEqual(vaxis.Key.escape, escape.codepoint);
+ try std.testing.expect(!escape.mods.alt);
+ const a = (try t.loop.tryEvent()).?.key_press;
+ try std.testing.expectEqual(@as(u21, 'A'), a.codepoint);
+ try std.testing.expect(!a.mods.alt);
+ try std.testing.expect(try t.loop.tryEvent() == null);
+}
+
test "an Escape read with the click after it is the Escape key, then the click" {
var t: TestInput = undefined;
try t.init();
diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json
index 6466a845..b2814d5c 100644
--- a/docs/typ/builtins-gui.json
+++ b/docs/typ/builtins-gui.json
@@ -17,7 +17,7 @@
{"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard.", "text": "Replace the selection with the system clipboard."},
{"name": "ClipYank", "leader": "SPC y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Copy the selection to the system clipboard.", "text": "Copy the selection to the system clipboard.\nEvery cursor's selection, joined; in an image or a PDF's pane, what it has selected."},
{"name": "ClipYankMain", "leader": "SPC Y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Copy the primary selection alone to the system clipboard.", "text": "Copy the primary selection alone to the system clipboard.\nClipYank (`SPC y`) copies every cursor's selection, joined; with one cursor the two are the same."},
- {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor, in a +Lsp.", "text": "List the language server's code actions for the cursor, in a +Lsp."},
+ {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor, to apply one.", "text": "List the language server's code actions for the cursor, to apply one.\nTyped 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."},
{"name": "Collapse", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Fold this pane to its tag, or give it its share of the column again.", "text": "Fold this pane to its tag, or give it its share of the column again."},
{"name": "Compare", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Draw the file's difference between each two jj revisions as one change, as Changes draws one.", "text": "Draw the file's difference between each two jj revisions as one change, as Changes draws one.\n`Compare <rev> <rev> [<rev> ...]`: two points or more in their order, each one revision (a commit or change id, a bookmark, `master@origin`, `@`): `Compare 9ef6312813 ea63317630 master@origin`. A pair is drawn as one change however many lie between its points; after its last line, its row: the two points, how many changes lie between them, their first and last days. One set a pane: a later Changes or Compare replaces it. Bare: as bare Changes."},
{"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init` in the configuration directory, in a pane.", "text": "Open the startup file, `init` in the configuration directory, in a pane.\nIts pane when it is open, else the file; not there yet, a pane of that name, which Save makes, its directory too."},
diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json
index 70d7c73d..0f7e3896 100644
--- a/docs/typ/builtins-tui.json
+++ b/docs/typ/builtins-tui.json
@@ -17,7 +17,7 @@
{"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard.", "text": "Replace the selection with the system clipboard."},
{"name": "ClipYank", "leader": "SPC y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Copy the selection to the system clipboard.", "text": "Copy the selection to the system clipboard.\nEvery cursor's selection, joined; in an image or a PDF's pane, what it has selected."},
{"name": "ClipYankMain", "leader": "SPC Y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Copy the primary selection alone to the system clipboard.", "text": "Copy the primary selection alone to the system clipboard.\nClipYank (`SPC y`) copies every cursor's selection, joined; with one cursor the two are the same."},
- {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor, in a +Lsp.", "text": "List the language server's code actions for the cursor, in a +Lsp."},
+ {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor, to apply one.", "text": "List the language server's code actions for the cursor, to apply one.\nTyped 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."},
{"name": "Collapse", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Fold this pane to its tag, or give it its share of the column again.", "text": "Fold this pane to its tag, or give it its share of the column again."},
{"name": "Compare", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Draw the file's difference between each two jj revisions as one change, as Changes draws one.", "text": "Draw the file's difference between each two jj revisions as one change, as Changes draws one.\n`Compare <rev> <rev> [<rev> ...]`: two points or more in their order, each one revision (a commit or change id, a bookmark, `master@origin`, `@`): `Compare 9ef6312813 ea63317630 master@origin`. A pair is drawn as one change however many lie between its points; after its last line, its row: the two points, how many changes lie between them, their first and last days. One set a pane: a later Changes or Compare replaces it. Bare: as bare Changes."},
{"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init` in the configuration directory, in a pane.", "text": "Open the startup file, `init` in the configuration directory, in a pane.\nIts pane when it is open, else the file; not there yet, a pane of that name, which Save makes, its directory too."},
diff --git a/test/behaviour/language_servers.zig b/test/behaviour/language_servers.zig
index 904fcfba..13e42fa6 100644
--- a/test/behaviour/language_servers.zig
+++ b/test/behaviour/language_servers.zig
@@ -298,3 +298,28 @@ test "language-servers: Index runs the language's indexer at the project's root,
const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)];
try std.testing.expect(std.mem.startsWith(u8, try bodyOf(&s, dir), s.at("% cd '{s}' && rust-analyzer scip .", .{dir})));
}
+
+test "language-servers: SPC l a lists the server's code actions in the pane's tag by their digits, the one under the cursor shown as its edit, and its digit applies it, one the server left to resolve resolved first" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var s = try Session.initLanguage(std.testing.allocator);
+ defer s.deinit();
+ const before = "mod lib;\n\nfn main() {\n let x = add(1, 2);\n let y = add(3, 4);\n let _ = x + y;\n}\n";
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "main.rs", .data = before });
+ var buf: [4096]u8 = undefined;
+ const main = try s.lookFile(s.at("{s}/main.rs:4:13", .{buf[0..try tmp.dir.realPath(std.testing.io, &buf)]}));
+ const body = s.at("/pane/{d}/body", .{main});
+ try s.keys(" la");
+ try std.testing.expect(std.mem.indexOf(u8, try s.read("/index"), "+Lsp") == null);
+ _ = try s.where("▶ 1 mock action: extract");
+ _ = try s.where(" 2 mock action: add a line");
+ _ = try s.where(" 3 mock action: rename add to sum");
+ // The third, its edit asked for with codeAction/resolve: the two calls.
+ try s.keys("\u{F800}\u{F800}");
+ _ = try s.where("let x = sum(1, 2);");
+ try s.expect(body, before);
+ try s.keys("3");
+ try s.expect(body, "mod lib;\n\nfn main() {\n let x = sum(1, 2);\n let y = sum(3, 4);\n let _ = x + y;\n}\n");
+ try s.keys("u");
+ try s.expect(body, before);
+}
diff --git a/test/behaviour/look_and_exec.zig b/test/behaviour/look_and_exec.zig
index a7de93cd..251b6325 100644
--- a/test/behaviour/look_and_exec.zig
+++ b/test/behaviour/look_and_exec.zig
@@ -790,3 +790,26 @@ test "look-and-exec: a look at a directory opens a pane listing it, as acme's di
try std.testing.expectEqualStrings("later", again[1]);
try std.testing.expectEqualStrings("sub/", again[2]);
}
+
+test "look-and-exec: a reading pane that walks to another file is the same pane: its number, an open of its files reading the new text, /log's rename for it, the file it left in Recent" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.txt", .data = "a\n" });
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.txt", .data = "b\n" });
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ var buf: [4096]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)];
+ const r = try s.lookFile(s.at("{s}/a.txt", .{dir}));
+ const body = try s.hold(s.at("/pane/{d}/body", .{r}), 0);
+ // A step in place: b.txt in the pane a.txt was in.
+ try s.write(s.at("/pane/{d}/look", .{r}), s.at("{s}/b.txt\n", .{dir}));
+ try expectEqual(r, try s.focused());
+ try s.expect(s.at("/pane/{d}/name", .{r}), s.at("{s}/b.txt\n", .{dir}));
+ try std.testing.expectEqualStrings("b\n", try s.readFid(body));
+ s.clunk(body);
+ const log = try s.read("/log");
+ try std.testing.expect(std.mem.endsWith(u8, log, s.at("rename {d} {s}/b.txt\n", .{ r, dir })));
+ try std.testing.expect(std.mem.indexOf(u8, log, s.at("del {d} ", .{r})) == null);
+ try std.testing.expect(std.mem.indexOf(u8, try s.read("/recent"), s.at("{s}/a.txt", .{dir})) != null);
+}
diff --git a/test/behaviour/other_files.zig b/test/behaviour/other_files.zig
index b19ffa0f..e6c104c3 100644
--- a/test/behaviour/other_files.zig
+++ b/test/behaviour/other_files.zig
@@ -22,6 +22,22 @@ test "other-files: kbdin types at the pane with the keyboard and mousein clicks,
try std.testing.expectError(error.Refused, s.read("/kbdin"));
}
+test "other-files: kbdin's keys are the user's: SPC f f opens Find's picker in the pane's tag where jumps walk, not the +Search a script's Find opens" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.txt", .data = "a\n" });
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.txt", .data = "b\n" });
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ var buf: [4096]u8 = undefined;
+ _ = try s.lookFile(s.at("{s}/a.txt", .{buf[0..try tmp.dir.realPath(std.testing.io, &buf)]}));
+ try s.keys(" ff");
+ try std.testing.expect(std.mem.indexOf(u8, try s.read("/index"), "+Search") == null);
+ // Its rows under the tag of the pane typed at, the cursor on the first.
+ _ = try s.where("▶ a.txt");
+ _ = try s.where(" b.txt");
+}
+
test "other-files: kbdin's Kalt rune is Alt on the key after it alone, and an Alt key types nothing" {
var s = try Session.initFile(std.testing.allocator, "x\n");
defer s.deinit();
diff --git a/test/lspmock.zig b/test/lspmock.zig
index 8b5c73a8..0fd34677 100644
--- a/test/lspmock.zig
+++ b/test/lspmock.zig
@@ -207,7 +207,7 @@ fn handle(a: std.mem.Allocator, raw: []const u8) void {
\\"referencesProvider":true,"documentHighlightProvider":true,
\\"hoverProvider":true,"documentSymbolProvider":true,
\\"workspaceSymbolProvider":true,"renameProvider":true,
- \\"documentFormattingProvider":true,"codeActionProvider":true,
+ \\"documentFormattingProvider":true,"codeActionProvider":{{"resolveProvider":true}},
\\"completionProvider":{{}},
\\"callHierarchyProvider":true,"typeHierarchyProvider":true,
\\"diagnosticProvider":{{"interFileDependencies":false,"workspaceDiagnostics":false}},
@@ -283,7 +283,14 @@ fn handle(a: std.mem.Allocator, raw: []const u8) void {
} else if (std.mem.eql(u8, method, "textDocument/formatting")) {
reply(a, rid, "[{{\"range\":{s},\"newText\":\"// formatted by mock\\n\"}}]", .{range(a, 0, 0, 0)});
} else if (std.mem.eql(u8, method, "textDocument/codeAction")) {
- reply(a, rid, "[{{\"title\":\"mock action: extract\"}}]", .{});
+ // A title alone (a command's), one with its edit (a line put in
+ // at the top), and one whose edit is resolved when asked (its
+ // `data` the document's uri).
+ reply(a, rid, "[{{\"title\":\"mock action: extract\"}},{{\"title\":\"mock action: add a line\",\"edit\":{{\"changes\":{{\"{s}\":[{{\"range\":{s},\"newText\":\"// added by mock\\n\"}}]}}}}}},{{\"title\":\"mock action: rename add to sum\",\"data\":\"{s}\"}}]", .{ uri, range(a, 0, 0, 0), uri });
+ } else if (std.mem.eql(u8, method, "codeAction/resolve")) {
+ // main.rs's two calls of `add` (L3, L4) renamed.
+ const doc = str(get(params, "data")) orelse uri;
+ reply(a, rid, "{{\"title\":\"mock action: rename add to sum\",\"edit\":{{\"changes\":{{\"{s}\":[{{\"range\":{s},\"newText\":\"sum\"}},{{\"range\":{s},\"newText\":\"sum\"}}]}}}}}}", .{ doc, range(a, 3, 12, 15), range(a, 4, 12, 15) });
} else if (std.mem.eql(u8, method, "textDocument/completion")) {
reply(a, rid, "{{\"items\":[{{\"label\":\"alpha\",\"detail\":\"fn alpha()\"}},{{\"label\":\"beta\",\"detail\":\"fn beta()\"}}]}}", .{});
} else if (std.mem.eql(u8, method, "textDocument/diagnostic")) {
diff --git a/test/process/window.zig b/test/process/window.zig
index 59c84616..292e0e00 100644
--- a/test/process/window.zig
+++ b/test/process/window.zig
@@ -8,6 +8,7 @@ const process = @import("../process.zig");
pub const cases = .{
.{ "window: a monkey over the effects: random clicks, drags, wheels, keys, columns, looks and themes, then it settles, alive, with no crash record", monkey },
.{ "window: its frame corpus, every kept frame and its sha256 into PARDES_GUI_CORPUS, to compare two builds on one machine", corpus },
+ .{ "window: a lone Esc written to its test stdin is the Escape key at once, the key written after it its own", loneEscape },
};
fn envOr(name: [*:0]const u8, default: []const u8) []const u8 {
@@ -193,6 +194,25 @@ fn bodyHas(f: *process.Files, serial: u32, word: []const u8) !void {
if (process.nowMs() > deadline) return error.NoOutput;
}
+/// A lone Esc a driver writes to the window's stdin, as its keys come:
+/// the Escape key at once. Held for the next write (DESIGN D15, POLISH 16),
+/// that write's `A` came as Alt-A and its `y` was typed where insert mode
+/// still was.
+fn loneEscape(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ try process.only(.gui);
+ var d = try process.Detached.start(gpa, exe, "loneesc", .{});
+ defer d.deinit();
+ const f = &d.files;
+ const pane = try paneWith(f, "loneesc.txt");
+ try d.typeKeys("ix");
+ try d.settle(gpa);
+ try d.typeKeys("\x1b");
+ try d.settle(gpa);
+ try d.typeKeys("Ay");
+ try d.settle(gpa);
+ try std.testing.expectEqualStrings("xinitialy\n", try f.read(f.at("/pane/{d}/body", .{pane})));
+}
+
extern "c" fn system(cmd: [*:0]const u8) c_int;
extern "c" fn ioctl(fd: c_int, request: c_ulong, ...) c_int;
@@ -402,10 +422,10 @@ fn corpus(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
defer arena.deinit();
const a = arena.allocator();
defer _ = system("rm -rf -- /tmp/pardes-gui-corpus");
- // Its Looks open panes and Del them by serial, as `Jumps new-pane`
- // does (SPEC §6.6): under walk a file pane steps in place, a new
- // serial, and the frames would not be the base's to compare.
- const init = "Shell /bin/sh\nTheme forge\nMessageLinger 0\nCursorBlink off\nJumps new-pane\n";
+ // Jumps walk, the default: the file pane's Looks at files step it in
+ // place, the same pane (its serial kept, Trail.show); a picture's and a
+ // PDF's open panes of their own.
+ const init = "Shell /bin/sh\nTheme forge\nMessageLinger 0\nCursorBlink off\n";
var k: Corpus = .{ .gpa = gpa, .a = a, .out = out };
{
try corpusRoot(a);
@@ -474,7 +494,8 @@ fn corpus(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
const image = try paneWith(f, "ramp.ppm");
try k.keep(&d, 0, "09 an image pane", false);
try f.write(f.at("/pane/{d}/exec", .{image}), "Del\n");
- try f.write(f.at("/pane/{d}/exec", .{notes}), "Del\n");
+ // The file pane walks back to shapes.zig (its trail's step).
+ try f.write(f.at("/pane/{d}/look", .{notes}), root ++ "/shapes.zig\n");
try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/doc.pdf\n");
_ = try paneWith(f, "doc.pdf");
try k.keep(&d, 0, "09 a PDF pane", false);
diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden
index b6521d31..5fe63c16 100644
--- a/test/snapshots/find.golden
+++ b/test/snapshots/find.golden
@@ -83,18 +83,18 @@
|4: rop | Grep Recent Panes Symbols All Jumplist
|5: nothing matches
|7: 1 beta body
-|40: ⏎ lands here · its text is the preview · S-⏎ a new pane 2 messages · SPC h m
+|40: ⏎ lands here · its text is the preview · S-⏎ a new pane 1 message · SPC h m
== snap cancel grid=120x41 cursor=7,3
|2: here.txt:1 › Find zqm 2/3 › /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Keep Save Term Collapse Follow Del
|3: 1 beta body
|4:
|5:
|7:
-|40: ✓ /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Find 2 messages · SPC h m
+|40: ✓ /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Find 1 message · SPC h m
== snap topbar grid=120x41 cursor=84,2
|2: ^ · › Find zqm 2/3 › /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Keep ␣ f Find bod 0/0
|3: │ │ Walk Look Split Newcol Grep Edit Copy Keep D
|4: rop | Grep Recent Panes Symbols All Jumplist
|5: nothing matches
|7: 1 beta body
-|40: ⏎ lands here · its text is the preview · S-⏎ a new pane 2 messages · SPC h m
+|40: ⏎ lands here · its text is the preview · S-⏎ a new pane 1 message · SPC h m
diff --git a/test/snapshots/leader.golden b/test/snapshots/leader.golden
index c6a5460e..9b7c1048 100644
--- a/test/snapshots/leader.golden
+++ b/test/snapshots/leader.golden
@@ -195,25 +195,25 @@
|18: 13 List the subtypes of the type under the cursor in a +Search; a single one is a jump.
|19: 14
|20: 15 SPC l a CodeAction
-|21: 16 List the language server's code actions for the cursor, in a +Lsp.
-|22: 17
-|23: 18 SPC l b Callstack
-|24: 19 Show the callers of the function under the cursor as a tree, outermost first, in a +Callstac↩
-|25: k.
-|26: 20 Each caller with its place to open and its signature, the line of each call under it; caller↩
-|27: s named for tests after the rest, a recursion marked `↻`. CallstackDepth sets how many level↩
-|28: s (8 by default); a deeper tree says where to go on from. `g c` does the same.
-|29: 21
-|30: 22 SPC l c Callers
-|31: 23 List the functions that call the one under the cursor, one level up; a single one is a jump.
-|32: 24
-|33: 25 SPC l d Diagnostics
-|34: 26 List this file's diagnostics in a +Search.
-|35: 27 `] d` and `[ d` step through them in the text, `] D` and `[ D` to the last and the first.
-|36: 28
-|37: 29 SPC l h SelectRefs
-|38: 30 Select every reference to the symbol under the cursor.
-|39: 31
+|21: 16 List the language server's code actions for the cursor, to apply one.
+|22: 17 Typed where jumps walk, they are a picker in the pane's tag, the one under the cursor shown ↩
+|23: as its edit, applied by Enter or its digit; else a +Lsp lists them.
+|24: 18
+|25: 19 SPC l b Callstack
+|26: 20 Show the callers of the function under the cursor as a tree, outermost first, in a +Callstac↩
+|27: k.
+|28: 21 Each caller with its place to open and its signature, the line of each call under it; caller↩
+|29: s named for tests after the rest, a recursion marked `↻`. CallstackDepth sets how many level↩
+|30: s (8 by default); a deeper tree says where to go on from. `g c` does the same.
+|31: 22
+|32: 23 SPC l c Callers
+|33: 24 List the functions that call the one under the cursor, one level up; a single one is a jump.
+|34: 25
+|35: 26 SPC l d Diagnostics
+|36: 27 List this file's diagnostics in a +Search.
+|37: 28 `] d` and `[ d` step through them in the text, `] D` and `[ D` to the last and the first.
+|38: 29
+|39: 30 SPC l h SelectRefs
|40: ✓ /tmp/pardes-snap/leader/cwd/cmds.txt Help 16 messages · SPC h m
== snap del-output grid=100x41 cursor=7,3
|5: