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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
|
//! 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("../root.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 TagState = @import("../TagState.zig");
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 {
/// Its pane's slot (walk.zig `.index`), that pane while `serial` says.
pub const replica = .{ .index = .{.{ "pane", pardes.Pardes, "panes" }} };
id: u32,
kind: lsp.Kind,
pane: Pane.Id,
serial: u32,
revision: u32,
arg: Effect.Buf(128),
row: i32 = 0,
col: i32 = 0,
/// A hover or code actions asked from the keyboard where jumps walk
/// (Pick.asked, when asked: a 9P script's answer comes after its write):
/// a hover drawn as ghost lines, no +Hover pane; the actions a picker
/// in the pane's tag, no +Lsp.
ghost: bool = false,
} = null,
/// A hover asked from the keyboard (where the walk is on), drawn as ghost
/// lines under the line it was asked at in its own body (pick-ui SPEC §3.5,
/// the coordinator's R3: never written): until Esc, an edit of that text,
/// or the next hover. Its first `hover_max` bytes.
hover: ?struct { serial: u32, row: i32, revision: u32, text: Effect.Buf(hover_max) } = null,
pub const hover_max = 1024;
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.editor())) 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: pardes.Kind.Buf(160) = .{};
if (!lsp.supports.contains(kind))
return p.reportFailure(id, said.print("{s}: no language server here answers it", .{lspWord(kind)}));
const pane = p.panes[id] orelse return;
if (kind != .status) {
const f = pane.file orelse
return p.reportFailure(id, said.print("{s}: only a file's pane asks a language server", .{lspWord(kind)}));
if (f.output != null)
return p.reportFailure(id, said.print("{s}: only a file's pane asks a language server", .{lspWord(kind)}));
}
if (arg.len > 128) return p.reportFailure(id, said.print("{s}: its argument is at most 128 bytes", .{lspWord(kind)}));
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, said.print("Rename: {s} is no name", .{arg}));
}
// A place in the file's text, as the server has it (File.fileText: the
// `Changes` layer's lines are none of it; one in them is after the file
// line above).
var off = if (pane.file) |*f| panes.File.fileOffset(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 = panes.File.fileText(&pane.file.?, p.scratch.allocator()) catch |err| return p.reportError(.at(id), lspWord(kind), err);
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, said.print("{s}: no {s} in this file", .{ lspWord(kind), arg }));
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: pardes.Kind.Buf(160) = .{};
var sent = arg;
var at = off;
if (kind == .explain) {
if (p.lsp_ask.last) |last| {
sent = explained.print("{s} {s}", .{ @tagName(last.kind), last.arg.slice() });
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 = .at(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,
.ghost = (kind == .hover or kind == .code_action) and pardes.Pick.asked(p),
};
p.emit(.{ .lsp = .{
.id = p.lsp_ask.seq,
.kind = kind,
.pane = .at(id),
.offset = @intCast(at),
.arg = .from(sent),
} });
}
pub const LspEdit = struct { start: usize, end: usize, text: []const u8 };
/// The client's edit records (`@put`, or `@edit` with `fallback`'s text),
/// in `a`; null for anything else or a malformed one.
pub fn parseLspEdits(a: std.mem.Allocator, bytes: []const u8, fallback: ?[]const u8) ?[]LspEdit {
if (bytes.len == 0 or bytes[bytes.len - 1] != '\n') return null;
const 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) = switch (std.meta.stringToEnum(enum { @"@put", @"@edit" }, head) orelse return null) {
.@"@put" => .put,
.@"@edit" => .edit,
};
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);
}
/// A code action's edit records (Pick.zig's actions) made in pane `pane`,
/// whose text they are of at `revision`: one undo step; false when they
/// are not (malformed, of another revision, changing nothing).
pub fn applyAction(p: *Pardes, pane: *Pane, revision: u32, records: []const u8) bool {
const edits = parseLspEdits(p.scratch.allocator(), records, null) orelse return false;
return applyLspEdits(p, pane, revision, edits);
}
/// The server's edits, of the file's text (its offsets; the `Changes`
/// layer's lines are none of it), made as the file's new text (File.load).
fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) bool {
const f = if (pane.file) |*file| file else return false;
if (f.revision != revision) return false;
const text = panes.File.fileText(f, p.scratch.allocator()) catch 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 > text.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, text[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, text.len - removed, added) catch return false;
const replacement = p.gpa.alloc(u8, final_len) catch return false;
const old_cursor = panes.File.fileOffset(f, 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)], text[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..], text[read_at..]);
edit.pushUndo(p.editor(), &pane.body) catch {
p.gpa.free(replacement);
return false;
};
panes.File.load(p, f, replacement);
// An edit asked for, undone as one: a reading pane is held (SPEC §6.5).
pardes.Trail.edited(p, f);
const cursor = modal.positionAt(f.content, panes.File.bufferOffset(f, mapped_cursor, false));
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(p.settings.tab);
return true;
}
/// Rename typed in pane `id`'s own tag (SPEC §3.5): the field the name
/// under its caret, which the body shows renamed as it is typed
/// (body_layer.renameGhosts) until Enter asks the server, or Esc.
pub fn openRename(p: *Pardes, id: usize) void {
const pane = p.panes[id] orelse return;
const old = renamedWord(pane) orelse return p.reportFailure(id, "Rename: nothing here to rename");
TagState.toRest(p);
const s = &p.view().tag_state;
s.kind = .rename;
s.host = pane.serial;
s.field.set(old);
s.previewing.set(id);
}
/// A key in Rename's field: Enter asks the server to rename to it (a name
/// the same as the old is no question), Esc (the tag's) puts it away.
pub fn renameKey(p: *Pardes, key: pardes.Key) void {
const s = &p.view().tag_state;
if (!key.ctrl and !key.alt and key.cp == pardes.Key.enter) {
const id = TagState.hostOf(p) orelse return TagState.toRest(p);
var name: Effect.Buf(128) = .{};
const typed = std.mem.trim(u8, s.field.text(), " ");
const same = std.mem.eql(u8, typed, renamedWord(p.panes[id].?) orelse "");
if (typed.len <= 128) name = .from(typed);
TagState.toRest(p);
if (same) return;
if (typed.len > 128) return p.reportFailure(id, "Rename: a name is at most 128 bytes");
return lspRequest(p, id, .rename, name.slice());
}
_ = s.field.key(key);
}
/// The name under pane `pane`'s caret, which a Rename renames.
pub fn renamedWord(pane: *const Pane) ?[]const u8 {
const line = panes.File.sourceLine(pane, pane.body.cur_row);
var lo: usize = @min(@as(usize, @intCast(@max(0, pane.body.cur_col))), line.len);
var hi = lo;
while (lo > 0 and (std.ascii.isAlphanumeric(line[lo - 1]) or line[lo - 1] == '_')) lo -= 1;
while (hi < line.len and (std.ascii.isAlphanumeric(line[hi]) or line[hi] == '_')) hi += 1;
return if (hi > lo) line[lo..hi] else null;
}
/// 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 asked = w.pane.index();
const pane = p.panes[asked] 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: pardes.Kind.Buf(256) = .{};
const rows = response orelse
return p.reportFailure(asked, said.print("{s}: the language server did not answer", .{lspWord(w.kind)}));
// 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(asked, said.print("{s}: {s}", .{ lspWord(w.kind), why }));
}
// 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, asked, 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.scratch.allocator(), rows, fallback)) |edits| {
if (applyLspEdits(p, pane, w.revision, edits)) {
var buf: pardes.Kind.Buf(64) = .{};
const verb: []const u8 = if (w.kind == .rename) "renamed" else "formatted";
p.setMessage(w.pane, buf.print("{s} {d} range(s)", .{ verb, edits.len }));
}
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.editor(), &pane.body) catch |err| return p.reportError(w.pane, "complete", err);
// 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, said.print("{s}: none", .{lspWord(w.kind)})),
.incoming_calls => "callers not found",
.outgoing_calls => "callees not found",
.hover => "nothing to show: not found",
else => "not found",
};
if (none) |text| p.reportFailure(asked, said.print("{s}: {s}", .{ lspWord(w.kind), text }));
return;
}
// A hover asked from the keyboard: ghost lines in its own body, no
// +Hover pane (SPEC §3.5).
if (w.kind == .hover and w.ghost) {
var cut = @min(rows.len, hover_max);
while (cut < rows.len and cut > 0 and rows[cut] & 0xC0 == 0x80) cut -= 1;
p.lsp_ask.hover = .{ .serial = pane.serial, .row = w.row, .revision = w.revision, .text = .from(rows[0..cut]) };
return;
}
// Code actions asked from the keyboard: a picker of them in the pane's
// own tag, each previewed as its edit and applied by Enter or its digit.
if (w.kind == .code_action and w.ghost) {
pardes.Pick.open(p, asked, .actions, "", "", rows);
if (pardes.Pick.live(p)) |pk| pk.revision = w.revision;
return;
}
// Anyone else's: their titles alone, in a +Lsp.
const listed_rows = if (w.kind == .code_action) titles: {
var kept: std.ArrayList(u8) = .empty;
var lines = std.mem.splitScalar(u8, rows, '\n');
while (lines.next()) |ln| if (ln.len > 0 and ln[0] != '@') {
kept.appendSlice(p.scratch.allocator(), ln) catch |err| return p.reportError(w.pane, lspWord(w.kind), err);
kept.append(p.scratch.allocator(), '\n') catch |err| return p.reportError(w.pane, lspWord(w.kind), err);
};
break :titles kept.items;
} else rows;
const from: panes.Output.Origin = .{ .query = w.kind };
const nrows = std.mem.count(u8, listed_rows, "\n");
if ((panes.Output.traits(from).jumps or w.kind == .diagnostics) and nrows == 1) {
const ln = std.mem.trimEnd(u8, rows, "\n");
const place = ln[0..panes.Output.location(ln).end];
p.look_missed = false;
look.lookAt(p, asked, 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)) {
// The server's line is the file's (File.bufferRow).
const ls = panes.File.lineStart(p.gpa, tf, panes.File.bufferRow(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: pardes.Kind.Buf(300) = .{};
p.setMessage(.at(v.active), where.print("{s}: the one, {s}", .{ lspWord(w.kind), place }));
}
return;
}
// Symbols and diagnostics asked from the keyboard, where jumps walk: a
// picker in the tag of the pane its Enter lands in (Pick.zig).
if (pardes.Pick.asked(p)) switch (w.kind) {
.document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics => return pardes.Pick.open(p, asked, .list, lspWord(w.kind), "", rows),
else => {},
};
// 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, asked, 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, listed_rows) catch |err| return p.reportError(w.pane, lspWord(w.kind), err);
const serial_before = p.next_serial;
p.fs.refilled = null;
panes.Output.fillResults(p, asked, dir, from, w.arg.slice(), content, null) catch |err| {
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, asked);
}
look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep);
break;
};
}
if (w.kind == .rename) {
var said_buf: pardes.Kind.Buf(128) = .{};
// 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)
said_buf.print("Rename: previewed, not applied: the server renamed in this file only, and {d} other open file(s) say the name", .{unrenamed})
else
said_buf.print("Rename: {d} edit(s) across files, previewed, not applied", .{nrows}));
}
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, asked, 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(0, e.lsp.pane.index());
seen = true;
};
try std.testing.expect(seen);
}
test "Def and Refs are a speaking file's words, out of its tag (UX K'4); gd, gr and a 2-1 chord on them typed in its tag 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.kindTail(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.kindTail(pane), " Def Refs Del"));
// Its tag's computed words have neither: typed into its own text, they
// run as any word there does.
try std.testing.expect(std.mem.indexOf(u8, tagline.computedWords(pane), "Def") == null);
pane.tag.own = try p.gpa.dupe(u8, "Def Refs");
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", p.messages.saidBy(pane));
}
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();
// About a jump opening a pane: `Jumps new-pane` (SPEC §6.6).
p.settings.jumps = .@"new-pane";
_ = 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(config.tab_width, 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", p.messages.saidBy(pane));
}
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", p.messages.saidBy(pane));
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);
}
test "a hover asked from the keyboard is ghost lines under the line it was asked at, drawn and never written, no +Hover pane; Esc takes them away" {
if (!lsp.supports.contains(.hover)) return error.SkipZigTest;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 });
defer p.deinit();
const pane = try p.setTestFile("one\ntwo\nthree\nfour\n");
const id = p.view().active;
p.settings.jumps = .walk;
while (p.nextEffect()) |_| {}
pane.focus = .body;
pane.body.cur_row = 1;
var npanes: usize = 0;
for (p.panes) |slot| npanes += @intFromBool(slot != null);
p.lspRequest(id, .hover, "");
while (p.nextEffect()) |_| {}
lspResponse(p, p.lsp_ask.seq, "pub fn add(a: i32) i32\nadds them\n");
var now: usize = 0;
for (p.panes) |slot| now += @intFromBool(slot != null);
try std.testing.expectEqual(npanes, now);
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
p.sync();
var s = try p.render(frame.allocator());
const body = s.region(.body, id).?.rect;
var buf: [256]u8 = undefined;
try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 1, &buf), "two") != null);
try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 2, &buf), "pub fn add(a: i32) i32") != null);
try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 3, &buf), "adds them") != null);
try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 4, &buf), "three") != null);
try std.testing.expectEqualStrings("one\ntwo\nthree\nfour\n", pane.file.?.content);
p.update(.{ .key = .{ .cp = pardes.Key.escape } });
try std.testing.expect(p.lsp_ask.hover == null);
try std.testing.expectEqual(id, p.view().active);
_ = frame.reset(.retain_capacity);
s = try p.render(frame.allocator());
try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 2, &buf), "three") != null);
}
/// Grid row `y` of `s` from column `x`, as text.
fn rowText(s: *const pardes.Surface, x: u16, y: u16, buf: []u8) []const u8 {
var n: usize = 0;
for (x..s.cols) |col| {
const g = s.cells[@as(usize, y) * s.cols + col].grapheme();
if (n + g.len > buf.len) break;
@memcpy(buf[n..][0..g.len], g);
n += g.len;
}
return buf[0..n];
}
test "SPC l r types the new name in the pane's own tag, the body showing each place in view renamed as it is typed, never written; Enter asks the server for it, Esc puts it away" {
if (!lsp.supports.contains(.rename)) return error.SkipZigTest;
const Key = pardes.Key;
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 });
defer p.deinit();
const pane = try p.setTestFile("const best = 1;\nconst b = best + best;\nconst bestow = 2;\n");
const id = p.view().active;
p.settings.jumps = .walk;
pane.focus = .body;
pane.body.cur_row = 0;
pane.body.cur_col = 7;
for (" lr") |c| p.update(.{ .key = .{ .cp = c } });
const s = &p.view().tag_state;
try std.testing.expectEqual(TagState.Kind.rename, s.kind);
try std.testing.expectEqualStrings("best", s.field.text());
for ("er") |c| p.update(.{ .key = .{ .cp = c } });
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
const a = frame.allocator();
try std.testing.expect(std.mem.indexOf(u8, (try pardes.TagState.head(p, a, pane)).?.text, "Rename best → bester") != null);
p.sync();
const sf = try p.render(a);
const body = sf.region(.body, id).?.rect;
var buf: [256]u8 = undefined;
// Each `best` in view struck and followed by the new name; `bestow` is
// another word. The first line is under the head's row (UX DESIGN M2).
try std.testing.expect(std.mem.indexOf(u8, rowText(sf, 0, body.y, &buf), "Rename best → bester") != null);
try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y + 1, &buf), "const b = bestbester + bestbester;") != null);
try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y + 2, &buf), "const bestow = 2;") != null);
try std.testing.expectEqualStrings("const best = 1;\nconst b = best + best;\nconst bestow = 2;\n", pane.file.?.content);
// Enter: the server asked to rename it, the tag at rest.
while (p.nextEffect()) |_| {}
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expectEqual(TagState.Kind.rest, s.kind);
try std.testing.expectEqualStrings("bester", p.lsp_ask.wait.?.arg.slice());
// Esc from the field asks nothing.
p.lsp_ask.wait = null;
for (" lr") |c| p.update(.{ .key = .{ .cp = c } });
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expectEqual(TagState.Kind.rest, s.kind);
try std.testing.expect(p.lsp_ask.wait == null);
}
test "an edit a language server sends (a format, a rename) holds the reading pane it lands in, as a typed edit does (SPEC §6.5)" {
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 });
defer p.deinit();
p.settings.jumps = .walk;
const pane = try p.setTestFile("let x = add(1, 2);\n");
try std.testing.expect(pardes.Trail.reading(p, pane));
const edits = [_]LspEdit{.{ .start = 8, .end = 11, .text = "sum" }};
try std.testing.expect(applyLspEdits(p, pane, pane.file.?.revision, &edits));
try std.testing.expectEqualStrings("let x = sum(1, 2);\n", pane.file.?.content);
try std.testing.expect(!pardes.Trail.reading(p, pane));
}
|