summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/lsp/Ask.zig591
-rw-r--r--src/lsp/lsp.zig3
-rw-r--r--src/ninep/ctl.zig15
-rw-r--r--src/pardes.zig578
-rw-r--r--test/output.zig4
5 files changed, 610 insertions, 581 deletions
diff --git a/src/lsp/Ask.zig b/src/lsp/Ask.zig
new file mode 100644
index 00000000..5ef63e7e
--- /dev/null
+++ b/src/lsp/Ask.zig
@@ -0,0 +1,591 @@
+//! A question asked of the language servers, from the core's side: a
+//! language word's request (Def, Refs, Hover, Rename, Callstack and the
+//! rest), the one answer awaited, and what the answer does when it comes
+//! (rows in a query pane, a jump, a rename's edits, a message).
+const std = @import("std");
+const pardes = @import("../pardes.zig");
+const lsp = @import("lsp.zig");
+const panes = @import("../panes.zig");
+const modal = @import("../modal.zig");
+const normal = @import("../normal.zig");
+const edit = @import("../edit.zig");
+const exec = @import("../exec.zig");
+const look = @import("../look.zig");
+const layout = @import("../layout.zig");
+const tagline = @import("../tagline.zig");
+const config = @import("../config.zig");
+const memory = @import("../memory.zig");
+const Pardes = pardes.Pardes;
+const Pane = panes.Pane;
+const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET;
+
+pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void {
+ var arg = arg_in;
+ if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary
+ // Lspwhy narrates the last query where it was asked -- that pane's
+ // file, place and argument -- from wherever it is run.
+ const last_pane: ?usize = if (kind == .explain) (if (p.lsp_last) |last| p.paneBySerial(last.serial) else null) else null;
+ const id = last_pane orelse asked;
+ var said: [128]u8 = undefined;
+ if (!lsp.supports.contains(kind))
+ return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no language server here answers it", .{lspWord(kind)}) catch "no language server answers it");
+ const pane = p.panes[id] orelse return;
+ if (kind != .status) {
+ const f = pane.file orelse
+ return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks");
+ if (f.output != null)
+ return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks");
+ }
+ if (arg.len > 128) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: its argument is at most 128 bytes", .{lspWord(kind)}) catch "argument too long");
+ if (kind == .rename) {
+ const zig_buf = if (pane.file) |f| std.mem.endsWith(u8, f.path, ".zig") else true;
+ if ((zig_buf and (!std.zig.isValidId(arg) or std.zig.isUnderscore(arg))) or
+ (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null))
+ return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name");
+ }
+ var off = if (pane.file) |f| modal.offsetAt(f.content, .{
+ .row = @intCast(@max(0, pane.body.cur_row)),
+ .col = @intCast(@max(0, pane.body.cur_col)),
+ }) else 0;
+ // Def or Refs given a symbol (a 2-1 chord's selection) asks at its
+ // occurrence nearest the cursor, which a sweep leaves at one end of
+ // what it selected; the server is asked at a place, never a name.
+ if ((kind == .definition or kind == .references) and arg.len > 0) {
+ const content = pane.file.?.content;
+ var nearest: ?usize = null;
+ var best: usize = 0;
+ var from: usize = 0;
+ while (std.mem.indexOfPos(u8, content, from, arg)) |at_hit| : (from = at_hit + 1) {
+ const d = if (at_hit > off) at_hit - off else off -| (at_hit + arg.len);
+ if (nearest != null and at_hit > off and d >= best) break;
+ if (nearest == null or d < best) {
+ nearest = at_hit;
+ best = d;
+ }
+ }
+ off = nearest orelse
+ return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch "no such symbol in this file");
+ arg = "";
+ }
+ // Lspwhy asks the last query again, narrated: its kind and argument,
+ // at its place when asked from its pane. None yet: a definition.
+ var explained: [160]u8 = undefined;
+ var sent = arg;
+ var at = off;
+ if (kind == .explain) {
+ if (p.lsp_last) |last| {
+ sent = std.fmt.bufPrint(&explained, "{s} {s}", .{ @tagName(last.kind), last.arg.slice() }) catch "";
+ if (last_pane != null) at = last.offset;
+ }
+ } else if (kind != .status) p.lsp_last = .{ .kind = kind, .arg = .from(arg), .serial = pane.serial, .offset = @intCast(off) };
+ p.lsp_seq +%= 1;
+ // A 9P write that asked it is answered once the answer is in.
+ if (p.fs.serving) p.fs.lsp_answer_at = pardes.turn.lsp_answers;
+ p.lsp_wait = .{
+ .id = p.lsp_seq,
+ .kind = kind,
+ .pane = id,
+ .serial = pane.serial,
+ .revision = if (pane.file) |f| f.revision else 0,
+ .arg = .from(arg),
+ .row = pane.body.cur_row,
+ .col = pane.body.cur_col,
+ };
+ p.emit(.{ .lsp = .{
+ .id = p.lsp_seq,
+ .kind = kind,
+ .pane = @intCast(id),
+ .offset = @intCast(at),
+ .arg = .from(sent),
+ } });
+}
+
+const LspEdit = struct { start: usize, end: usize, text: []const u8 };
+
+fn parseLspEdits(p: *Pardes, 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;
+ var form: enum { undecided, edit, put } = .undecided;
+ while (lines.next()) |line| {
+ if (line.len == 0) {
+ if (lines.peek() == null) break;
+ return null;
+ }
+ var fields = std.mem.tokenizeScalar(u8, line, ' ');
+ const head = fields.next() orelse return null;
+ const want: @TypeOf(form) = if (std.mem.eql(u8, head, "@put"))
+ .put
+ else if (std.mem.eql(u8, head, "@edit"))
+ .edit
+ else
+ return null;
+ if (form == .undecided) form = want;
+ if (form != want) return null;
+ const start = std.fmt.parseInt(usize, fields.next() orelse return null, 10) catch return null;
+ const end = std.fmt.parseInt(usize, fields.next() orelse return null, 10) catch return null;
+ var text: []const u8 = if (want == .edit) (fallback orelse return null) else "";
+ if (want == .put) {
+ if (fields.next()) |encoded| text = decodePct(a, encoded) orelse return null;
+ }
+ if (fields.next() != null) return null;
+ edits[n] = .{ .start = start, .end = end, .text = text };
+ n += 1;
+ }
+ return if (n == 0) null else edits[0..n];
+}
+
+/// The `@put` text codec's read half (lsp.put writes it): `%XX` bytes,
+/// everything else literal. An invalid escape fails the whole record.
+fn decodePct(a: std.mem.Allocator, encoded: []const u8) ?[]const u8 {
+ const out = a.alloc(u8, encoded.len) catch return null;
+ var n: usize = 0;
+ var i: usize = 0;
+ while (i < encoded.len) {
+ if (encoded[i] == '%') {
+ if (i + 3 > encoded.len) return null;
+ out[n] = std.fmt.parseInt(u8, encoded[i + 1 .. i + 3], 16) catch return null;
+ i += 3;
+ } else {
+ out[n] = encoded[i];
+ i += 1;
+ }
+ n += 1;
+ }
+ return out[0..n];
+}
+
+fn mapLspEditOffset(edits: []const LspEdit, old: usize) usize {
+ var old_at: usize = 0;
+ var new_at: usize = 0;
+ for (edits) |e| {
+ if (old < e.start) return new_at + (old - old_at);
+ new_at += e.start - old_at;
+ if (old < e.end) return new_at + @min(old - e.start, e.text.len -| 1);
+ new_at += e.text.len;
+ if (old == e.end) return new_at;
+ old_at = e.end;
+ }
+ return new_at + (old - old_at);
+}
+
+fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) bool {
+ const f = if (pane.file) |*file| file else return false;
+ if (f.revision != revision) return false;
+
+ var removed: usize = 0;
+ var added: usize = 0;
+ var previous_end: usize = 0;
+ var same = true;
+ for (edits) |e| {
+ if (e.start < previous_end or e.start > e.end or e.end > f.content.len) return false;
+ if (e.start == e.end and e.text.len == 0) return false; // an empty insert is a malformed record
+ removed = std.math.add(usize, removed, e.end - e.start) catch return false;
+ added = std.math.add(usize, added, e.text.len) catch return false;
+ previous_end = e.end;
+ if (same and !std.mem.eql(u8, f.content[e.start..e.end], e.text)) same = false;
+ }
+ if (same) return false; // a no-op response earns no undo entry
+ const final_len = std.math.add(usize, f.content.len - removed, added) catch return false;
+ const replacement = p.gpa.alloc(u8, final_len) catch return false;
+
+ const old_cursor = modal.offsetAt(f.content, .{
+ .row = @intCast(@max(0, pane.body.cur_row)),
+ .col = @intCast(@max(0, pane.body.cur_col)),
+ });
+ const mapped_cursor = mapLspEditOffset(edits, old_cursor);
+ var read_at: usize = 0;
+ var write_at: usize = 0;
+ for (edits) |e| {
+ @memcpy(replacement[write_at .. write_at + (e.start - read_at)], f.content[read_at..e.start]);
+ write_at += e.start - read_at;
+ @memcpy(replacement[write_at .. write_at + e.text.len], e.text);
+ write_at += e.text.len;
+ read_at = e.end;
+ }
+ @memcpy(replacement[write_at..], f.content[read_at..]);
+
+ edit.pushUndo(p, &pane.body);
+ panes.File.setContent(p, f, replacement);
+ const cursor = modal.positionAt(f.content, mapped_cursor);
+ pane.body.cur_row = @intCast(cursor.row);
+ pane.body.cur_col = @intCast(cursor.col);
+ pane.body.vsel.active = false;
+ pane.body.select = false;
+ pane.body.sticky_col = -1;
+ pane.ensureCursorVisible();
+ return true;
+}
+
+/// The builtin word that asks `kind`, for what it says.
+fn lspWord(kind: lsp.Kind) []const u8 {
+ return switch (kind) {
+ .hover => "Hover",
+ .definition => "Def",
+ .references => "Refs",
+ .explain => "Lspwhy",
+ .callstack => "Callstack",
+ .incoming_calls => "Callers",
+ .outgoing_calls => "Callees",
+ .document_symbols => "Symbols",
+ .workspace_symbols => "WsSymbols",
+ .diagnostics => "Diagnostics",
+ .workspace_diagnostics => "WsDiagnostics",
+ .code_action => "CodeAction",
+ .select_refs => "SelectRefs",
+ .supertypes => "Supertypes",
+ .subtypes => "Subtypes",
+ .rename => "Rename",
+ .format => "Format",
+ .index => "Index",
+ else => @tagName(kind),
+ };
+}
+
+pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
+ defer pardes.turn.bump(&pardes.turn.lsp_answers);
+ const w = p.lsp_wait orelse return;
+ if (w.id != id) return; // superseded by a newer press, or the pane died
+ p.lsp_wait = null;
+ const pane = p.panes[w.pane] orelse return;
+ if (pane.serial != w.serial) return;
+ // Whatever fails from here -- no answer, nothing found, no room for
+ // its pane -- fails a 9P write that asked it too.
+ const failures = p.fs.failures;
+ defer if (p.fs.failures != failures) p.noteLateFailure(w.pane);
+ var said: [256]u8 = undefined;
+ const rows = response orelse
+ return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: the language server did not answer", .{lspWord(w.kind)}) catch "no answer");
+ // A backend that cannot answer it says why (`@none <why>`).
+ if (std.mem.startsWith(u8, rows, "@none ")) {
+ const why = std.mem.trimEnd(u8, rows["@none ".len..], "\n");
+ return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), why[0..@min(why.len, 200)] }) catch "no answer");
+ }
+ // Index's answer is its indexer's command line, run in a command
+ // pane (lsp_client.indexCommand).
+ if (w.kind == .index) {
+ if (std.mem.startsWith(u8, rows, "@run ")) _ = exec.execute(p, w.pane, std.mem.trimEnd(u8, rows["@run ".len..], "\n"));
+ return;
+ }
+ 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 (applyLspEdits(p, pane, w.revision, edits)) {
+ var buf: [64]u8 = undefined;
+ const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted";
+ p.setMessage(w.pane, std.fmt.bufPrint(&buf, "{s} {d} range(s)", .{ verb, edits.len }) catch verb);
+ }
+ return;
+ }
+ if (w.kind == .rename and rows.len > 0) {
+ // fall through: a multi-file rename previews as rows
+ } else if (w.kind == .format and rows.len > 0) {
+ // fall through: "cannot format" and friends are prose
+ } else if (w.kind == .format) return; // a rename of nothing says so, below
+ }
+ if (rows.len == 0) {
+ if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and
+ pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p, &pane.body);
+ // Nothing found fails, but for a file with no diagnostics,
+ // which is no failure, and a completion's Tab.
+ const none: ?[]const u8 = switch (w.kind) {
+ .completion, .format => null,
+ .rename => "nothing here to rename",
+ .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, std.fmt.bufPrint(&said, "{s}: none", .{lspWord(w.kind)}) catch "none"),
+ .incoming_calls => "callers not found",
+ .outgoing_calls => "callees not found",
+ .hover => "nothing to show: not found",
+ else => "not found",
+ };
+ if (none) |text| p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), text }) catch "nothing found");
+ return;
+ }
+
+ const from: panes.Output.Origin = .{ .query = w.kind };
+ const nrows = std.mem.count(u8, 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];
+ p.look_missed = false;
+ look.lookAt(p, w.pane, place);
+ // The one place is the text's places, as a list's would be: tinted,
+ // and n and N step it.
+ const spot = look.parsePathLine(place);
+ if (!p.look_missed and spot.at.line > 0) if (p.panes[p.active]) |there| if (there.file) |*tf| if (spot.at.line <= panes.File.nlines(p.gpa, tf)) {
+ const ls = panes.File.lineStart(p.gpa, tf, spot.at.line - 1);
+ const line = tf.content[ls .. std.mem.indexOfScalarPos(u8, tf.content, ls, '\n') orelse tf.content.len];
+ const col = @min(spot.at.col -| 1, line.len);
+ // To its end when the server said it, else the word there.
+ const end = if (spot.at.end_line == spot.at.line and spot.at.end_col > col) @min(spot.at.end_col, line.len) else if (look.expandedWord(line, col)) |word| word.hi else col + 1;
+ if (ls + end <= tf.content.len) there.places.feed(p, there, 0, &.{.{ .start = ls + col, .end = ls + end }}, ls + col);
+ };
+ // A word that asks for a list (Callers, Refs) with one answer
+ // jumps to it with no list: where it went is said, as the list
+ // would have shown it. A definition's jump is the answer itself.
+ const listing = switch (w.kind) {
+ .references, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true,
+ else => false,
+ };
+ if (listing and !p.look_missed) {
+ var where: [300]u8 = undefined;
+ p.setMessage(p.active, std.fmt.bufPrint(&where, "{s}: the one, {s}", .{ lspWord(w.kind), place[0..@min(place.len, 240)] }) catch lspWord(w.kind));
+ }
+ return;
+ }
+
+ // The lists of places: into the asking text's query pane (made or
+ // reused), line 1 their word, the places in that text its places.
+ const listed: ?panes.Query.Source = switch (w.kind) {
+ .references => .refs,
+ .definition => .defs,
+ .implementation => .impls,
+ .diagnostics => .diagnostics,
+ else => null,
+ };
+ if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) {
+ p.fs.refilled = null;
+ panes.Query.fillList(p, w.pane, source, rows);
+ p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null;
+ return;
+ };
+ const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice();
+ const content = p.gpa.dupe(u8, rows) catch return;
+ const serial_before = p.next_serial;
+ p.fs.refilled = null;
+ panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| {
+ p.reportError(w.pane, "language response", err);
+ return;
+ };
+ if (rows.len >= 1 << 20) memory.trim();
+ // What a 9P write that asked it answers: the pane the rows are in
+ // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled
+ // again, not the pane it was asked from.
+ p.fs.lsp_result = if (p.next_serial != serial_before) p.next_serial else p.fs.refilled;
+ if (w.kind == .callstack) {
+ for (p.panes, 0..) |slot, result_id| if (slot) |result_pane| {
+ if (result_pane.serial != p.fs.lsp_result) continue;
+ if (p.next_serial != serial_before) {
+ const report_rows = std.mem.count(u8, result_pane.file.?.content, "\n");
+ const wanted: u16 = @intCast(@min(p.screen_h, report_rows + result_pane.tag_rows));
+ layout.givePaneRows(p, result_id, wanted, w.pane);
+ }
+ look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep);
+ break;
+ };
+ }
+ if (w.kind == .rename) {
+ var said_buf: [128]u8 = undefined;
+ // Rows that only name a file the server left alone (lsp_client
+ // renameEdits) are no edits.
+ const unrenamed = std.mem.count(u8, rows, ", which the server did not rename\n");
+ p.setMessage(w.pane, if (unrenamed > 0)
+ std.fmt.bufPrint(&said_buf, "Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed}) catch "Rename: previewed"
+ else
+ std.fmt.bufPrint(&said_buf, "Rename: {d} edit(s) across files, previewed, not applied", .{nrows}) catch "Rename: previewed");
+ }
+ if (panes.Output.traits(from).jumps) {
+ const result = p.panes[pane.search_pane orelse return] orelse return;
+ const file = pane.file orelse return;
+ const row = panes.Output.nextResult(result.file.?.content, result.file.?.location_rows, lsp.rel(dir, file.path), .{
+ .line = @as(usize, @intCast(@max(0, w.row))) + 1,
+ .col = @as(usize, @intCast(@max(0, w.col))) + 1,
+ });
+ _ = look.jumpResult(p, w.pane, row);
+ }
+}
+
+test "Lspwhy after a Hover asks to explain that hover, in its file at its place, run from any pane" {
+ if (!lsp.supports.contains(.hover)) return error.SkipZigTest;
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("const a = 1;\nconst b = a;\n");
+ const f = &pane.file.?;
+ p.gpa.free(f.path);
+ f.path = try p.gpa.dupe(u8, "/tmp/x.zig");
+ while (p.nextEffect()) |_| {}
+ pane.body.cur_row = 1;
+ pane.body.cur_col = 10;
+ p.lspRequest(0, .hover, "");
+ var hover_at: u32 = 0;
+ while (p.nextEffect()) |e| if (e == .lsp) {
+ hover_at = e.lsp.offset;
+ };
+ pane.body.cur_row = 0;
+ pane.body.cur_col = 0;
+ p.lsp_wait = null;
+ // Run from another file's pane: still the hover's file and place.
+ const other = p.freeSlot().?;
+ _ = try p.openTutorView(other);
+ p.lspRequest(other, .explain, "");
+ var seen = false;
+ while (p.nextEffect()) |e| if (e == .lsp) {
+ try std.testing.expectEqual(lsp.Kind.explain, e.lsp.kind);
+ try std.testing.expectEqualStrings("hover ", e.lsp.arg.slice());
+ try std.testing.expectEqual(hover_at, e.lsp.offset);
+ try std.testing.expectEqual(@as(u8, 0), e.lsp.pane);
+ seen = true;
+ };
+ try std.testing.expect(seen);
+}
+
+test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all run them" {
+ if (!lsp.supports.contains(.definition)) return error.SkipZigTest;
+ const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 24, .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("const alpha = 1;\nconst beta = alpha;\n");
+ // A .txt has no server: no Def, no Refs.
+ try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), "Def") == null);
+ const f = &pane.file.?;
+ p.gpa.free(f.path);
+ f.path = try p.gpa.dupe(u8, "/tmp/x.zig");
+ try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs Del"));
+ p.sync();
+ while (p.nextEffect()) |_| {}
+ const Asked = struct {
+ fn one(q: *Pardes, kind: lsp.Kind) !u32 {
+ var at: ?u32 = null;
+ while (q.nextEffect()) |e| if (e == .lsp) {
+ try std.testing.expectEqual(kind, e.lsp.kind);
+ try std.testing.expectEqualStrings("", e.lsp.arg.slice());
+ try std.testing.expect(at == null);
+ at = e.lsp.offset;
+ };
+ q.lsp_wait = null;
+ return at orelse error.NothingAsked;
+ }
+ };
+ // gd and gr: at the cursor, on `alpha`'s declaration.
+ pane.body.cur_row = 0;
+ pane.body.cur_col = 8;
+ p.update(.{ .key = .{ .cp = 'g' } });
+ p.update(.{ .key = .{ .cp = 'd' } });
+ try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .definition));
+ p.update(.{ .key = .{ .cp = 'g' } });
+ p.update(.{ .key = .{ .cp = 'r' } });
+ try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .references));
+ p.update(.{ .key = .{ .cp = 'g' } });
+ p.update(.{ .key = .{ .cp = 'c' } });
+ try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .callstack));
+
+ const r = p.rects[0];
+ const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane);
+ const use_y = p.bodyTop(pane, r) + 1;
+ // Copied out of the scratch arena, which each p.update resets.
+ const tag = try std.testing.allocator.dupe(u8, try tagline.tagText(p, p.scratch.allocator(), pane));
+ defer std.testing.allocator.free(tag);
+ for ([_]struct { word: []const u8, kind: lsp.Kind }{ .{ .word = " Def ", .kind = .definition }, .{ .word = " Refs", .kind = .references } }) |w| {
+ // B1 sweeps the use of `alpha` on the second line (bytes 30..35),
+ // leaving the cursor at its far end.
+ p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x0 + 13, .row = use_y } });
+ p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x0 + 17, .row = use_y } });
+ p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x0 + 17, .row = use_y } });
+ // B2 on the tag word, B1 clicked while it is held: the sweep is its
+ // argument, and it asks at the start of `alpha`, not at the cursor.
+ const wx = r.x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, w.word).? + 1));
+ p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } });
+ p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = wx, .row = r.y } });
+ p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = wx, .row = r.y } });
+ p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } });
+ try std.testing.expectEqual(@as(u32, 30), try Asked.one(p, w.kind));
+ // Clicked bare, it asks at the cursor, where the sweep left it.
+ pane.body.cur_row = 0;
+ pane.body.cur_col = 2;
+ p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } });
+ p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } });
+ try std.testing.expectEqual(@as(u32, 2), try Asked.one(p, w.kind));
+ }
+ // A symbol the file does not hold is said, and nothing is asked.
+ exec.runBuiltin(p, .Def, 0, "", "gamma");
+ try std.testing.expectError(error.NothingAsked, Asked.one(p, .definition));
+ try std.testing.expectEqualStrings("Def: no gamma in this file", pane.msg[0..pane.msg_len]);
+}
+
+test "Callstack always opens and focuses its own pane, reusing it for another symbol" {
+ if (!lsp.supports.contains(.callstack)) return;
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ _ = try p.setTestFile("fn work() {}\n");
+ const source = p.panes[0].?;
+ p.lspRequest(0, .callstack, "");
+ const first = p.lsp_wait orelse return error.NoRequest;
+ lspResponse(p, first.id, "╰──┬ /test.txt:1:4-7 work\n@callstack-match ╰─ /test.txt:1:4-7 fn work() {}\n");
+ const report = p.panes[p.active].?;
+ try std.testing.expect(report != source);
+ try std.testing.expect(std.mem.endsWith(u8, report.file.?.path, "/+Callstack"));
+ try std.testing.expectEqual(@as(i32, 0), source.body.cur_row);
+ const stale_selection = std.mem.indexOfScalar(u8, report.file.?.content, '\n').? + 1;
+ report.body.setRange(report.file.?.content, 0, .{ .anchor = stale_selection, .head = stale_selection + 6 }, true);
+ layout.toggleCollapse(p, 0);
+ var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer frame.deinit();
+ const surface = try p.render(frame.allocator());
+ p.presented();
+ const r = p.rects[p.active];
+ const row = r.y + report.tag_rows;
+ const col = r.x + config.GUTTER + panes.File.gutterWidth(report) + 7;
+ try std.testing.expectEqual(.off, surface.at(col, row).style.ul);
+ p.update(.{ .mouse = .{ .button = .right, .kind = .press, .row = row, .col = col } });
+ p.update(.{ .mouse = .{ .button = .right, .kind = .release, .row = row, .col = col } });
+ try std.testing.expect(!source.collapsed);
+ try std.testing.expectEqual(@as(usize, 0), p.active);
+ try std.testing.expect(!report.body.vsel.active);
+ try std.testing.expectEqual(@as(usize, 0), report.body.nsel);
+ const serial = report.serial;
+ p.lspRequest(0, .callstack, "");
+ const second = p.lsp_wait orelse return error.NoRequest;
+ lspResponse(p, second.id, "No callers reported\n");
+ try std.testing.expectEqual(serial, p.panes[p.active].?.serial);
+ try std.testing.expectEqualStrings("No callers reported\n", p.panes[p.active].?.file.?.content);
+}
+
+test "Callers with one answer jumps to it and says where, in a msg" {
+ if (!lsp.supports.contains(.incoming_calls)) return;
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("fn a() {}\nfn b() { a(); }\n");
+ p.lspRequest(p.active, .incoming_calls, "");
+ const wait = p.lsp_wait.?;
+ p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = "/test.txt:2:10 b\n" } });
+ try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
+ try std.testing.expectEqualStrings("Callers: the one, /test.txt:2:10", pane.msg[0..pane.msg_len]);
+}
+
+test "a Rename the language server finds nothing for says so, and changes nothing" {
+ if (!lsp.supports.contains(.rename)) return;
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("const value=1;\n");
+ p.lspRequest(p.active, .rename, "renamed");
+ const wait = p.lsp_wait.?;
+ p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = "" } });
+ try std.testing.expectEqualStrings("Rename: nothing here to rename", pane.msg[0..pane.msg_len]);
+ try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content);
+}
+
+test "LSP failure clears only its matching wait without completion indentation" {
+ if (!lsp.supports.contains(.completion)) return;
+ const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ const pane = try p.setTestFile("x");
+ pane.body.mode = .insert;
+ pane.body.cur_col = 1;
+
+ p.lspRequest(p.active, .completion, "");
+ const old_id = p.lsp_wait.?.id;
+ p.lspRequest(p.active, .completion, "");
+ const current_id = p.lsp_wait.?.id;
+ p.update(.{ .lsp_resp = .{ .id = old_id, .rows = null } });
+ try std.testing.expectEqual(current_id, p.lsp_wait.?.id);
+ p.update(.{ .lsp_resp = .{ .id = current_id, .rows = null } });
+ try std.testing.expect(p.lsp_wait == null);
+ try std.testing.expectEqualStrings("x", pane.file.?.content);
+ try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
+
+ p.lspRequest(p.active, .completion, "");
+ p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "" } });
+ try std.testing.expect(p.lsp_wait == null);
+ try std.testing.expectEqualStrings("x ", pane.file.?.content);
+ try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
+}
diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig
index e307a40d..eefa27c9 100644
--- a/src/lsp/lsp.zig
+++ b/src/lsp/lsp.zig
@@ -1,5 +1,8 @@
const std = @import("std");
+/// The core's side of a question to the servers (Ask.zig).
+pub const Ask = @import("Ask.zig");
+
pub const Kind = enum {
definition,
declaration,
diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig
index 3393c851..4cb4728f 100644
--- a/src/ninep/ctl.zig
+++ b/src/ninep/ctl.zig
@@ -18,6 +18,7 @@ const exec_line = @import("../exec.zig");
const tree = @import("tree.zig");
const pane_files = @import("pane.zig");
const keys = @import("../keys.zig");
+const Ask = @import("../lsp/Ask.zig");
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
@@ -2118,22 +2119,22 @@ test "a language server question that finds nothing, cannot be answered, or is a
p.fs.late_failure_len = 0;
p.lspRequest(id, .incoming_calls, "");
try testing.expect(p.lsp_wait != null);
- p.lspResponse(p.lsp_wait.?.id, "");
+ Ask.lspResponse(p, p.lsp_wait.?.id, "");
try testing.expectEqualStrings("Callers: callers not found", p.fs.late_failure[0..p.fs.late_failure_len]);
// A backend that cannot answer says why.
p.fs.late_failure_len = 0;
p.lspRequest(id, .outgoing_calls, "");
- p.lspResponse(p.lsp_wait.?.id, "@none zls does not answer call hierarchy\n");
+ Ask.lspResponse(p, p.lsp_wait.?.id, "@none zls does not answer call hierarchy\n");
try testing.expectEqualStrings("Callees: zls does not answer call hierarchy", p.fs.late_failure[0..p.fs.late_failure_len]);
// No answer at all.
p.fs.late_failure_len = 0;
p.lspRequest(id, .hover, "");
- p.lspResponse(p.lsp_wait.?.id, null);
+ Ask.lspResponse(p, p.lsp_wait.?.id, null);
try testing.expectEqualStrings("Hover: the language server did not answer", p.fs.late_failure[0..p.fs.late_failure_len]);
// No diagnostics is no failure.
p.fs.late_failure_len = 0;
p.lspRequest(id, .diagnostics, "");
- p.lspResponse(p.lsp_wait.?.id, "");
+ Ask.lspResponse(p, p.lsp_wait.?.id, "");
try testing.expectEqual(@as(u16, 0), p.fs.late_failure_len);
// An image's body takes no write.
const slot = p.freeSlot().?;
@@ -2802,7 +2803,7 @@ test "a Rename that reaches other files previews them, says so, and is the pane
const id = p.active;
p.fs.lsp_result = null;
p.lspRequest(id, .rename, "sum");
- p.lspResponse(p.lsp_wait.?.id, "lib.rs:2:8 sum\nmain.rs:4:13-15 sum\n");
+ Ask.lspResponse(p, p.lsp_wait.?.id, "lib.rs:2:8 sum\nmain.rs:4:13-15 sum\n");
const preview = p.panes[p.panes[id].?.search_pane.?].?;
try testing.expectEqual(preview.serial, p.fs.lsp_result.?);
try testing.expect(th.logHas(p, "Rename: 2 edit(s) across files, previewed, not applied"));
@@ -2849,7 +2850,7 @@ test "a Rename the server answered for this file alone, with other open files sa
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
p.lspRequest(p.active, .rename, "sum");
- p.lspResponse(p.lsp_wait.?.id, "util.zig:1:8 sum\nmain.zig: also says add, which the server did not rename\n");
+ Ask.lspResponse(p, p.lsp_wait.?.id, "util.zig:1:8 sum\nmain.zig: also says add, which the server did not rename\n");
try testing.expect(th.logHas(p, "Rename: previewed, not applied: the server renamed in this file only, and 1 other open file(s) say the name"));
}
@@ -2889,7 +2890,7 @@ test "Lspinfo's answer is the +Lsp pane it fills, as a Rename preview's is its +
defer p.deinit();
p.fs.lsp_result = null;
p.lspRequest(p.active, .status, "");
- p.lspResponse(p.lsp_wait.?.id, "language servers:\n");
+ Ask.lspResponse(p, p.lsp_wait.?.id, "language servers:\n");
const shown = p.paneBySerial(p.fs.lsp_result.?).?;
try testing.expect(std.mem.endsWith(u8, p.panes[shown].?.file.?.path, "+Lsp"));
}
diff --git a/src/pardes.zig b/src/pardes.zig
index 55b0832f..5add3f68 100644
--- a/src/pardes.zig
+++ b/src/pardes.zig
@@ -281,6 +281,7 @@ test "a compact tagline anchors at its own pane, and both shells step from the s
test {
_ = @import("rollback.zig");
+ _ = @import("lsp/Ask.zig");
_ = @import("Jump.zig");
_ = @import("keys.zig");
_ = @import("Effect.zig");
@@ -768,112 +769,6 @@ test "a frame no one watches is not drawn, and is drawn once someone does" {
try std.testing.expectEqual(@as(usize, 1), Watch.presents);
}
-test "Lspwhy after a Hover asks to explain that hover, in its file at its place, run from any pane" {
- if (!lsp.supports.contains(.hover)) return error.SkipZigTest;
- const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- const pane = try p.setTestFile("const a = 1;\nconst b = a;\n");
- const f = &pane.file.?;
- p.gpa.free(f.path);
- f.path = try p.gpa.dupe(u8, "/tmp/x.zig");
- while (p.nextEffect()) |_| {}
- pane.body.cur_row = 1;
- pane.body.cur_col = 10;
- p.lspRequest(0, .hover, "");
- var hover_at: u32 = 0;
- while (p.nextEffect()) |e| if (e == .lsp) {
- hover_at = e.lsp.offset;
- };
- pane.body.cur_row = 0;
- pane.body.cur_col = 0;
- p.lsp_wait = null;
- // Run from another file's pane: still the hover's file and place.
- const other = p.freeSlot().?;
- _ = try p.openTutorView(other);
- p.lspRequest(other, .explain, "");
- var seen = false;
- while (p.nextEffect()) |e| if (e == .lsp) {
- try std.testing.expectEqual(lsp.Kind.explain, e.lsp.kind);
- try std.testing.expectEqualStrings("hover ", e.lsp.arg.slice());
- try std.testing.expectEqual(hover_at, e.lsp.offset);
- try std.testing.expectEqual(@as(u8, 0), e.lsp.pane);
- seen = true;
- };
- try std.testing.expect(seen);
-}
-
-test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all run them" {
- if (!lsp.supports.contains(.definition)) return error.SkipZigTest;
- const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 24, .tty_only = true });
- defer p.deinit();
- const pane = try p.setTestFile("const alpha = 1;\nconst beta = alpha;\n");
- // A .txt has no server: no Def, no Refs.
- try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), "Def") == null);
- const f = &pane.file.?;
- p.gpa.free(f.path);
- f.path = try p.gpa.dupe(u8, "/tmp/x.zig");
- try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs Del"));
- p.sync();
- while (p.nextEffect()) |_| {}
- const Asked = struct {
- fn one(q: *Pardes, kind: lsp.Kind) !u32 {
- var at: ?u32 = null;
- while (q.nextEffect()) |e| if (e == .lsp) {
- try std.testing.expectEqual(kind, e.lsp.kind);
- try std.testing.expectEqualStrings("", e.lsp.arg.slice());
- try std.testing.expect(at == null);
- at = e.lsp.offset;
- };
- q.lsp_wait = null;
- return at orelse error.NothingAsked;
- }
- };
- // gd and gr: at the cursor, on `alpha`'s declaration.
- pane.body.cur_row = 0;
- pane.body.cur_col = 8;
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'd' } });
- try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .definition));
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'r' } });
- try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .references));
- p.update(.{ .key = .{ .cp = 'g' } });
- p.update(.{ .key = .{ .cp = 'c' } });
- try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .callstack));
-
- const r = p.rects[0];
- const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane);
- const use_y = p.bodyTop(pane, r) + 1;
- // Copied out of the scratch arena, which each p.update resets.
- const tag = try std.testing.allocator.dupe(u8, try tagline.tagText(p, p.scratch.allocator(), pane));
- defer std.testing.allocator.free(tag);
- for ([_]struct { word: []const u8, kind: lsp.Kind }{ .{ .word = " Def ", .kind = .definition }, .{ .word = " Refs", .kind = .references } }) |w| {
- // B1 sweeps the use of `alpha` on the second line (bytes 30..35),
- // leaving the cursor at its far end.
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x0 + 13, .row = use_y } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x0 + 17, .row = use_y } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x0 + 17, .row = use_y } });
- // B2 on the tag word, B1 clicked while it is held: the sweep is its
- // argument, and it asks at the start of `alpha`, not at the cursor.
- const wx = r.x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, w.word).? + 1));
- p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = wx, .row = r.y } });
- p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = wx, .row = r.y } });
- p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } });
- try std.testing.expectEqual(@as(u32, 30), try Asked.one(p, w.kind));
- // Clicked bare, it asks at the cursor, where the sweep left it.
- pane.body.cur_row = 0;
- pane.body.cur_col = 2;
- p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } });
- p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } });
- try std.testing.expectEqual(@as(u32, 2), try Asked.one(p, w.kind));
- }
- // A symbol the file does not hold is said, and nothing is asked.
- exec.runBuiltin(p, .Def, 0, "", "gamma");
- try std.testing.expectError(error.NothingAsked, Asked.one(p, .definition));
- try std.testing.expectEqualStrings("Def: no gamma in this file", pane.msg[0..pane.msg_len]);
-}
-
test "the Tutor pane is named +Tutor in the session's directory, never a bare path at the root" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
defer p.deinit();
@@ -2896,6 +2791,10 @@ pub const Pardes = struct {
/// `p.executeBuiltinLine(...)`; it lives with the rest of exec in exec.zig.
pub const executeBuiltinLine = exec.executeBuiltinLine;
+ /// A language word's request, called from every word and test as
+ /// `p.lspRequest(...)`; it lives with its answer in lsp/Ask.zig.
+ pub const lspRequest = @import("lsp/Ask.zig").lspRequest;
+
/// Performing an effect, called from every host and test as
/// `p.perform(e)`; it lives with the effects in Effect.zig.
pub const perform = @import("Effect.zig").perform;
@@ -4334,7 +4233,7 @@ pub const Pardes = struct {
pane.body.mode = .normal;
p.reportError(e.pane, "terminal exited; Del retries close", err);
},
- .lsp_resp => |r| p.lspResponse(r.id, r.rows),
+ .lsp_resp => |r| @import("lsp/Ask.zig").lspResponse(p, r.id, r.rows),
.pipe_resp => |r| Pipe.pipeResponse(p, r.id, r.success, r.outputs, r.failure),
.search => |b| Stream.receive(p, &b),
.file_changed => |fc| _ = p.applyWatchedFileChanged(fc.pane, fc.bytes),
@@ -4524,231 +4423,6 @@ pub const Pardes = struct {
pub const SavePath = Effect.Buf(effect_path_cap);
- pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void {
- var arg = arg_in;
- if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary
- // Lspwhy narrates the last query where it was asked -- that pane's
- // file, place and argument -- from wherever it is run.
- const last_pane: ?usize = if (kind == .explain) (if (p.lsp_last) |last| p.paneBySerial(last.serial) else null) else null;
- const id = last_pane orelse asked;
- var said: [128]u8 = undefined;
- if (!lsp.supports.contains(kind))
- return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no language server here answers it", .{lspWord(kind)}) catch "no language server answers it");
- const pane = p.panes[id] orelse return;
- if (kind != .status) {
- const f = pane.file orelse
- return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks");
- if (f.output != null)
- return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: only a file's pane asks a language server", .{lspWord(kind)}) catch "only a file's pane asks");
- }
- if (arg.len > 128) return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: its argument is at most 128 bytes", .{lspWord(kind)}) catch "argument too long");
- if (kind == .rename) {
- const zig_buf = if (pane.file) |f| std.mem.endsWith(u8, f.path, ".zig") else true;
- if ((zig_buf and (!std.zig.isValidId(arg) or std.zig.isUnderscore(arg))) or
- (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null))
- return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name");
- }
- var off = if (pane.file) |f| modal.offsetAt(f.content, .{
- .row = @intCast(@max(0, pane.body.cur_row)),
- .col = @intCast(@max(0, pane.body.cur_col)),
- }) else 0;
- // Def or Refs given a symbol (a 2-1 chord's selection) asks at its
- // occurrence nearest the cursor, which a sweep leaves at one end of
- // what it selected; the server is asked at a place, never a name.
- if ((kind == .definition or kind == .references) and arg.len > 0) {
- const content = pane.file.?.content;
- var nearest: ?usize = null;
- var best: usize = 0;
- var from: usize = 0;
- while (std.mem.indexOfPos(u8, content, from, arg)) |at_hit| : (from = at_hit + 1) {
- const d = if (at_hit > off) at_hit - off else off -| (at_hit + arg.len);
- if (nearest != null and at_hit > off and d >= best) break;
- if (nearest == null or d < best) {
- nearest = at_hit;
- best = d;
- }
- }
- off = nearest orelse
- return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch "no such symbol in this file");
- arg = "";
- }
- // Lspwhy asks the last query again, narrated: its kind and argument,
- // at its place when asked from its pane. None yet: a definition.
- var explained: [160]u8 = undefined;
- var sent = arg;
- var at = off;
- if (kind == .explain) {
- if (p.lsp_last) |last| {
- sent = std.fmt.bufPrint(&explained, "{s} {s}", .{ @tagName(last.kind), last.arg.slice() }) catch "";
- if (last_pane != null) at = last.offset;
- }
- } else if (kind != .status) p.lsp_last = .{ .kind = kind, .arg = .from(arg), .serial = pane.serial, .offset = @intCast(off) };
- p.lsp_seq +%= 1;
- // A 9P write that asked it is answered once the answer is in.
- if (p.fs.serving) p.fs.lsp_answer_at = turn.lsp_answers;
- p.lsp_wait = .{
- .id = p.lsp_seq,
- .kind = kind,
- .pane = id,
- .serial = pane.serial,
- .revision = if (pane.file) |f| f.revision else 0,
- .arg = .from(arg),
- .row = pane.body.cur_row,
- .col = pane.body.cur_col,
- };
- p.emit(.{ .lsp = .{
- .id = p.lsp_seq,
- .kind = kind,
- .pane = @intCast(id),
- .offset = @intCast(at),
- .arg = .from(sent),
- } });
- }
-
- const LspEdit = struct { start: usize, end: usize, text: []const u8 };
-
- fn parseLspEdits(p: *Pardes, 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;
- var form: enum { undecided, edit, put } = .undecided;
- while (lines.next()) |line| {
- if (line.len == 0) {
- if (lines.peek() == null) break;
- return null;
- }
- var fields = std.mem.tokenizeScalar(u8, line, ' ');
- const head = fields.next() orelse return null;
- const want: @TypeOf(form) = if (std.mem.eql(u8, head, "@put"))
- .put
- else if (std.mem.eql(u8, head, "@edit"))
- .edit
- else
- return null;
- if (form == .undecided) form = want;
- if (form != want) return null;
- const start = std.fmt.parseInt(usize, fields.next() orelse return null, 10) catch return null;
- const end = std.fmt.parseInt(usize, fields.next() orelse return null, 10) catch return null;
- var text: []const u8 = if (want == .edit) (fallback orelse return null) else "";
- if (want == .put) {
- if (fields.next()) |encoded| text = decodePct(a, encoded) orelse return null;
- }
- if (fields.next() != null) return null;
- edits[n] = .{ .start = start, .end = end, .text = text };
- n += 1;
- }
- return if (n == 0) null else edits[0..n];
- }
-
- /// The `@put` text codec's read half (lsp.put writes it): `%XX` bytes,
- /// everything else literal. An invalid escape fails the whole record.
- fn decodePct(a: std.mem.Allocator, encoded: []const u8) ?[]const u8 {
- const out = a.alloc(u8, encoded.len) catch return null;
- var n: usize = 0;
- var i: usize = 0;
- while (i < encoded.len) {
- if (encoded[i] == '%') {
- if (i + 3 > encoded.len) return null;
- out[n] = std.fmt.parseInt(u8, encoded[i + 1 .. i + 3], 16) catch return null;
- i += 3;
- } else {
- out[n] = encoded[i];
- i += 1;
- }
- n += 1;
- }
- return out[0..n];
- }
-
- fn mapLspEditOffset(edits: []const LspEdit, old: usize) usize {
- var old_at: usize = 0;
- var new_at: usize = 0;
- for (edits) |e| {
- if (old < e.start) return new_at + (old - old_at);
- new_at += e.start - old_at;
- if (old < e.end) return new_at + @min(old - e.start, e.text.len -| 1);
- new_at += e.text.len;
- if (old == e.end) return new_at;
- old_at = e.end;
- }
- return new_at + (old - old_at);
- }
-
- fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) bool {
- const f = if (pane.file) |*file| file else return false;
- if (f.revision != revision) return false;
-
- var removed: usize = 0;
- var added: usize = 0;
- var previous_end: usize = 0;
- var same = true;
- for (edits) |e| {
- if (e.start < previous_end or e.start > e.end or e.end > f.content.len) return false;
- if (e.start == e.end and e.text.len == 0) return false; // an empty insert is a malformed record
- removed = std.math.add(usize, removed, e.end - e.start) catch return false;
- added = std.math.add(usize, added, e.text.len) catch return false;
- previous_end = e.end;
- if (same and !std.mem.eql(u8, f.content[e.start..e.end], e.text)) same = false;
- }
- if (same) return false; // a no-op response earns no undo entry
- const final_len = std.math.add(usize, f.content.len - removed, added) catch return false;
- const replacement = p.gpa.alloc(u8, final_len) catch return false;
-
- const old_cursor = modal.offsetAt(f.content, .{
- .row = @intCast(@max(0, pane.body.cur_row)),
- .col = @intCast(@max(0, pane.body.cur_col)),
- });
- const mapped_cursor = mapLspEditOffset(edits, old_cursor);
- var read_at: usize = 0;
- var write_at: usize = 0;
- for (edits) |e| {
- @memcpy(replacement[write_at .. write_at + (e.start - read_at)], f.content[read_at..e.start]);
- write_at += e.start - read_at;
- @memcpy(replacement[write_at .. write_at + e.text.len], e.text);
- write_at += e.text.len;
- read_at = e.end;
- }
- @memcpy(replacement[write_at..], f.content[read_at..]);
-
- edit.pushUndo(p, &pane.body);
- panes.File.setContent(p, f, replacement);
- const cursor = modal.positionAt(f.content, mapped_cursor);
- pane.body.cur_row = @intCast(cursor.row);
- pane.body.cur_col = @intCast(cursor.col);
- pane.body.vsel.active = false;
- pane.body.select = false;
- pane.body.sticky_col = -1;
- pane.ensureCursorVisible();
- return true;
- }
-
- /// The builtin word that asks `kind`, for what it says.
- fn lspWord(kind: lsp.Kind) []const u8 {
- return switch (kind) {
- .hover => "Hover",
- .definition => "Def",
- .references => "Refs",
- .explain => "Lspwhy",
- .callstack => "Callstack",
- .incoming_calls => "Callers",
- .outgoing_calls => "Callees",
- .document_symbols => "Symbols",
- .workspace_symbols => "WsSymbols",
- .diagnostics => "Diagnostics",
- .workspace_diagnostics => "WsDiagnostics",
- .code_action => "CodeAction",
- .select_refs => "SelectRefs",
- .supertypes => "Supertypes",
- .subtypes => "Subtypes",
- .rename => "Rename",
- .format => "Format",
- .index => "Index",
- else => @tagName(kind),
- };
- }
-
/// What was said of a failure just now on pane `id` is also the waiting
/// 9P write's (9p_io, `fs.late_failure`).
pub fn noteLateFailure(p: *Pardes, id: usize) void {
@@ -4764,158 +4438,6 @@ pub const Pardes = struct {
p.fs.late_failure_len = @intCast(kept.len);
}
- pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void {
- defer turn.bump(&turn.lsp_answers);
- const w = p.lsp_wait orelse return;
- if (w.id != id) return; // superseded by a newer press, or the pane died
- p.lsp_wait = null;
- const pane = p.panes[w.pane] orelse return;
- if (pane.serial != w.serial) return;
- // Whatever fails from here -- no answer, nothing found, no room for
- // its pane -- fails a 9P write that asked it too.
- const failures = p.fs.failures;
- defer if (p.fs.failures != failures) p.noteLateFailure(w.pane);
- var said: [256]u8 = undefined;
- const rows = response orelse
- return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: the language server did not answer", .{lspWord(w.kind)}) catch "no answer");
- // A backend that cannot answer it says why (`@none <why>`).
- if (std.mem.startsWith(u8, rows, "@none ")) {
- const why = std.mem.trimEnd(u8, rows["@none ".len..], "\n");
- return p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), why[0..@min(why.len, 200)] }) catch "no answer");
- }
- // Index's answer is its indexer's command line, run in a command
- // pane (lsp_client.indexCommand).
- if (w.kind == .index) {
- if (std.mem.startsWith(u8, rows, "@run ")) _ = exec.execute(p, w.pane, std.mem.trimEnd(u8, rows["@run ".len..], "\n"));
- return;
- }
- if (w.kind == .rename or w.kind == .format) {
- const fallback: ?[]const u8 = if (w.kind == .rename) w.arg.slice() else null;
- if (p.parseLspEdits(rows, fallback)) |edits| {
- if (p.applyLspEdits(pane, w.revision, edits)) {
- var buf: [64]u8 = undefined;
- const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted";
- p.setMessage(w.pane, std.fmt.bufPrint(&buf, "{s} {d} range(s)", .{ verb, edits.len }) catch verb);
- }
- return;
- }
- if (w.kind == .rename and rows.len > 0) {
- // fall through: a multi-file rename previews as rows
- } else if (w.kind == .format and rows.len > 0) {
- // fall through: "cannot format" and friends are prose
- } else if (w.kind == .format) return; // a rename of nothing says so, below
- }
- if (rows.len == 0) {
- if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and
- pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p, &pane.body);
- // Nothing found fails, but for a file with no diagnostics,
- // which is no failure, and a completion's Tab.
- const none: ?[]const u8 = switch (w.kind) {
- .completion, .format => null,
- .rename => "nothing here to rename",
- .diagnostics, .workspace_diagnostics => return p.setMessage(w.pane, std.fmt.bufPrint(&said, "{s}: none", .{lspWord(w.kind)}) catch "none"),
- .incoming_calls => "callers not found",
- .outgoing_calls => "callees not found",
- .hover => "nothing to show: not found",
- else => "not found",
- };
- if (none) |text| p.reportFailure(w.pane, std.fmt.bufPrint(&said, "{s}: {s}", .{ lspWord(w.kind), text }) catch "nothing found");
- return;
- }
-
- const from: panes.Output.Origin = .{ .query = w.kind };
- const nrows = std.mem.count(u8, 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];
- p.look_missed = false;
- look.lookAt(p, w.pane, place);
- // The one place is the text's places, as a list's would be: tinted,
- // and n and N step it.
- const spot = look.parsePathLine(place);
- if (!p.look_missed and spot.at.line > 0) if (p.panes[p.active]) |there| if (there.file) |*tf| if (spot.at.line <= panes.File.nlines(p.gpa, tf)) {
- const ls = panes.File.lineStart(p.gpa, tf, spot.at.line - 1);
- const line = tf.content[ls .. std.mem.indexOfScalarPos(u8, tf.content, ls, '\n') orelse tf.content.len];
- const col = @min(spot.at.col -| 1, line.len);
- // To its end when the server said it, else the word there.
- const end = if (spot.at.end_line == spot.at.line and spot.at.end_col > col) @min(spot.at.end_col, line.len) else if (look.expandedWord(line, col)) |word| word.hi else col + 1;
- if (ls + end <= tf.content.len) there.places.feed(p, there, 0, &.{.{ .start = ls + col, .end = ls + end }}, ls + col);
- };
- // A word that asks for a list (Callers, Refs) with one answer
- // jumps to it with no list: where it went is said, as the list
- // would have shown it. A definition's jump is the answer itself.
- const listing = switch (w.kind) {
- .references, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true,
- else => false,
- };
- if (listing and !p.look_missed) {
- var where: [300]u8 = undefined;
- p.setMessage(p.active, std.fmt.bufPrint(&where, "{s}: the one, {s}", .{ lspWord(w.kind), place[0..@min(place.len, 240)] }) catch lspWord(w.kind));
- }
- return;
- }
-
- // The lists of places: into the asking text's query pane (made or
- // reused), line 1 their word, the places in that text its places.
- const listed: ?panes.Query.Source = switch (w.kind) {
- .references => .refs,
- .definition => .defs,
- .implementation => .impls,
- .diagnostics => .diagnostics,
- else => null,
- };
- if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) {
- p.fs.refilled = null;
- panes.Query.fillList(p, w.pane, source, rows);
- p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null;
- return;
- };
- const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice();
- const content = p.gpa.dupe(u8, rows) catch return;
- const serial_before = p.next_serial;
- p.fs.refilled = null;
- panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| {
- p.reportError(w.pane, "language response", err);
- return;
- };
- if (rows.len >= 1 << 20) memory.trim();
- // What a 9P write that asked it answers: the pane the rows are in
- // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled
- // again, not the pane it was asked from.
- p.fs.lsp_result = if (p.next_serial != serial_before) p.next_serial else p.fs.refilled;
- if (w.kind == .callstack) {
- for (p.panes, 0..) |slot, result_id| if (slot) |result_pane| {
- if (result_pane.serial != p.fs.lsp_result) continue;
- if (p.next_serial != serial_before) {
- const report_rows = std.mem.count(u8, result_pane.file.?.content, "\n");
- const wanted: u16 = @intCast(@min(p.screen_h, report_rows + result_pane.tag_rows));
- layout.givePaneRows(p, result_id, wanted, w.pane);
- }
- look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep);
- break;
- };
- }
- if (w.kind == .rename) {
- var said_buf: [128]u8 = undefined;
- // Rows that only name a file the server left alone (lsp_client
- // renameEdits) are no edits.
- const unrenamed = std.mem.count(u8, rows, ", which the server did not rename\n");
- p.setMessage(w.pane, if (unrenamed > 0)
- std.fmt.bufPrint(&said_buf, "Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed}) catch "Rename: previewed"
- else
- std.fmt.bufPrint(&said_buf, "Rename: {d} edit(s) across files, previewed, not applied", .{nrows}) catch "Rename: previewed");
- }
- if (panes.Output.traits(from).jumps) {
- const result = p.panes[pane.search_pane orelse return] orelse return;
- const file = pane.file orelse return;
- const row = panes.Output.nextResult(result.file.?.content, result.file.?.location_rows, lsp.rel(dir, file.path), .{
- .line = @as(usize, @intCast(@max(0, w.row))) + 1,
- .col = @as(usize, @intCast(@max(0, w.col))) + 1,
- });
- _ = look.jumpResult(p, w.pane, row);
- }
- }
-
/// The rows n/N's walk over look-able text reads before it stops (look.zig).
pub const max_look_rows = 8192;
@@ -5742,68 +5264,6 @@ test "tty output follows only from the bottom" {
try std.testing.expect(panes.terminal.scrollbar(sp).offset > live);
}
-test "Callstack always opens and focuses its own pane, reusing it for another symbol" {
- if (!lsp.supports.contains(.callstack)) return;
- const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- _ = try p.setTestFile("fn work() {}\n");
- const source = p.panes[0].?;
- p.lspRequest(0, .callstack, "");
- const first = p.lsp_wait orelse return error.NoRequest;
- p.lspResponse(first.id, "╰──┬ /test.txt:1:4-7 work\n@callstack-match ╰─ /test.txt:1:4-7 fn work() {}\n");
- const report = p.panes[p.active].?;
- try std.testing.expect(report != source);
- try std.testing.expect(std.mem.endsWith(u8, report.file.?.path, "/+Callstack"));
- try std.testing.expectEqual(@as(i32, 0), source.body.cur_row);
- const stale_selection = std.mem.indexOfScalar(u8, report.file.?.content, '\n').? + 1;
- report.body.setRange(report.file.?.content, 0, .{ .anchor = stale_selection, .head = stale_selection + 6 }, true);
- layout.toggleCollapse(p, 0);
- var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer frame.deinit();
- const surface = try p.render(frame.allocator());
- p.presented();
- const r = p.rects[p.active];
- const row = r.y + report.tag_rows;
- const col = r.x + config.GUTTER + panes.File.gutterWidth(report) + 7;
- try std.testing.expectEqual(.off, surface.at(col, row).style.ul);
- p.update(.{ .mouse = .{ .button = .right, .kind = .press, .row = row, .col = col } });
- p.update(.{ .mouse = .{ .button = .right, .kind = .release, .row = row, .col = col } });
- try std.testing.expect(!source.collapsed);
- try std.testing.expectEqual(@as(usize, 0), p.active);
- try std.testing.expect(!report.body.vsel.active);
- try std.testing.expectEqual(@as(usize, 0), report.body.nsel);
- const serial = report.serial;
- p.lspRequest(0, .callstack, "");
- const second = p.lsp_wait orelse return error.NoRequest;
- p.lspResponse(second.id, "No callers reported\n");
- try std.testing.expectEqual(serial, p.panes[p.active].?.serial);
- try std.testing.expectEqualStrings("No callers reported\n", p.panes[p.active].?.file.?.content);
-}
-
-test "Callers with one answer jumps to it and says where, in a msg" {
- if (!lsp.supports.contains(.incoming_calls)) return;
- const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- const pane = try p.setTestFile("fn a() {}\nfn b() { a(); }\n");
- p.lspRequest(p.active, .incoming_calls, "");
- const wait = p.lsp_wait.?;
- p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = "/test.txt:2:10 b\n" } });
- try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row);
- try std.testing.expectEqualStrings("Callers: the one, /test.txt:2:10", pane.msg[0..pane.msg_len]);
-}
-
-test "a Rename the language server finds nothing for says so, and changes nothing" {
- if (!lsp.supports.contains(.rename)) return;
- const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- const pane = try p.setTestFile("const value=1;\n");
- p.lspRequest(p.active, .rename, "renamed");
- const wait = p.lsp_wait.?;
- p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = "" } });
- try std.testing.expectEqualStrings("Rename: nothing here to rename", pane.msg[0..pane.msg_len]);
- try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content);
-}
-
test "an unasked desktop paste reaches a tty pane's program, not its buffer" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
@@ -6024,32 +5484,6 @@ fn bootAndTearDown(gpa: std.mem.Allocator) !void {
p.deinit();
}
-test "LSP failure clears only its matching wait without completion indentation" {
- if (!lsp.supports.contains(.completion)) return;
- const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- const pane = try p.setTestFile("x");
- pane.body.mode = .insert;
- pane.body.cur_col = 1;
-
- p.lspRequest(p.active, .completion, "");
- const old_id = p.lsp_wait.?.id;
- p.lspRequest(p.active, .completion, "");
- const current_id = p.lsp_wait.?.id;
- p.update(.{ .lsp_resp = .{ .id = old_id, .rows = null } });
- try std.testing.expectEqual(current_id, p.lsp_wait.?.id);
- p.update(.{ .lsp_resp = .{ .id = current_id, .rows = null } });
- try std.testing.expect(p.lsp_wait == null);
- try std.testing.expectEqualStrings("x", pane.file.?.content);
- try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);
-
- p.lspRequest(p.active, .completion, "");
- p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "" } });
- try std.testing.expect(p.lsp_wait == null);
- try std.testing.expectEqualStrings("x ", pane.file.?.content);
- try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
-}
-
test "every allocation failure during boot is a clean OutOfMemory" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, bootAndTearDown, .{});
}
diff --git a/test/output.zig b/test/output.zig
index c72668b4..0711442c 100644
--- a/test/output.zig
+++ b/test/output.zig
@@ -202,7 +202,7 @@ test "references fill the asking text's query pane: sorted under their files, th
const request = p.lsp_wait.?.id;
// the cursor moves before the answer: it is placed by where it was asked
source.body.cur_row = 4;
- p.lspResponse(request, response);
+ pardes.lsp.Ask.lspResponse(p, request, response);
const qid = panes.Query.ofOwner(p, source.serial) orelse return error.MissingResults;
const results = p.panes[qid].?;
const content = results.file.?.content;
@@ -272,7 +272,7 @@ test "a single language location opens the full spaced filename" {
const p = try Pardes.init(std.testing.allocator, .{ .file = path });
defer p.deinit();
p.lspRequest(0, .references, "");
- p.lspResponse(p.lsp_wait.?.id, "with space.zig:2:1 second\n");
+ pardes.lsp.Ask.lspResponse(p, p.lsp_wait.?.id, "with space.zig:2:1 second\n");
try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/with space.zig"));
try std.testing.expectEqual(@as(i32, 1), p.panes[p.active].?.body.cur_row);
for (p.panes) |slot| {