summaryrefslogtreecommitdiff
path: root/src/lsp/Ask.zig
blob: 8ed0aecc1d862bcb5f6fcac427928cd875389970 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! 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 Effect = pardes.Effect;

const Ask = @This();

seq: u32 = 0,
/// The last query asked (Lspwhy explains it): its kind, argument, and the
/// pane and place it was asked at.
last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null,
/// The query whose answer is awaited.
wait: ?struct {
    id: u32,
    kind: lsp.Kind,
    pane: usize,
    serial: u32,
    revision: u32,
    arg: Effect.Buf(128),
    row: i32 = 0,
    col: i32 = 0,
} = null,
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_ask.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_ask.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_ask.last = .{ .kind = kind, .arg = .from(arg), .serial = pane.serial, .offset = @intCast(off) };
    p.lsp_ask.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_ask.wait = .{
        .id = p.lsp_ask.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_ask.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 {
    const v = p.view();
    defer pardes.turn.bump(&pardes.turn.lsp_answers);
    const w = p.lsp_ask.wait orelse return;
    if (w.id != id) return; // superseded by a newer press, or the pane died
    p.lsp_ask.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[v.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(v.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(v.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_ask.wait = null;
    // Run from another file's pane: still the hover's file and place.
    const other = p.freeSlot().?;
    _ = try panes.openTutorView(p, 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_ask.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.view().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_ask.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.view().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.view().rects[p.view().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.view().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_ask.wait orelse return error.NoRequest;
    lspResponse(p, second.id, "No callers reported\n");
    try std.testing.expectEqual(serial, p.panes[p.view().active].?.serial);
    try std.testing.expectEqualStrings("No callers reported\n", p.panes[p.view().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.view().active, .incoming_calls, "");
    const wait = p.lsp_ask.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.view().active, .rename, "renamed");
    const wait = p.lsp_ask.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.view().active, .completion, "");
    const old_id = p.lsp_ask.wait.?.id;
    p.lspRequest(p.view().active, .completion, "");
    const current_id = p.lsp_ask.wait.?.id;
    p.update(.{ .lsp_resp = .{ .id = old_id, .rows = null } });
    try std.testing.expectEqual(current_id, p.lsp_ask.wait.?.id);
    p.update(.{ .lsp_resp = .{ .id = current_id, .rows = null } });
    try std.testing.expect(p.lsp_ask.wait == null);
    try std.testing.expectEqualStrings("x", pane.file.?.content);
    try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col);

    p.lspRequest(p.view().active, .completion, "");
    p.update(.{ .lsp_resp = .{ .id = p.lsp_ask.wait.?.id, .rows = "" } });
    try std.testing.expect(p.lsp_ask.wait == null);
    try std.testing.expectEqualStrings("x   ", pane.file.?.content);
    try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col);
}