//! 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; /// 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). delay_ns: u64, /// Its key cell is written at once (SPC, `"`, `C-w`); the others change /// nothing until the delay is up, so `gg` never touches the tag. at_once: bool, 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, .at_once = true, .node = &leader_tree }, .window = .{ .key = .{ .cp = config.window_prefix[0].cp, .ctrl = true }, .cell = "C-w", .label = "window", .delay_ns = 250 * ms, .at_once = true, .node = &window_tree }, .goto = .{ .key = .{ .cp = config.goto_prefix }, .cell = "g", .label = "goto", .delay_ns = 500 * ms, .at_once = false, .node = &goto_tree }, .match = .{ .key = .{ .cp = config.match_prefix }, .cell = "m", .label = "match", .delay_ns = 500 * ms, .at_once = false, .node = &match_tree }, .view = .{ .key = .{ .cp = config.view_prefix }, .cell = "z", .label = "view", .delay_ns = 500 * ms, .at_once = false, .node = &view_tree }, .view_sticky = .{ .key = .{ .cp = config.view_prefix_sticky }, .cell = "Z", .label = "view", .delay_ns = 500 * ms, .at_once = false, .node = &view_sticky_tree }, .prev = .{ .key = .{ .cp = config.prev_prefix }, .cell = "[", .label = "previous", .delay_ns = 500 * ms, .at_once = false, .node = &prev_tree }, .next = .{ .key = .{ .cp = config.next_prefix }, .cell = "]", .label = "next", .delay_ns = 500 * ms, .at_once = false, .node = &next_tree }, .register = .{ .key = .{ .cp = config.register_prefix }, .cell = "\"", .label = "registers", .delay_ns = 300 * ms, .at_once = true, .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. pub const ngroups = groups.len + std.enums.values(Root).len - 1; 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) }; /// 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; for (path) |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, }; /// 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 { 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; } /// 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); }