summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/Pick.zig264
-rw-r--r--core/body_layer.zig2
-rw-r--r--core/builtins.zig6
-rw-r--r--core/lsp/Ask.zig47
-rw-r--r--dev/lsp/lsp_client.zig85
-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/lspmock.zig11
9 files changed, 390 insertions, 54 deletions
diff --git a/core/Pick.zig b/core/Pick.zig
index e19866d3..6d2c9ba1 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) = .{},
@@ -225,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;
@@ -303,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;
+ }
+ },
}
}
@@ -401,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);
};
}
@@ -416,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);
@@ -459,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 };
+const Row = struct { text: []const u8, key: u8 = 0, pre: u16 = 0, faint: u16 = 0, dim: bool = false, marks: []const u16 = &.{}, target: Target = .none };
fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row {
const dir = pk.dir.slice();
@@ -528,6 +553,19 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) !Row {
row.target = .{ .place = .{ .path = f.path, .at = .{ .line = cand.ref } } };
},
.themes => {},
+ // 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);
@@ -588,9 +626,9 @@ 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) {
- try text.appendSlice(arena, " ⏎ wear it · esc");
+ // Themes and actions have no acts and no other sources: no second row.
+ if (pk.source == .themes or pk.source == .actions) {
+ try text.appendSlice(arena, if (pk.source == .themes) " ⏎ wear it · esc" else " ⏎ or 1-9 apply it · esc");
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 };
}
@@ -613,7 +651,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?TagState.Head {
for (acts) |act| if (offered(pk, act)) try text.print(arena, "{s} ", .{act.word});
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;
@@ -665,7 +703,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) };
+ 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) };
}
out[0] = .{ .rows = rows };
return out;
@@ -823,6 +861,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
@@ -840,14 +1000,18 @@ 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 (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)) return;
if (s.field.key(k)) filter(p, pk);
return;
@@ -1926,3 +2090,65 @@ test "n and N walk the newest list or search word, or the one Looked at (SPEC §
p.update(.{ .key = .{ .cp = 'n', .text = "n" } });
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);
+ // 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));
+ // `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));
+}
diff --git a/core/body_layer.zig b/core/body_layer.zig
index a182f218..82bfcebc 100644
--- a/core/body_layer.zig
+++ b/core/body_layer.zig
@@ -557,6 +557,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
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/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/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/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/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")) {