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
|
//! One binding table (walk UI, pick-ui SPEC.md §4): every key sequence a
//! root starts, as a tree per root, made at compile time from the tables
//! that bind them: SPC's from `config.leader_path` and `config.leader_args`,
//! the helix prefixes' (`g m z Z [ ]`) from their roles in modal.zig and
//! their chords in config.zig, window mode's (`C-w`) from
//! `config.window_keys`. An addon's leader words join SPC's levels where
//! they are read (`level`). Which-key, Help and describe-key all read it.
const std = @import("std");
const pardes = @import("root.zig");
const config = @import("config.zig");
const builtins = @import("builtins.zig");
const modal = @import("modal.zig");
const Builtin = pardes.Builtin;
const Pardes = pardes.Pardes;
const Pane = pardes.Pane;
const Key = pardes.Key;
const Role = modal.Normal.Role;
const edit = @import("edit.zig");
const File = @import("File.zig");
/// The keys a sequence starts with. `register` (`"`) is drawn the same way
/// but its rows are the registers' contents, not a tree.
pub const Root = enum(u8) { leader, window, goto, match, view, view_sticky, prev, next, register };
/// What a leaf runs: a builtin, a builtin with its argument
/// (`config.leader_args`, by index), or a normal-mode role typed as its keys.
pub const Leaf = union(enum) { builtin: Builtin, arg: u8, role: Role };
/// A group (`children`) or a leaf. `label` is a group's name, a builtin
/// leaf's word (`Def`), a motion's description (`line start`).
pub const Node = struct {
key: u8,
label: []const u8,
leaf: ?Leaf = null,
children: []const Node = &.{},
/// A group's slot in a view's memory of the leaf it ran last
/// (TagState.used).
group: u8 = 0,
/// It asks the language server: dimmed in a pane none speaks for.
lsp: bool = false,
};
pub const Info = struct {
key: Key,
/// Its key cell in the head (`␣` for SPC).
cell: []const u8,
label: []const u8,
/// How long after it the level shows (SPEC §3.3): the tag changes
/// nothing before (UX D12), so `gg` and a fast `SPC f s` never touch it;
/// its keys show on the notice row's right end at once (Messages).
delay_ns: u64,
node: *const Node,
};
const ms = std.time.ns_per_ms;
pub const info = std.EnumArray(Root, Info).init(.{
.leader = .{ .key = .{ .cp = config.leader[0].cp }, .cell = "␣", .label = "SPC", .delay_ns = 250 * ms, .node = &leader_tree },
.window = .{ .key = .{ .cp = config.window_prefix[0].cp, .ctrl = true }, .cell = "C-w", .label = "window", .delay_ns = 250 * ms, .node = &window_tree },
.goto = .{ .key = .{ .cp = config.goto_prefix }, .cell = "g", .label = "goto", .delay_ns = 500 * ms, .node = &goto_tree },
.match = .{ .key = .{ .cp = config.match_prefix }, .cell = "m", .label = "match", .delay_ns = 500 * ms, .node = &match_tree },
.view = .{ .key = .{ .cp = config.view_prefix }, .cell = "z", .label = "view", .delay_ns = 500 * ms, .node = &view_tree },
.view_sticky = .{ .key = .{ .cp = config.view_prefix_sticky }, .cell = "Z", .label = "view", .delay_ns = 500 * ms, .node = &view_sticky_tree },
.prev = .{ .key = .{ .cp = config.prev_prefix }, .cell = "[", .label = "previous", .delay_ns = 500 * ms, .node = &prev_tree },
.next = .{ .key = .{ .cp = config.next_prefix }, .cell = "]", .label = "next", .delay_ns = 500 * ms, .node = &next_tree },
.register = .{ .key = .{ .cp = config.register_prefix }, .cell = "\"", .label = "registers", .delay_ns = 300 * ms, .node = ®ister_tree },
});
/// SPC's groups by their key, as the spec names them (Appendix A).
const leader_groups = [_]struct { key: u8, label: []const u8 }{
.{ .key = 'b', .label = "buffer" }, .{ .key = 'c', .label = "column" },
.{ .key = 'f', .label = "file" }, .{ .key = 'h', .label = "help" },
.{ .key = 'j', .label = "jump" }, .{ .key = 'l', .label = "lsp" },
.{ .key = 'n', .label = "new" }, .{ .key = 's', .label = "session" },
.{ .key = 't', .label = "view" },
};
/// Every group of every tree, a slot each in a view's memory: SPC's by
/// path, then each root's own level.
pub const groups = groups: {
@setEvalBranchQuota(100_000);
var paths: []const []const u8 = &.{""};
for (leaderPaths()) |path| for (1..path.len) |n| {
const head = path[0..n];
for (paths) |had| {
if (std.mem.eql(u8, had, head)) break;
} else paths = paths ++ .{head};
};
break :groups paths;
};
/// SPC's groups, then one for each other root, then the verbs a register
/// takes (`"a ▸`).
pub const ngroups = groups.len + std.enums.values(Root).len;
fn rootGroup(comptime r: Root) u8 {
return @intCast(groups.len + @intFromEnum(r) - 1);
}
/// Every path SPC has: a builtin's (each one, whether this view takes it
/// or not: `here` is asked where a level is read) and `leader_args`'.
fn leaderPaths() []const []const u8 {
comptime {
var paths: []const []const u8 = &.{};
for (std.enums.values(Builtin)) |b| if (config.leader_path.get(b)) |path| {
paths = paths ++ .{path};
};
for (config.leader_args) |la| paths = paths ++ .{la.path};
return paths;
}
}
/// Which-key order (SPEC §4.2): groups first, then keys: punctuation, then
/// a-z with a lowercase key before its capital.
fn rank(key: u8, group: bool) u16 {
const letter: u16 = if (std.ascii.isAlphabetic(key)) 256 + @as(u16, std.ascii.toLower(key) - 'a') * 2 + @intFromBool(std.ascii.isUpper(key)) else key;
return letter + if (group) 0 else @as(u16, 1024);
}
fn sorted(comptime nodes: []const Node) []const Node {
comptime {
var out: [nodes.len]Node = nodes[0..nodes.len].*;
for (1..out.len) |i| {
var j = i;
while (j > 0 and rank(out[j].key, out[j].children.len > 0) < rank(out[j - 1].key, out[j - 1].children.len > 0)) : (j -= 1) {
const t = out[j];
out[j] = out[j - 1];
out[j - 1] = t;
}
}
const final = out;
return &final;
}
}
/// SPC's level under `prefix`.
fn leaderLevel(comptime prefix: []const u8) []const Node {
comptime {
@setEvalBranchQuota(200_000);
var keys: []const u8 = "";
for (leaderPaths()) |path| {
if (path.len <= prefix.len or !std.mem.startsWith(u8, path, prefix)) continue;
if (std.mem.indexOfScalar(u8, keys, path[prefix.len]) == null) keys = keys ++ .{path[prefix.len]};
}
var nodes: [keys.len]Node = undefined;
for (keys, 0..) |k, i| {
const here = prefix ++ .{k};
const lsp = here[0] == 'l';
nodes[i] = for (std.enums.values(Builtin)) |b| {
const path = config.leader_path.get(b) orelse continue;
if (std.mem.eql(u8, path, here)) break .{ .key = k, .label = @tagName(b), .leaf = .{ .builtin = b }, .lsp = lsp };
} else for (config.leader_args, 0..) |la, a| {
if (std.mem.eql(u8, la.path, here)) break .{ .key = k, .label = la.arg, .leaf = .{ .arg = a }, .lsp = lsp };
} else .{ .key = k, .label = groupLabel(here), .children = leaderLevel(here), .group = groupIndex(here) };
}
return sorted(&nodes);
}
}
fn groupLabel(comptime path: []const u8) []const u8 {
if (path.len == 1) for (leader_groups) |g| if (g.key == path[0]) return g.label;
return path;
}
fn groupIndex(comptime path: []const u8) u8 {
for (groups, 0..) |g, i| if (std.mem.eql(u8, g, path)) return i;
unreachable;
}
/// A role's key under its root: the first chord config.zig binds it to
/// that a plain key types; none when only a held one does (`z C-d`).
fn roleKey(comptime role: Role) ?u8 {
const binding = @field(config, @tagName(role));
if (@TypeOf(binding) == comptime_int) return if (binding >= 0x20 and binding < 0x7f) binding else null;
for (binding) |c| if (!c.ctrl and !c.alt and c.cp >= 0x20 and c.cp < 0x7f) return @intCast(c.cp);
return null;
}
/// The builtin a role runs (normal.zig executeNormalAction), shown by its
/// word; null for a motion, shown by its description.
fn roleWord(comptime role: Role) ?Builtin {
return switch (role) {
.goto_definition => .Def,
.goto_references => .Refs,
.goto_callstack => .Callstack,
else => null,
};
}
/// A motion's description: its role's name without its context's word,
/// spaced (`goto_line_start` is `line start`).
fn roleLabel(comptime role: Role) []const u8 {
if (role == .match_prefix) return "matching bracket";
if (roleWord(role)) |b| return @tagName(b);
var name: []const u8 = @tagName(role);
for ([_][]const u8{ "goto_", "view_", "match_" }) |head| if (std.mem.startsWith(u8, name, head)) {
name = name[head.len..];
};
var out: [name.len]u8 = undefined;
for (name, 0..) |c, i| out[i] = if (c == '_') ' ' else c;
const final = out;
return &final;
}
fn roleLsp(comptime role: Role) bool {
return switch (role) {
.goto_definition, .goto_declaration, .goto_type_definition, .goto_implementation, .goto_references, .goto_callstack, .goto_diagnostic, .goto_diagnostic_end => true,
else => false,
};
}
/// A root's level of roles, `from` to `to` in Role's order (the order its
/// context tries them, modal.zig): the first role a key has is the one it
/// runs, so a later role on the same key is not shown.
fn roleLevel(comptime from: Role, comptime to: Role, comptime extra: []const Role) []const Node {
comptime {
@setEvalBranchQuota(100_000);
var nodes: []const Node = &.{};
var roles: []const Role = extra;
for (@intFromEnum(from)..@intFromEnum(to) + 1) |i| roles = roles ++ .{@as(Role, @enumFromInt(i))};
for (roles) |role| {
const key = roleKey(role) orelse continue;
for (nodes) |n| {
if (n.key == key) break;
} else nodes = nodes ++ .{Node{ .key = key, .label = roleLabel(role), .leaf = .{ .role = role }, .lsp = roleLsp(role) }};
}
return sorted(nodes);
}
}
const leader_tree: Node = .{ .key = ' ', .label = "SPC", .children = leaderLevel(""), .group = 0 };
const goto_tree: Node = .{ .key = config.goto_prefix, .label = "goto", .children = roleLevel(.goto_file_start, .goto_callstack, &.{}), .group = rootGroup(.goto) };
const match_tree: Node = .{ .key = config.match_prefix, .label = "match", .children = roleLevel(.match_inside, .surround_delete, &.{.match_prefix}), .group = rootGroup(.match) };
const view_tree: Node = .{ .key = config.view_prefix, .label = "view", .children = roleLevel(.view_top, .view_scroll_up, &.{}), .group = rootGroup(.view) };
const view_sticky_tree: Node = .{ .key = config.view_prefix_sticky, .label = "view", .children = roleLevel(.view_top, .view_scroll_up, &.{}), .group = rootGroup(.view_sticky) };
const prev_tree: Node = .{ .key = config.prev_prefix, .label = "previous", .children = roleLevel(.goto_paragraph, .goto_xml_element, &.{}), .group = rootGroup(.prev) };
const next_tree: Node = .{ .key = config.next_prefix, .label = "next", .children = roleLevel(.goto_paragraph, .goto_xml_element, &.{}), .group = rootGroup(.next) };
const register_tree: Node = .{ .key = config.register_prefix, .label = "registers", .group = rootGroup(.register) };
/// What the register `"` named does next (SPEC §9: `"a ▸ p after P before
/// y into R replace`): normal mode's paste, yank and replace, which read
/// the register the parser holds.
const register_verbs: Node = .{ .key = 0, .label = "register", .group = ngroups - 1, .children = sorted(&.{
.{ .key = roleKey(.paste_after).?, .label = "after", .leaf = .{ .role = .paste_after } },
.{ .key = roleKey(.paste_before).?, .label = "before", .leaf = .{ .role = .paste_before } },
.{ .key = roleKey(.yank).?, .label = "into", .leaf = .{ .role = .yank } },
.{ .key = roleKey(.replace_with_yank).?, .label = "replace", .leaf = .{ .role = .replace_with_yank } },
}) };
/// pardes's window mode (layout.windowKey): its moves, Collapse and Del;
/// a letter picks the pane its box shows.
const window_tree: Node = .{ .key = 'w', .label = "window", .group = rootGroup(.window), .children = window: {
var nodes: []const Node = &.{};
for (config.window_keys) |wk| nodes = nodes ++ .{Node{ .key = @intCast(wk.letter.cp), .label = @tagName(wk.cmd), .leaf = .{ .builtin = wk.cmd } }};
nodes = nodes ++ .{
Node{ .key = config.window_collapse[0].cp, .label = "Collapse", .leaf = .{ .builtin = .Collapse } },
Node{ .key = config.window_delete[0].cp, .label = "Del", .leaf = .{ .builtin = .Del } },
};
break :window sorted(nodes);
} };
/// The node `path` reaches under `root`, or null.
pub fn nodeAt(root: Root, path: []const u8) ?*const Node {
var n = info.get(root).node;
var keys = path;
// A register's name is any key: under each, its verbs.
if (root == .register and path.len > 0) {
n = ®ister_verbs;
keys = path[1..];
}
for (keys) |k| n = for (n.children) |*c| {
if (c.key == k) break c;
} else return null;
return n;
}
/// A level's child as which-key shows it: the tree's, or an addon's word
/// (SPC's alone), or an addon's path going on (a group of its words).
pub const Child = struct {
key: u8,
label: []const u8,
node: ?*const Node = null,
word: ?*const pardes.Kind.Word = null,
group: bool = false,
lsp: bool = false,
/// Its label is cut (a register's first line): `…` after it.
more: bool = false,
};
/// The most children a level shows: SPC's top has 17, and an addon's
/// words (Kind.Registry's 64) may each start a key of their own.
pub const max_children = 96;
/// The children of `path` under `root` this view takes, in which-key order:
/// the tree's (a builtin this view's frontend has not dropped), then the
/// addons' leader words joined in (SPC alone). Bounded by the level and the
/// registry's 64 words.
pub fn level(p: *const Pardes, root: Root, path: []const u8, out: *[max_children]Child) []Child {
if (root == .register and path.len == 0) return registerLevel(p, out);
var n: usize = 0;
if (nodeAt(root, path)) |node| for (node.children) |*c| {
if (c.leaf) |leaf| if (leaf == .builtin and !builtins.registry.here(p, leaf.builtin)) continue;
out[n] = .{ .key = c.key, .label = c.label, .node = c, .group = c.children.len > 0, .lsp = c.lsp };
n += 1;
};
if (root == .leader) for (p.kinds.words[0..p.kinds.nwords]) |*w| {
const keys = w.leader.slice();
if (keys.len <= path.len or !std.mem.startsWith(u8, keys, path)) continue;
const k = keys[path.len];
const last = keys.len == path.len + 1;
for (out[0..n]) |c| {
if (c.key == k) break;
} else if (n < out.len) {
out[n] = .{ .key = k, .label = if (last) w.name.slice() else "addon", .word = if (last) w else null, .group = !last };
n += 1;
}
};
const shown = out[0..n];
for (1..@max(1, shown.len)) |i| {
var j = i;
while (j > 0 and rank(shown[j].key, shown[j].group) < rank(shown[j - 1].key, shown[j - 1].group)) : (j -= 1)
std.mem.swap(Child, &shown[j], &shown[j - 1]);
}
return shown;
}
/// The registers `"` shows (SPEC §9), in its order, and what each is: the
/// default first, the ones a name was given (`"ay`) after it, by name,
/// then these, the last four computed from the pane with the keyboard.
pub const register_names = [_]struct { key: u8, name: []const u8 }{
.{ .key = '"', .name = "yank" },
.{ .key = '/', .name = "last search" },
.{ .key = ':', .name = "last command" },
.{ .key = '|', .name = "last pipe" },
.{ .key = '+', .name = "system clipboard" },
.{ .key = '@', .name = "last macro" },
.{ .key = '%', .name = "this file's name" },
.{ .key = '.', .name = "the selections" },
.{ .key = '#', .name = "selection numbers" },
.{ .key = '_', .name = "black hole" },
};
/// The display columns of a register's first line which-key shows; the
/// rest is `…` (UX D11: 20 cells, the `…` among them).
pub const register_cut = 20;
/// A register's value as a row shows it (UX D11): its first line in
/// `register_cut` cells at most, a path cut from the left
/// (`…core/Query.zig`), other text from the right (`…` after it), a newline
/// that ends what shows said `⏎`; `—` when it holds nothing. Only its first
/// `4 * register_cut` bytes are read.
pub fn registerShown(arena: std.mem.Allocator, tab: u16, value: []const u8) ![]const u8 {
if (value.len == 0) return "—";
const bound = if (value.len > 4 * register_cut) modal.graphemeStart(value, 4 * register_cut) else value.len;
const newline = std.mem.indexOfScalar(u8, value[0..bound], '\n');
const line = value[0 .. newline orelse bound];
const width = File.displayWidth(tab, line);
if (width <= register_cut and line.len == value.len) return line;
if (width < register_cut and newline != null) return std.mem.concat(arena, u8, &.{ line, "⏎" });
// A path: one line, no spaces, a slash in it; its end says which file.
if (newline == null and bound == value.len and std.mem.indexOfAny(u8, line, " \t") == null and std.mem.indexOfScalar(u8, line, '/') != null) {
var start = File.rawAtDisplay(tab, line, width - (register_cut - 1));
if (File.rawDisplayCol(tab, line, start) < width - (register_cut - 1)) start = modal.nextGrapheme(line, start);
return std.mem.concat(arena, u8, &.{ "…", line[start..] });
}
return std.mem.concat(arena, u8, &.{ line[0..File.byteAtDisplay(tab, line, register_cut - 1)], "…" });
}
/// `"`'s level: a child a register, its label the first line of its value
/// (`—` when empty), cut. Read when the level is (a key, a frame), never
/// kept: the first `register_cut` columns of each, the named ones bounded
/// by the level's room.
fn registerLevel(p: *const Pardes, out: *[max_children]Child) []Child {
var n: usize = 1;
for (p.registers.list.items) |*reg| {
if (reg.name <= ' ' or reg.name > '~' or n == out.len - (register_names.len - 1)) continue;
const k: u8 = @intCast(reg.name);
for (register_names) |r| {
if (r.key == k) break;
} else {
var j = n;
while (j > 1 and out[j - 1].key > k) : (j -= 1) out[j] = out[j - 1];
out[j] = .{ .key = k, .label = "" };
n += 1;
}
}
out[0] = .{ .key = '"', .label = "" };
for (register_names[1..]) |r| {
out[n] = .{ .key = r.key, .label = "" };
n += 1;
}
for (out[0..n]) |*c| {
const value = registerValue(p, c.key);
const bound = if (value.len > 4 * register_cut) modal.graphemeStart(value, 4 * register_cut) else value.len;
const line = value[0 .. std.mem.indexOfScalar(u8, value[0..bound], '\n') orelse bound];
const cut = File.byteAtDisplay(p.settings.tab, line, register_cut);
c.label = if (value.len == 0) "—" else line[0..cut];
c.more = cut < value.len;
}
return out[0..n];
}
/// Register `key`'s value as a paste of the pane with the keyboard reads
/// its first range's (edit.registerValue): a stored one's first value; `%`
/// the file's name, `.` the primary selection's text, `#` its number, `_`
/// nothing. Borrowed from the register or the pane, for the frame.
pub fn registerValue(p: *const Pardes, key: u8) []const u8 {
const pane = p.panes[p.view().active] orelse return "";
switch (key) {
'_' => return "",
'#' => return "1",
'%' => return if (pane.file) |*f| f.path else "",
'.' => {
const f = if (pane.file) |*f| f else return "";
const t = &pane.body;
const b = edit.cellBounds(.{ .row = t.cur_row, .col = t.cur_col, .arow = if (t.vsel.active) t.vsel.row else t.cur_row, .acol = if (t.vsel.active) t.vsel.col else t.cur_col });
const first = File.sourceLine(pane, b.lo_row);
const last = File.sourceLine(pane, b.hi_row);
if (f.content.len == 0) return "";
const lo = @min(f.content.len, first.ptr - f.content.ptr + @as(usize, @intCast(@max(0, b.lo_col))));
const hi = @min(f.content.len, last.ptr - f.content.ptr + @as(usize, @intCast(@max(0, b.hi_col))));
return f.content[lo..modal.nextGrapheme(f.content, @max(lo, hi))];
},
else => for (p.registers.list.items) |*reg| {
if (reg.name == key) return if (reg.values.len == 0) "" else reg.values[0];
} else return "",
}
}
/// A key as a cell shows it: `SPC` for the space.
pub fn keyName(key: u8) []const u8 {
return if (key == ' ') "SPC" else @as(*const [1]u8, &printable[key - 0x20]);
}
const printable = blk: {
var all: [0x5f]u8 = undefined;
for (&all, 0x20..) |*c, i| c.* = i;
break :blk all;
};
/// A child's one-line documentation: a builtin's summary, an addon word's
/// own, a motion's description under its root's name.
pub fn docOf(root: Root, c: Child, buf: []u8) []const u8 {
if (c.word) |w| return w.doc.slice();
const node = c.node orelse return "";
if (node.children.len > 0) return "a group";
return switch (node.leaf.?) {
.builtin => |b| builtins.registry.doc(b).summary,
.arg => |a| std.fmt.bufPrint(buf, "{s} {s}: {s}", .{ @tagName(config.leader_args[a].cmd), config.leader_args[a].arg, builtins.registry.doc(config.leader_args[a].cmd).summary }) catch "",
.role => |role| if (roleWordAt(role)) |b| builtins.registry.doc(b).summary else std.fmt.bufPrint(buf, "{s} {s}", .{ info.get(root).label, c.label }) catch c.label,
};
}
/// `roleWord` for a role known only when the program runs.
fn roleWordAt(role: Role) ?Builtin {
return switch (role) {
inline else => |r| comptime roleWord(r),
};
}
/// Whether child `c` is dimmed in pane `pane`: it asks a language server
/// and none speaks for the pane's text.
pub fn dimmed(pane: *const Pane, c: Child) bool {
if (!c.lsp) return false;
const f = pane.file orelse return true;
return f.output != null or f.mini != null or !pardes.lsp.speaks(f.path);
}
/// The keys that type `path` under `root`, the root's first: a leaf run
/// from Help or describe-key is typed as its keys are.
pub fn keysOf(root: Root, path: []const u8, out: *[16]Key) []Key {
out[0] = info.get(root).key;
const n = @min(path.len, out.len - 1);
for (path[0..n], 1..) |k, i| out[i] = .{ .cp = k };
return out[0 .. n + 1];
}
/// The root a key starts, if it starts one.
pub fn rootOf(key: Key) ?Root {
for (std.enums.values(Root)) |r| {
const k = info.get(r).key;
if (key.cp == k.cp and key.ctrl == k.ctrl and !key.alt) return r;
}
return null;
}
/// `SPC l k`, `g d`, `C-w h`: a chord as Help's rows and describe-key spell
/// it.
pub fn chord(root: Root, path: []const u8, buf: []u8) []const u8 {
var w = std.Io.Writer.fixed(buf);
w.writeAll(if (root == .leader) "SPC" else info.get(root).cell) catch {};
for (path) |k| w.print(" {s}", .{keyName(k)}) catch {};
return w.buffered();
}
/// Every leaf of every root, Help's rows (SPEC §4.5): `chord · word · group`,
/// and the same in lowercase, which the scorer matches a lowercase query
/// against.
pub const Flat = struct { root: Root, path: []const u8, node: *const Node, row: []const u8, lower: []const u8 };
pub const flat: []const Flat = flat: {
@setEvalBranchQuota(1_000_000);
var all: []const Flat = &.{};
for (std.enums.values(Root)) |r| all = all ++ flatten(r, info.get(r).node, "", info.get(r).label);
break :flat all;
};
fn flatten(comptime r: Root, comptime node: *const Node, comptime path: []const u8, comptime group: []const u8) []const Flat {
comptime {
var all: []const Flat = &.{};
for (node.children) |*c| {
const here = path ++ .{c.key};
if (c.children.len > 0) {
all = all ++ flatten(r, c, here, if (r == .leader) c.label else group ++ " " ++ c.label);
continue;
}
var spelled: []const u8 = if (r == .leader) "SPC" else info.get(r).cell;
for (here) |k| spelled = spelled ++ " " ++ keyName(k);
const row = spelled ++ " · " ++ c.label ++ " · " ++ (if (r == .leader and path.len == 0) "root" else group);
var lower: [row.len]u8 = undefined;
for (row, 0..) |ch, i| lower[i] = std.ascii.toLower(ch);
const low = lower;
all = all ++ .{Flat{ .root = r, .path = here, .node = c, .row = row, .lower = &low }};
}
return all;
}
}
test "SPC's tree is made from the leader paths, groups first, a key's lowercase before its capital" {
const top = nodeAt(.leader, "").?;
// Groups first: every group comes before every leaf.
var leaves = false;
for (top.children) |c| {
if (c.children.len == 0) leaves = true else try std.testing.expect(!leaves);
}
const l = nodeAt(.leader, "l").?;
try std.testing.expectEqualStrings("lsp", l.label);
try std.testing.expect(l.lsp == false and l.children.len >= 15);
// `d` Diagnostics before `D` WsDiagnostics, `s` before `S`.
var d: ?usize = null;
for (l.children, 0..) |c, i| {
if (c.key == 'd') d = i;
if (c.key == 'D') try std.testing.expectEqual(d.? + 1, i);
}
const hover = nodeAt(.leader, "lk").?;
try std.testing.expectEqualStrings("Hover", hover.label);
try std.testing.expect(hover.lsp and hover.leaf.?.builtin == .Hover);
// A path with an argument is a leaf of its own word.
try std.testing.expectEqualStrings("Panes", nodeAt(.leader, "bb").?.label);
try std.testing.expect(nodeAt(.leader, "lz") == null);
}
test "the helix prefixes are trees of their roles: a builtin by its word, a motion by its description" {
try std.testing.expectEqualStrings("Def", nodeAt(.goto, "d").?.label);
try std.testing.expectEqualStrings("line start", nodeAt(.goto, "h").?.label);
try std.testing.expectEqualStrings("file start", nodeAt(.goto, "g").?.label);
try std.testing.expectEqualStrings("top", nodeAt(.view, "t").?.label);
try std.testing.expectEqualStrings("matching bracket", nodeAt(.match, "m").?.label);
try std.testing.expectEqualStrings("function", nodeAt(.next, "f").?.label);
try std.testing.expectEqualStrings("add newline", nodeAt(.prev, " ").?.label);
try std.testing.expectEqualStrings("Left", nodeAt(.window, "h").?.label);
// `zz` and `zc` both centre: one row, the first key.
var centres: usize = 0;
for (nodeAt(.view, "").?.children) |c| if (std.mem.eql(u8, c.label, "center")) {
centres += 1;
};
try std.testing.expectEqual(@as(usize, 1), centres);
}
test "Help's rows: every leaf of every root, spelled as its chord, its word and its group" {
var found: usize = 0;
for (flat) |f| {
if (std.mem.eql(u8, f.row, "SPC l k · Hover · lsp")) found += 1;
if (std.mem.eql(u8, f.row, "g d · Def · goto")) found += 1;
if (std.mem.eql(u8, f.row, "] f · function · next")) found += 1;
if (std.mem.eql(u8, f.row, "SPC q · Exit · root")) found += 1;
}
try std.testing.expectEqual(@as(usize, 4), found);
for (flat) |f| try std.testing.expectEqual(f.row.len, f.lower.len);
}
test "\" shows the registers rolled, the ones holding something, each its value cut to 20 cells (a path from the left, a newline a dim ⏎); Down unrolls them all, `key value` with the name at the right, beside the cursor's value and its verbs, their keys in the key ink; a register's key goes down to its verbs, Backspace back up, p pastes it (UX D11)" {
const tagline = @import("tagline.zig");
const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 });
defer p.deinit();
const pane = try p.setTestFile("one\ntwo\n");
try p.registers.put(p.gpa, 'a', "const best = rank(q, name) orelse continue;\nreturn best;", 0, 1, true);
try p.registers.put(p.gpa, '"', "self.dirty = true;", 0, 1, true);
try p.registers.put(p.gpa, 'n', "ab\ncd", 0, 1, true);
try p.registers.put(p.gpa, 'p', "/home/user/proj/core/Query.zig", 0, 1, true);
var frame = std.heap.ArenaAllocator.init(std.testing.allocator);
defer frame.deinit();
const a = frame.allocator();
p.clock.now_ns = 5 * std.time.ns_per_s;
p.clock.stepped_ns = p.clock.now_ns;
p.sync();
// Nothing in the tag until the level shows 300 ms on (UX D12).
const rest = try a.dupe(u8, try tagline.tagText(p, a, pane));
p.update(.{ .key = .{ .cp = '"' } });
try std.testing.expectEqualStrings(rest, try tagline.tagText(p, a, pane));
p.advance(p.clock.now_ns);
try std.testing.expectEqual(p.clock.now_ns + 300 * std.time.ns_per_ms, p.view().tag_state.due_ns);
p.clock.now_ns = p.view().tag_state.due_ns;
const rolled = try tagline.tagText(p, a, pane);
try std.testing.expect(std.mem.indexOf(u8, rolled, "\" ▸ \" self.dirty = true; a const best = rank(q… n ab⏎ p …proj/core/Query.zig % /test.txt . o # 1 ") != null);
// Its ⏎ in the dim ink.
const h = (try @import("TagState.zig").head(p, a, pane)).?;
const nl = std.mem.indexOf(u8, h.text, "ab⏎").? + 2;
for (h.spans) |span| {
if (span.lo == nl) break try std.testing.expectEqual(.dim, span.style);
} else return error.NoDimNewline;
// Down unrolls: a row each, the cursor on the default, its value
// beside them.
p.update(.{ .key = .{ .cp = Key.down } });
try std.testing.expect(p.view().tag_state.unrolled);
try std.testing.expect(pardes.Band.covered(p, pane, p.view().active).band >= 4);
_ = try p.render(a);
const layer = &p.surface.tag_layers[pardes.BAND_LAYER];
var band: std.ArrayList(u8) = .empty;
for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try band.appendSlice(a, cell.grapheme());
try std.testing.expect(std.mem.indexOf(u8, band.items, "▶ \" self.dirty = true;") != null);
try std.testing.expect(std.mem.indexOf(u8, band.items, "/ —") != null);
try std.testing.expect(std.mem.indexOf(u8, band.items, "\"\" · yank") != null);
try std.testing.expect(std.mem.indexOf(u8, band.items, "p after P before R replace y into") != null);
// The empty register's `—` and the names in the dim ink, the verbs'
// letters bold in the key ink.
const inks = p.chrome().on(.focus);
const Cells = struct {
fn at(l: *const pardes.Layer, word: []const u8) ?*const pardes.Cell {
for (0..l.rows) |row| {
const cells = l.cells[row * l.cols ..][0..l.cols];
var x: usize = 0;
while (x + word.len <= cells.len) : (x += 1) {
for (word, cells[x..][0..word.len]) |c, cell| {
if (cell.len != 1 or cell.text[0] != c) break;
} else return &cells[x];
}
}
return null;
}
};
try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, Cells.at(layer, "last search").?.style.fg);
const verbs = Cells.at(layer, "p after").?;
try std.testing.expectEqual(pardes.Color{ .rgb = inks.key }, verbs.style.fg);
try std.testing.expect(verbs.style.bold);
for (0..layer.rows) |row| {
const cells = layer.cells[row * layer.cols ..][0..layer.cols];
for (cells, 0..) |cell, x| if (std.mem.eql(u8, cell.grapheme(), "—") and x > 2 and std.mem.eql(u8, cells[x - 3].grapheme(), "/"))
try std.testing.expectEqual(pardes.Color{ .rgb = inks.dim }, cell.style.fg);
}
// The next row's value in full, every line of it.
p.update(.{ .key = .{ .cp = Key.down } });
_ = frame.reset(.retain_capacity);
_ = try p.render(a);
band = .empty;
for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try band.appendSlice(a, cell.grapheme());
try std.testing.expect(std.mem.indexOf(u8, band.items, "const best = rank(q, name) orelse continue;") != null);
try std.testing.expect(std.mem.indexOf(u8, band.items, "return best;") != null);
// Enter chooses it: its verbs, rolled.
p.update(.{ .key = .{ .cp = Key.enter } });
try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), "\" a ▸ p after P before R replace y into") != null);
try std.testing.expect(!p.view().tag_state.unrolled);
// Backspace: the registers again; a register's own key goes down too.
p.update(.{ .key = .{ .cp = Key.backspace } });
try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), "\" ▸ \" self.dirty") != null);
p.update(.{ .key = .{ .cp = 'a' } });
try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), "\" a ▸ p after") != null);
// p pastes it after the selection, and the tag is at rest.
p.update(.{ .key = .{ .cp = 'p' } });
try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "const best = rank(q, name) orelse continue;") != null);
try std.testing.expect(p.view().tag_state.root == null);
try std.testing.expect(@import("TagState.zig").hostOf(p) == null);
// Esc from the registers: rest, the keyboard where it was.
const id = p.view().active;
p.update(.{ .key = .{ .cp = '"' } });
p.update(.{ .key = .{ .cp = Key.escape } });
try std.testing.expect(p.view().tag_state.root == null);
try std.testing.expectEqual(id, p.view().active);
try std.testing.expectEqual(@as(u21, 0), pane.body.normal.register);
}
|