kraal 0.2.0

A terminal workspace manager for SSH fleets and coding agents
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
//! What keys do: every command kraal has, the presets that bind them, and the lookups the
//! server, its menu, its help and its command search share.
//!
//! Commands are reached with a leader key (`ctrl+b` by default) followed by a short sequence, and
//! a menu shows what can follow. The "kraal" preset gives each theme a letter: the lowercase
//! letter runs the theme's main action (`s` connects to a server), the uppercase one opens the
//! theme's menu (`S`: upload, download, edit the servers). Inside every menu the same letters do
//! the same things (`n` new, `x` close, `e` rename, arrows for previous and next). The "classic"
//! preset keeps tmux's single keys. A few frequent commands also have direct keys that need no
//! leader.

use std::collections::BTreeMap;

use serde::Deserialize;

use crate::input::{Key, KeyCode, KeySpec};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
    NewPane,
    SplitRight,
    SplitDown,
    ClosePane,
    ToggleZoom,
    ToggleFloating,
    NewFloating,
    FocusLeft,
    FocusRight,
    FocusUp,
    FocusDown,
    FocusOrTabLeft,
    FocusOrTabRight,
    ResizeMode,
    ResizeLeft,
    ResizeRight,
    ResizeUp,
    ResizeDown,
    PanePicker,
    RenamePane,
    NewTab,
    NextTab,
    PrevTab,
    CloseTab,
    RenameTab,
    Tab(u8),
    WorkspacePicker,
    NewWorkspace,
    NextWorkspace,
    PrevWorkspace,
    RenameWorkspace,
    CloseWorkspace,
    SaveWorkspace,
    AgentPicker,
    NextAttention,
    SwitchAccount,
    SshPicker,
    EditServers,
    Upload,
    Download,
    Files,
    OpenPreview,
    ToolPicker,
    Runbooks,
    GitActions,
    ScrollMode,
    Search,
    CopyLastOutput,
    Hints,
    ToggleSidebar,
    Messages,
    SelectForBroadcast,
    BroadcastSelected,
    BroadcastTab,
    BroadcastWorkspace,
    BroadcastOff,
    BroadcastToggle,
    CommandPalette,
    Help,
    Detach,
    SendPrefix,
}

use Action::*;

/// Every action (but `Tab(n)`): its name in the configuration, and what it does.
const ACTIONS: &[(Action, &str, &str)] = &[
    (NewPane, "new_pane", "New pane"),
    (SplitRight, "split_right", "Split right"),
    (SplitDown, "split_down", "Split down"),
    (ClosePane, "close_pane", "Close pane"),
    (ToggleZoom, "toggle_zoom", "Zoom pane"),
    (ToggleFloating, "toggle_floating", "Floating panes: show or hide"),
    (NewFloating, "new_floating", "New floating pane"),
    (FocusLeft, "focus_left", "Focus left"),
    (FocusRight, "focus_right", "Focus right"),
    (FocusUp, "focus_up", "Focus up"),
    (FocusDown, "focus_down", "Focus down"),
    (FocusOrTabLeft, "focus_or_tab_left", "Focus left (previous tab at the edge)"),
    (FocusOrTabRight, "focus_or_tab_right", "Focus right (next tab at the edge)"),
    (ResizeMode, "resize_mode", "Resize panes"),
    (ResizeLeft, "resize_left", "Resize left"),
    (ResizeRight, "resize_right", "Resize right"),
    (ResizeUp, "resize_up", "Resize up"),
    (ResizeDown, "resize_down", "Resize down"),
    (PanePicker, "pane_picker", "Find a pane"),
    (RenamePane, "rename_pane", "Rename pane"),
    (NewTab, "new_tab", "New tab"),
    (NextTab, "next_tab", "Next tab"),
    (PrevTab, "prev_tab", "Previous tab"),
    (CloseTab, "close_tab", "Close tab"),
    (RenameTab, "rename_tab", "Rename tab"),
    (WorkspacePicker, "workspace_picker", "Choose a workspace"),
    (NewWorkspace, "new_workspace", "New workspace"),
    (NextWorkspace, "next_workspace", "Next workspace"),
    (PrevWorkspace, "prev_workspace", "Previous workspace"),
    (RenameWorkspace, "rename_workspace", "Rename workspace"),
    (CloseWorkspace, "close_workspace", "Close workspace"),
    (SaveWorkspace, "save_workspace", "Save workspace layout"),
    (AgentPicker, "agent_picker", "Start an agent"),
    (NextAttention, "next_attention", "Next agent needing you"),
    (SwitchAccount, "switch_account", "Change the agent's account"),
    (SshPicker, "ssh_picker", "Connect to a server"),
    (EditServers, "edit_servers", "Edit saved servers"),
    (Upload, "upload", "Upload to this pane's server"),
    (Download, "download", "Download from this pane's server"),
    (Files, "files", "File manager"),
    (OpenPreview, "open_preview", "Preview a file"),
    (ToolPicker, "tools", "Tools here (where this pane is)"),
    (Runbooks, "runbooks", "Runbooks"),
    (GitActions, "git_actions", "Git and worktrees"),
    (ScrollMode, "scroll_mode", "Copy mode: scroll and select"),
    (Search, "search", "Search the output"),
    (CopyLastOutput, "copy_last_output", "Copy the last command's output"),
    (Hints, "hints", "Open a link or path (hints on screen)"),
    (ToggleSidebar, "toggle_sidebar", "Sidebar"),
    (Messages, "messages", "Message log"),
    (SelectForBroadcast, "select_for_broadcast", "Mark for broadcast (this pane)"),
    (BroadcastSelected, "broadcast_selected", "Broadcast to the marked panes"),
    (BroadcastTab, "broadcast_tab", "Broadcast to this tab"),
    (BroadcastWorkspace, "broadcast_workspace", "Broadcast to this workspace"),
    (BroadcastOff, "broadcast_off", "Stop broadcasting"),
    (BroadcastToggle, "broadcast_toggle", "Broadcast on/off (this tab)"),
    (CommandPalette, "command_palette", "Search commands"),
    (Help, "help", "Help"),
    (Detach, "detach", "Detach (programs keep running)"),
    (SendPrefix, "send_prefix", "Send the prefix key"),
];

impl Action {
    pub fn parse(name: &str) -> Option<Action> {
        if let Some(&(a, _, _)) = ACTIONS.iter().find(|(_, n, _)| *n == name) {
            return Some(a);
        }
        // Names of earlier versions.
        match name {
            "toggle_sync" => return Some(BroadcastToggle),
            "mark_pane" => return Some(SelectForBroadcast),
            _ => {}
        }
        let n: u8 = name.strip_prefix("tab_")?.parse().ok()?;
        (1..=9).contains(&n).then_some(Tab(n))
    }

    pub fn name(self) -> String {
        match self {
            Tab(n) => format!("tab_{n}"),
            a => ACTIONS.iter().find(|(x, _, _)| *x == a).map(|(_, n, _)| n.to_string()).unwrap_or_default(),
        }
    }

    pub fn describe(self) -> String {
        match self {
            Tab(n) => format!("Go to tab {n}"),
            a => ACTIONS.iter().find(|(x, _, _)| *x == a).map(|(_, _, d)| d.to_string()).unwrap_or_default(),
        }
    }

    /// The description without its explanation (after a colon, or in parentheses): what the
    /// menu shows.
    pub fn label(self) -> String {
        let d = self.describe();
        let short = d.split(" (").next().unwrap_or(&d);
        short.split(':').next().unwrap_or(short).trim().to_string()
    }

    /// Every action, in the order of the reference (tabs 1-9 as one).
    pub fn all() -> impl Iterator<Item = Action> {
        ACTIONS.iter().map(|(a, _, _)| *a).chain(std::iter::once(Tab(1)))
    }
}

/// What a key sequence runs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    Action(Action),
    /// A tool of `[tools]`, by name.
    Tool(String),
}

type Table = &'static [(&'static str, &'static [&'static str])];

/// A menu of a preset: its name in the configuration (`menu_<id>`), the key that opens it, its
/// title, and its main action (the one its theme's lowercase letter runs).
type MenuDef = (&'static str, &'static str, &'static str, Action);

/// A set of default bindings.
pub struct Preset {
    pub name: &'static str,
    /// Sequences after the leader (keys separated by spaces), in menu order. `{id}` stands for
    /// the key of menu `id`, `{prefix}` for the prefix key.
    leader: Table,
    direct: Table,
    menus: &'static [MenuDef],
    /// What a tool's `key` follows.
    tool_menu: &'static str,
}

pub const KRAAL: Preset = Preset {
    name: "kraal",
    leader: &[
        // The main action of each theme; its uppercase letter opens the theme's menu.
        ("ssh_picker", &["s", "{servers} s", "{servers} enter"]),
        ("broadcast_toggle", &["b", "{broadcast} b", "{broadcast} enter"]),
        ("workspace_picker", &["w", "{workspaces} w", "{workspaces} enter"]),
        ("agent_picker", &["a", "{agents} a", "{agents} enter"]),
        ("new_tab", &["t", "{tabs} t", "{tabs} n", "{tabs} enter"]),
        ("pane_picker", &["p", "{panes} p", "{panes} enter"]),
        ("scroll_mode", &["v", "{view} v", "{view} enter"]),
        ("files", &["f", "{files} f", "{files} enter"]),
        ("tools", &["r", "{run} r", "{run} enter"]),
        // Verbs and fixed keys.
        ("new_pane", &["n", "{panes} n"]),
        ("close_pane", &["x", "{panes} x"]),
        ("toggle_zoom", &["z"]),
        ("select_for_broadcast", &["m", "{broadcast} m"]),
        ("hints", &["o", "{view} o"]),
        ("search", &["g", "/", "{view} g"]),
        ("focus_left", &["left"]),
        ("focus_down", &["down"]),
        ("focus_up", &["up"]),
        ("focus_right", &["right"]),
        ("tab_1", &["1"]),
        ("tab_2", &["2"]),
        ("tab_3", &["3"]),
        ("tab_4", &["4"]),
        ("tab_5", &["5"]),
        ("tab_6", &["6"]),
        ("tab_7", &["7"]),
        ("tab_8", &["8"]),
        ("tab_9", &["9"]),
        ("command_palette", &["space"]),
        ("help", &["h", "?"]),
        ("detach", &["d"]),
        ("send_prefix", &["{prefix}"]),
        // The rest of each menu.
        ("split_right", &["{panes} right"]),
        ("split_down", &["{panes} down"]),
        ("rename_pane", &["{panes} e"]),
        ("resize_mode", &["{panes} r"]),
        ("new_floating", &["{panes} f"]),
        ("prev_tab", &["{tabs} left"]),
        ("next_tab", &["{tabs} right"]),
        ("rename_tab", &["{tabs} e"]),
        ("close_tab", &["{tabs} x"]),
        ("new_workspace", &["{workspaces} n"]),
        ("prev_workspace", &["{workspaces} left"]),
        ("next_workspace", &["{workspaces} right"]),
        ("rename_workspace", &["{workspaces} e"]),
        ("save_workspace", &["{workspaces} s"]),
        ("close_workspace", &["{workspaces} x"]),
        ("next_attention", &["{agents} g"]),
        ("switch_account", &["{agents} c"]),
        ("upload", &["{servers} u", "{files} u"]),
        ("download", &["{servers} d", "{files} d"]),
        ("edit_servers", &["{servers} e"]),
        ("open_preview", &["{files} p"]),
        ("runbooks", &["{run} b"]),
        ("git_actions", &["{run} g"]),
        ("toggle_floating", &["{view} f"]),
        ("toggle_sidebar", &["{view} l"]),
        ("messages", &["{view} j"]),
        ("broadcast_workspace", &["{broadcast} w"]),
        ("broadcast_selected", &["{broadcast} s"]),
        ("broadcast_off", &["{broadcast} o"]),
        ("copy_last_output", &["{view} c"]),
    ],
    direct: &[
        ("focus_or_tab_left", &["alt+left"]),
        ("focus_or_tab_right", &["alt+right"]),
        ("focus_up", &["alt+up"]),
        ("focus_down", &["alt+down"]),
        ("new_pane", &["alt+n"]),
        ("next_attention", &["alt+a"]),
    ],
    menus: &[
        ("servers", "S", "Servers", SshPicker),
        ("broadcast", "B", "Broadcast", BroadcastToggle),
        ("workspaces", "W", "Workspaces", WorkspacePicker),
        ("agents", "A", "Agents", AgentPicker),
        ("tabs", "T", "Tabs", NewTab),
        ("panes", "P", "Panes", PanePicker),
        ("view", "V", "View", ScrollMode),
        ("files", "F", "Files", Files),
        ("run", "R", "Run", ToolPicker),
    ],
    tool_menu: "{run}",
};

/// tmux's keys, as kraal had them first.
pub const CLASSIC: Preset = Preset {
    name: "classic",
    leader: &[
        ("split_right", &["%", "|"]),
        ("split_down", &["\"", "-"]),
        ("close_pane", &["x"]),
        ("toggle_zoom", &["z"]),
        ("toggle_floating", &["t"]),
        ("new_floating", &["F"]),
        ("files", &["f"]),
        ("focus_left", &["h", "left"]),
        ("focus_right", &["l", "right"]),
        ("focus_up", &["k", "up"]),
        ("focus_down", &["j", "down"]),
        ("resize_left", &["H", "ctrl+left"]),
        ("resize_right", &["L", "ctrl+right"]),
        ("resize_up", &["K", "ctrl+up"]),
        ("resize_down", &["J", "ctrl+down"]),
        ("new_tab", &["c"]),
        ("next_tab", &["n", "tab"]),
        ("prev_tab", &["p", "shift+tab"]),
        ("close_tab", &["&"]),
        ("rename_tab", &[","]),
        ("rename_pane", &["."]),
        ("rename_workspace", &["$"]),
        ("tab_1", &["1"]),
        ("tab_2", &["2"]),
        ("tab_3", &["3"]),
        ("tab_4", &["4"]),
        ("tab_5", &["5"]),
        ("tab_6", &["6"]),
        ("tab_7", &["7"]),
        ("tab_8", &["8"]),
        ("tab_9", &["9"]),
        ("next_workspace", &[")"]),
        ("prev_workspace", &["("]),
        ("workspace_picker", &["o", "w"]),
        ("ssh_picker", &["s"]),
        ("upload", &["U"]),
        ("download", &["D"]),
        ("pane_picker", &["g"]),
        ("agent_picker", &["G"]),
        ("switch_account", &["A"]),
        ("git_actions", &["R"]),
        ("tools", &["T"]),
        ("hints", &["space"]),
        ("runbooks", &["r"]),
        ("next_attention", &["a"]),
        ("toggle_sidebar", &["b"]),
        ("broadcast_toggle", &["y"]),
        ("select_for_broadcast", &["m"]),
        ("scroll_mode", &["[", "pageup", "v"]),
        ("search", &["/"]),
        ("open_preview", &["e"]),
        ("save_workspace", &["S"]),
        ("command_palette", &[":"]),
        ("detach", &["d", "q"]),
        ("help", &["?"]),
        ("send_prefix", &["{prefix}"]),
        ("copy_last_output", &["Y"]),
    ],
    direct: &[
        ("focus_or_tab_left", &["alt+h", "alt+left"]),
        ("focus_or_tab_right", &["alt+l", "alt+right"]),
        ("focus_up", &["alt+k", "alt+up"]),
        ("focus_down", &["alt+j", "alt+down"]),
        ("new_pane", &["alt+n"]),
        ("toggle_floating", &["alt+f"]),
        ("next_attention", &["alt+a"]),
        ("workspace_picker", &["alt+o"]),
        ("agent_picker", &["alt+g"]),
    ],
    menus: &[],
    tool_menu: "",
};

pub const PRESETS: [&Preset; 2] = [&KRAAL, &CLASSIC];

/// `[keys]` of the configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct KeysConfig {
    /// "kraal" or "classic".
    pub preset: String,
    pub prefix: Vec<String>,
    /// Per action, replacing the preset's: sequences after the prefix. `menu_<id>` gives the
    /// keys that open a menu (`menu_servers = ["M"]`).
    #[serde(default)]
    pub leader: BTreeMap<String, Vec<String>>,
    /// The earlier name of `leader`.
    #[serde(default)]
    pub prefixed: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    pub direct: BTreeMap<String, Vec<String>>,
}

/// What the keys typed after the leader lead to.
#[derive(Debug, PartialEq)]
pub enum Lookup {
    Run(Command),
    /// A menu: more keys to come.
    More,
    Nothing,
}

/// One line of the leader menu.
#[derive(Debug, Clone, PartialEq)]
pub struct MenuEntry {
    pub key: KeySpec,
    pub label: String,
    /// It opens a further menu.
    pub group: bool,
    pub command: Option<Command>,
    /// The main action of a theme, whose menu its uppercase letter opens.
    pub main: bool,
}

/// A menu of the keymap: the keys that open it after the prefix, its title, and its main action.
#[derive(Debug, Clone)]
pub struct Menu {
    pub id: &'static str,
    pub keys: Vec<KeySpec>,
    pub title: &'static str,
    pub main: Action,
}

/// `text` without a leading `word` (any case) and the space after it, capitalised.
fn strip_word(text: &str, word: &str) -> Option<String> {
    let head = text.get(..word.len())?;
    let rest = text[word.len()..].strip_prefix(' ')?;
    let mut chars = rest.chars();
    let first = chars.next()?;
    head.eq_ignore_ascii_case(word).then(|| first.to_uppercase().chain(chars).collect())
}

/// Resolved key bindings.
#[derive(Debug, Clone, Default)]
pub struct Keymap {
    pub preset: &'static str,
    pub prefix: Vec<KeySpec>,
    pub direct: Vec<(KeySpec, Action)>,
    /// Sequences after the prefix, in menu order.
    pub leader: Vec<(Vec<KeySpec>, Command)>,
    pub menus: Vec<Menu>,
    /// What a tool's key follows: each key of the tool menu, or nothing (tools then follow the
    /// prefix directly).
    tool_menu: Vec<Vec<KeySpec>>,
}

/// The sequences `text` stands for. `{id}` is each key of menu `id` (none when the menu has no
/// key), `{prefix}` each prefix key.
fn expand(text: &str, menus: &[Menu], prefix: &[KeySpec]) -> Result<Vec<Vec<KeySpec>>, String> {
    let mut out: Vec<Vec<KeySpec>> = vec![Vec::new()];
    let mut empty = true;
    for token in text.split_whitespace() {
        empty = false;
        let named = token.strip_prefix('{').and_then(|t| t.strip_suffix('}'));
        let choices: Vec<KeySpec> = match named {
            Some("prefix") => prefix.to_vec(),
            Some(id) => menus
                .iter()
                .find(|m| m.id == id)
                .map(|m| m.keys.clone())
                .ok_or_else(|| format!("{token:?}: no such menu"))?,
            None => vec![KeySpec::parse(token).map_err(|e| format!("{token:?}: {e}"))?],
        };
        out = out
            .into_iter()
            .flat_map(|seq| {
                choices.iter().map(move |k| {
                    let mut seq = seq.clone();
                    seq.push(k.clone());
                    seq
                })
            })
            .collect();
    }
    if empty {
        return Err("empty".into());
    }
    Ok(out)
}

/// Bindings of `table`, with the user's entries replacing the preset's for their actions.
/// Entries naming a menu (`menu_<id>`) are not actions: [`Keymap::build`] reads them.
fn bindings(
    preset: Table,
    user: &[&BTreeMap<String, Vec<String>>],
    ctx: &str,
    (menus, prefix): (&[Menu], &[KeySpec]),
    warnings: &mut Vec<String>,
) -> Vec<(Vec<KeySpec>, Action)> {
    let is_menu = |name: &str| name.starts_with("menu_");
    let overridden: Vec<&str> = user.iter().flat_map(|m| m.keys()).map(String::as_str).collect();
    let mut out = Vec::new();
    let mut add = |name: &str, seqs: &[String], warnings: &mut Vec<String>| {
        let Some(action) = Action::parse(name) else {
            warnings.push(format!("{ctx}: unknown action {name:?}"));
            return;
        };
        for s in seqs {
            match expand(s, menus, prefix) {
                Ok(all) => out.extend(all.into_iter().map(|keys| (keys, action))),
                Err(e) => warnings.push(format!("{ctx}.{name}: invalid key {e}")),
            }
        }
    };
    for (name, seqs) in preset.iter().filter(|(n, _)| !overridden.contains(n)) {
        let seqs: Vec<String> = seqs.iter().map(|s| s.to_string()).collect();
        add(name, &seqs, warnings);
    }
    for map in user {
        for (name, seqs) in map.iter().filter(|(n, _)| !is_menu(n)) {
            add(name, seqs, warnings);
        }
    }
    out
}

/// A section of the reference: its title, and rows of keys with what they do.
pub type Section = (String, Vec<(String, String)>);

/// Keys and what they do in lists, text fields, questions and modes: fixed, the same in every
/// preset.
pub const MODE_KEYS: &[(&str, &[(&str, &str)])] = &[
    (
        "In lists",
        &[
            ("type", "filter"),
            ("↑ ↓", "move"),
            ("⏎", "choose"),
            ("tab", "more actions on the selected item"),
            ("esc", "close"),
        ],
    ),
    (
        "In text fields",
        &[
            ("← → home end", "move (alt+← → by word)"),
            ("ctrl+w ctrl+u ctrl+k", "delete a word, to the start, to the end"),
            ("⏎ / esc", "accept / cancel"),
        ],
    ),
    (
        "In questions",
        &[
            ("y / n", "yes / no"),
            ("← → tab", "move between the answers"),
            ("⏎", "the selected answer"),
            ("↑ ↓", "scroll a long question"),
            ("esc", "no"),
        ],
    ),
    (
        "Copy mode",
        &[
            ("arrows hjkl", "move"),
            ("w b e", "next word, previous word, end of word"),
            ("0 $ home end", "start, end of the line"),
            ("g G", "top, bottom"),
            ("pageup pagedown", "a page up, down (ctrl+u ctrl+d: half a page)"),
            ("v V ctrl+v", "select characters, lines, a block"),
            ("y or ⏎", "copy and leave"),
            ("/ n N", "search, next, previous"),
            ("p P", "the prompt above, below (shells that mark commands)"),
            ("o O", "select a command's output, the whole command"),
            ("esc q", "leave"),
        ],
    ),
    (
        "Searching the output",
        &[
            ("type", "the text to find"),
            ("↑ ↓", "older, newer match"),
            ("⏎", "keep the match and go on in copy mode"),
            ("esc", "cancel"),
        ],
    ),
    ("Resizing", &[("arrows hjkl", "move the border"), ("⏎ or esc", "done")]),
    (
        "Hints",
        &[("a label", "copy what it marks, or act on it"), ("tab", "switch between copy and act"), ("esc", "cancel")],
    ),
    (
        "Mouse",
        &[
            ("click", "focus a pane, tab, workspace or agent"),
            ("drag a border", "resize panes"),
            ("drag in a pane", "select and copy (double: word, triple: line)"),
            ("ctrl+click", "open a link; on a frame's top: mark for broadcast"),
            ("shift + mouse", "your terminal's own selection"),
        ],
    ),
];

/// Whether two bindings would catch the same key press (`ctrl+m` and `enter` do).
fn same_key(a: &KeySpec, b: &KeySpec) -> bool {
    a.matches(&Key { code: b.code, mods: b.mods, raw: Vec::new() })
        || b.matches(&Key { code: a.code, mods: a.mods, raw: Vec::new() })
}

fn starts_with(seq: &[KeySpec], typed: &[Key]) -> bool {
    seq.len() >= typed.len() && seq.iter().zip(typed).all(|(s, k)| s.matches(k))
}

impl Keymap {
    /// Build from the configuration; also returns warnings about entries that were left out.
    pub fn build(cfg: &KeysConfig) -> (Keymap, Vec<String>) {
        let mut warnings = Vec::new();
        let preset = PRESETS.iter().find(|p| p.name == cfg.preset).copied().unwrap_or_else(|| {
            warnings.push(format!("keys.preset: no preset {:?} (kraal or classic)", cfg.preset));
            &KRAAL
        });
        let prefix: Vec<KeySpec> = cfg
            .prefix
            .iter()
            .filter_map(|s| {
                KeySpec::parse(s).map_err(|e| warnings.push(format!("keys.prefix: invalid key {s:?}: {e}"))).ok()
            })
            .collect();
        // The menus first: the leader's sequences name them.
        let user = [&cfg.prefixed, &cfg.leader];
        let mut menus = Vec::new();
        for &(id, key, title, main) in preset.menus {
            let name = format!("menu_{id}");
            let keys = match user.iter().rev().find_map(|m| m.get(&name)) {
                Some(list) => list
                    .iter()
                    .filter_map(|k| {
                        KeySpec::parse(k).map_err(|e| warnings.push(format!("keys.leader.{name}: {e}"))).ok()
                    })
                    .collect(),
                None => KeySpec::parse(key).into_iter().collect(),
            };
            menus.push(Menu { id, keys, title, main });
        }
        for name in user.iter().flat_map(|m| m.keys()).filter(|n| n.starts_with("menu_")) {
            if !menus.iter().any(|m| name[5..] == *m.id) {
                warnings.push(format!("keys.leader: no menu {name:?} in the {} preset", preset.name));
            }
        }
        let direct: Vec<(KeySpec, Action)> =
            bindings(preset.direct, &[&cfg.direct], "keys.direct", (&menus, &prefix), &mut warnings)
                .into_iter()
                .filter_map(|(mut keys, a)| {
                    if keys.len() > 1 {
                        warnings.push(format!("keys.direct.{}: one key, not a sequence", a.name()));
                        return None;
                    }
                    Some((keys.remove(0), a))
                })
                .collect();
        // A direct key that is also the prefix, or bound twice, would shadow the other.
        let mut kept: Vec<(KeySpec, Action)> = Vec::new();
        for (k, a) in direct {
            if prefix.iter().any(|p| same_key(p, &k)) {
                warnings.push(format!("keys.direct.{}: {k} is the prefix key", a.name()));
            } else if let Some((_, other)) = kept.iter().find(|(x, _)| same_key(x, &k)) {
                warnings.push(format!("keys.direct.{}: {k} is already {:?}", a.name(), other.describe()));
            } else {
                kept.push((k, a));
            }
        }
        let leader = bindings(preset.leader, &user, "keys.leader", (&menus, &prefix), &mut warnings);
        let tool_menu = match preset.tool_menu {
            "" => vec![Vec::new()],
            t => expand(t, &menus, &prefix).unwrap_or_default(),
        };
        let mut km = Keymap { preset: preset.name, prefix, direct: kept, menus, tool_menu, ..Keymap::default() };
        for (keys, a) in leader {
            km.add(keys, Command::Action(a), &mut warnings);
        }
        (km, warnings)
    }

    /// Bind a sequence, unless it collides with one already bound.
    fn add(&mut self, keys: Vec<KeySpec>, command: Command, warnings: &mut Vec<String>) -> bool {
        let shown = |k: &[KeySpec]| k.iter().map(KeySpec::to_string).collect::<Vec<_>>().join(" ");
        let what = |c: &Command| match c {
            Command::Action(a) => a.describe(),
            Command::Tool(t) => format!("tool {t}"),
        };
        for (other, c) in &self.leader {
            let n = other.len().min(keys.len());
            if other[..n].iter().zip(&keys[..n]).all(|(a, b)| same_key(a, b)) {
                warnings.push(if other.len() == keys.len() {
                    format!("key {:?} is already {:?}", shown(&keys), what(c))
                } else {
                    format!("key {:?} clashes with {:?} ({})", shown(&keys), shown(other), what(c))
                });
                return false;
            }
        }
        self.leader.push((keys, command));
        true
    }

    /// Bind the `key` of each tool (after the preset's tool menu); warnings for invalid or taken
    /// keys.
    pub fn bind_tools(&mut self, tools: &BTreeMap<String, crate::tools::ToolDef>) -> Vec<String> {
        let mut warnings = Vec::new();
        for (name, t) in tools.iter().filter(|(_, t)| t.enabled) {
            let Some(key) = &t.key else { continue };
            match KeySpec::parse(key) {
                Ok(k) => {
                    for menu in self.tool_menu.clone() {
                        let mut keys = menu;
                        keys.push(k.clone());
                        let mut why = Vec::new();
                        if !self.add(keys, Command::Tool(name.clone()), &mut why) {
                            warnings.extend(why.into_iter().map(|w| format!("tools.{name}: {w}")));
                        }
                    }
                }
                Err(e) => warnings.push(format!("tools.{name}: invalid key {key:?}: {e}")),
            }
        }
        warnings
    }

    /// Whether `key` is the prefix: by the character it types, else by its place on the
    /// keyboard (see [`Key::by_place`]) when no direct key takes it as typed.
    pub fn is_prefix(&self, key: &Key) -> bool {
        let prefix = |k: &Key| self.prefix.iter().any(|p| p.matches(k));
        prefix(key) || (self.direct_typed(key).is_none() && key.by_place().is_some_and(|k| prefix(&k)))
    }

    /// The action of a direct key: by the character typed, else by the key's place when the
    /// prefix does not take it as typed.
    pub fn direct(&self, key: &Key) -> Option<Action> {
        self.direct_typed(key).or_else(|| {
            let typed_prefix = self.prefix.iter().any(|p| p.matches(key));
            key.by_place().filter(|_| !typed_prefix).and_then(|k| self.direct_typed(&k))
        })
    }

    fn direct_typed(&self, key: &Key) -> Option<Action> {
        self.direct.iter().find(|(k, _)| k.matches(key)).map(|(_, a)| *a)
    }

    /// `key` as the keymap reads it after `typed`: as typed when a sequence goes on with it,
    /// else as the key at its place on the keyboard (the digit row, a non-Latin layout) when one
    /// does, so a binding written for a character never loses its key to another's place.
    pub fn leader_key(&self, typed: &[Key], key: Key) -> Key {
        let reads = |k: &Key| {
            let mut keys = typed.to_vec();
            keys.push(k.clone());
            self.lookup(&keys) != Lookup::Nothing
        };
        if reads(&key) {
            return key;
        }
        let place = key.by_place().or_else(|| digit_row(&key));
        match place {
            Some(place) if reads(&place) => place,
            _ => key,
        }
    }

    /// What the keys typed after the leader so far lead to.
    pub fn lookup(&self, typed: &[Key]) -> Lookup {
        let mut more = false;
        for (seq, cmd) in &self.leader {
            if !starts_with(seq, typed) {
                continue;
            }
            if seq.len() == typed.len() {
                return Lookup::Run(cmd.clone());
            }
            more = true;
        }
        if more { Lookup::More } else { Lookup::Nothing }
    }

    /// The keys that can follow `typed`, for the menu: commands and further menus.
    pub fn menu(&self, typed: &[Key]) -> Vec<MenuEntry> {
        let typed_specs: Vec<KeySpec> = typed.iter().map(|k| KeySpec::new(k.code, k.mods)).collect();
        let within = self.group_title(&typed_specs);
        let mut out: Vec<MenuEntry> = Vec::new();
        for (seq, cmd) in &self.leader {
            if seq.len() <= typed.len() || !starts_with(seq, typed) {
                continue;
            }
            let key = seq[typed.len()].clone();
            let group = seq.len() > typed.len() + 1;
            // One line per key, and per command (its first key).
            if out.iter().any(|e| e.key == key || (!group && e.command.as_ref() == Some(cmd))) {
                continue;
            }
            let label = if group {
                self.group_title(&seq[..=typed.len()]).unwrap_or("…").to_string()
            } else {
                let label = match cmd {
                    Command::Action(a) => a.label(),
                    Command::Tool(t) => t.clone(),
                };
                // The menu's name is not repeated: in Broadcast, "Broadcast to this workspace" is
                // "To this workspace".
                match within.and_then(|title| strip_word(&label, title)) {
                    Some(rest) => rest,
                    None => label,
                }
            };
            let main = typed.is_empty() && !group && matches!(cmd, Command::Action(a) if self.is_main(*a));
            out.push(MenuEntry { key, label, group, command: (!group).then(|| cmd.clone()), main });
        }
        // The main actions of the themes, then the other commands, then the menus.
        out.sort_by_key(|e| (e.group, !e.main));
        out
    }

    /// Whether `action` is the main action of one of the menus.
    pub fn is_main(&self, action: Action) -> bool {
        self.menus.iter().any(|m| m.main == action && !m.keys.is_empty())
    }

    /// The title of the menu `keys` open, if it has one.
    pub fn group_title(&self, keys: &[KeySpec]) -> Option<&'static str> {
        match keys {
            [k] => self.menus.iter().find(|m| m.keys.contains(k)).map(|m| m.title),
            _ => None,
        }
    }

    /// `ctrl+b B`: how to open menu `id`.
    pub fn menu_hint(&self, id: &str) -> Option<String> {
        let key = self.menus.iter().find(|m| m.id == id)?.keys.first()?;
        Some(format!("{} {key}", self.prefix_label()))
    }

    /// The whole reference, for the help screen and `kraal config keys`: sections of (keys,
    /// what they do). The keys after the prefix come first, then each menu, the keys without the
    /// prefix, and the fixed keys of lists, fields, questions and modes.
    pub fn reference(&self, ascii: bool) -> Vec<Section> {
        let p = self.prefix_label();
        let seq = |keys: &[KeySpec]| {
            let mut parts = vec![p.clone()];
            parts.extend(keys.iter().map(|k| pretty(k, ascii)));
            parts.join(" ")
        };
        let root = format!("After {p}");
        // Each section, with the commands it lists (a command shows once per section).
        let mut sections: Vec<(Section, Vec<Command>)> = vec![((root.clone(), Vec::new()), Vec::new())];
        for (keys, cmd) in &self.leader {
            let title = match keys.len() {
                1 => root.clone(),
                _ => match self.group_title(&keys[..1]) {
                    Some(t) => format!("{t} ({p} {})", pretty(&keys[0], ascii)),
                    None => format!("{p} {} …", pretty(&keys[0], ascii)),
                },
            };
            let row = match cmd {
                Command::Action(Tab(n)) if *n > 1 && keys.len() == 1 => None,
                Command::Action(FocusDown | FocusRight | FocusUp) if keys.len() == 1 => None,
                Command::Action(FocusLeft) if keys.len() == 1 => Some((
                    format!("{p} {}", if ascii { "arrows" } else { "←↓↑→" }),
                    "Focus the pane on that side".to_string(),
                )),
                Command::Action(Tab(_)) if keys.len() == 1 => Some((format!("{p} 1…9"), "Go to tab 1-9".to_string())),
                Command::Action(a) => Some((seq(keys), a.describe())),
                Command::Tool(t) => Some((seq(keys), format!("Tool: {t}"))),
            };
            let Some(row) = row else { continue };
            match sections.iter_mut().find(|((t, _), _)| *t == title) {
                Some(((_, rows), seen)) => {
                    if !seen.contains(cmd) {
                        seen.push(cmd.clone());
                        rows.push(row);
                    }
                }
                None => sections.push(((title, vec![row]), vec![cmd.clone()])),
            }
        }
        let mut out: Vec<Section> =
            sections.into_iter().map(|(section, _)| section).filter(|(_, rows)| !rows.is_empty()).collect();
        let direct: Vec<(String, String)> = self.direct.iter().map(|(k, a)| (k.to_string(), a.describe())).collect();
        if !direct.is_empty() {
            out.push(("Without the prefix".into(), direct));
        }
        for (title, rows) in MODE_KEYS {
            let shown = |k: &str| {
                if !ascii {
                    return k.to_string();
                }
                [('⏎', "enter"), ('↑', "up"), ('↓', "down"), ('←', "left"), ('→', "right")]
                    .iter()
                    .fold(k.to_string(), |s, (from, to)| s.replace(*from, to))
            };
            out.push((title.to_string(), rows.iter().map(|(k, w)| (shown(k), w.to_string())).collect()));
        }
        out
    }

    /// `ctrl+b p r`, or the direct key: how to reach an action, for hints and help.
    pub fn hint(&self, action: Action) -> Option<String> {
        if let Some((k, _)) = self.direct.iter().find(|(_, a)| *a == action) {
            return Some(k.to_string());
        }
        self.leader_hint(&Command::Action(action))
    }

    /// The leader sequence of a command, with the prefix.
    pub fn leader_hint(&self, command: &Command) -> Option<String> {
        let (seq, _) = self.leader.iter().find(|(_, c)| c == command)?;
        let mut parts = vec![self.prefix_label()];
        parts.extend(seq.iter().map(KeySpec::to_string));
        Some(parts.join(" "))
    }

    /// Every way to reach `command`: direct keys, then leader sequences.
    pub fn all_hints(&self, command: &Command) -> Vec<String> {
        let mut out: Vec<String> = match command {
            Command::Action(a) => self.direct.iter().filter(|(_, x)| x == a).map(|(k, _)| k.to_string()).collect(),
            Command::Tool(_) => Vec::new(),
        };
        let prefix = self.prefix_label();
        out.extend(
            self.leader.iter().filter(|(_, c)| c == command).map(|(seq, _)| {
                format!("{prefix} {}", seq.iter().map(KeySpec::to_string).collect::<Vec<_>>().join(" "))
            }),
        );
        out
    }

    pub fn prefix_label(&self) -> String {
        self.prefix.first().map(|k| k.to_string()).unwrap_or_else(|| "prefix".into())
    }
}

/// A key as menus show it: arrows as arrows (unless `ascii`).
pub fn pretty(key: &KeySpec, ascii: bool) -> String {
    if !ascii && key.mods == Default::default() {
        let arrow = match key.code {
            KeyCode::Left => Some("←"),
            KeyCode::Right => Some("→"),
            KeyCode::Up => Some("↑"),
            KeyCode::Down => Some("↓"),
            KeyCode::Enter => Some("⏎"),
            _ => None,
        };
        if let Some(a) = arrow {
            return a.to_string();
        }
    }
    key.to_string()
}

/// The digit a key of the digit row types on AZERTY keyboards (French and Belgian) without
/// Shift, when the terminal did not say where the key is: a key typed right after the prefix
/// can arrive before kraal asks the terminal for places.
fn digit_row(key: &Key) -> Option<Key> {
    let KeyCode::Char(c) = key.code else { return None };
    // A key whose place the terminal gave is read by it; Shift types the digit itself.
    if key.has_place() || key.mods.ctrl || key.mods.alt || key.mods.shift {
        return None;
    }
    let digit = match c {
        '&' => '1',
        'é' => '2',
        '"' => '3',
        '\'' => '4',
        '(' => '5',
        '-' | '§' => '6',
        'è' => '7',
        '_' | '!' => '8',
        'ç' => '9',
        'à' => '0',
        _ => return None,
    };
    Some(Key { code: KeyCode::Char(digit), mods: crate::input::Mods::NONE, raw: key.raw.clone() })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::Mods;

    fn cfg(user: &str) -> crate::config::Config {
        crate::config::Config::from_user_toml(user).unwrap()
    }

    fn key(c: char) -> Key {
        Key { code: KeyCode::Char(c), mods: Mods::NONE, raw: vec![c as u8] }
    }

    #[test]
    fn presets_bind_cleanly() {
        for preset in PRESETS {
            let (km, warnings) = Keymap::build(&cfg(&format!("[keys]\npreset = \"{}\"\n", preset.name)).keys);
            assert!(warnings.is_empty(), "{}: {warnings:?}", preset.name);
            assert!(km.leader.iter().any(|(_, c)| *c == Command::Action(Tab(9))));
            assert!(km.leader.iter().any(|(_, c)| *c == Command::Action(Help)));
            assert!(km.direct.iter().any(|(_, a)| *a == NextAttention));
        }
        for (a, name, _) in ACTIONS {
            assert_eq!(Action::parse(name), Some(*a));
        }
    }

    #[test]
    fn a_theme_letter_runs_its_main_action_and_its_capital_opens_its_menu() {
        let (km, _) = Keymap::build(&cfg("").keys);
        assert_eq!(km.preset, "kraal");
        let run = |a: Action| Lookup::Run(Command::Action(a));
        for (c, a) in [
            ('s', SshPicker),
            ('b', BroadcastToggle),
            ('w', WorkspacePicker),
            ('a', AgentPicker),
            ('t', NewTab),
            ('p', PanePicker),
            ('v', ScrollMode),
            ('f', Files),
            ('r', ToolPicker),
        ] {
            assert_eq!(km.lookup(&[key(c)]), run(a), "{c}");
            // The same letter inside its menu does the same.
            let menu = key(c.to_ascii_uppercase());
            assert_eq!(km.lookup(std::slice::from_ref(&menu)), Lookup::More, "{c}");
            assert_eq!(km.lookup(&[menu, key(c)]), run(a), "{c} in its menu");
        }
        for (c, a) in [('n', NewPane), ('x', ClosePane), ('z', ToggleZoom), ('m', SelectForBroadcast), ('o', Hints)] {
            assert_eq!(km.lookup(&[key(c)]), run(a), "{c}");
        }
        assert_eq!(km.lookup(&[key('g')]), run(Search));
        assert_eq!(km.lookup(&[key('/')]), run(Search));
        assert_eq!(km.lookup(&[key('?')]), run(Help));
        let right = Key { code: KeyCode::Right, mods: Mods::NONE, raw: Vec::new() };
        assert_eq!(km.lookup(&[key('P'), right]), run(SplitRight));
        assert_eq!(km.lookup(&[key('q')]), Lookup::Nothing);
        // The same verbs in every menu.
        for menu in ['P', 'T', 'W'] {
            assert!(matches!(km.lookup(&[key(menu), key('x')]), Lookup::Run(_)), "{menu} x");
            assert!(matches!(km.lookup(&[key(menu), key('e')]), Lookup::Run(_)), "{menu} e");
        }
    }

    #[test]
    fn the_menu_lists_main_actions_then_keys_then_menus() {
        let (km, _) = Keymap::build(&cfg("").keys);
        let root = km.menu(&[]);
        let first_plain = root.iter().position(|e| !e.main).unwrap();
        let first_menu = root.iter().position(|e| e.group).unwrap();
        assert!(root[..first_plain].iter().all(|e| e.main) && first_plain == 9, "{root:?}");
        assert!(root[first_plain..first_menu].iter().all(|e| !e.main && !e.group));
        assert!(root[first_menu..].iter().all(|e| e.group));
        assert_eq!(root[0].label, "Connect to a server");
        let panes = root.iter().find(|e| e.key == KeySpec::parse("P").unwrap()).unwrap();
        assert!(panes.group && panes.label == "Panes");
        assert!(km.menu(&[key('P')]).iter().any(|e| e.label == "Resize panes"));
        let b: Vec<String> = km.menu(&[key('B')]).into_iter().map(|e| e.label).collect();
        assert_eq!(b[0], "On/off");
        assert!(b.contains(&"To this workspace".to_string()) && b.contains(&"Stop broadcasting".to_string()), "{b:?}");
        assert_eq!(km.hint(SplitRight).as_deref(), Some("ctrl+b P right"));
        assert_eq!(km.hint(SshPicker).as_deref(), Some("ctrl+b s"));
        assert_eq!(km.hint(NewPane).as_deref(), Some("alt+n"));
        assert_eq!(km.menu_hint("broadcast").as_deref(), Some("ctrl+b B"));
        // The reference covers the menus and the modes.
        let reference = km.reference(false);
        assert!(reference.iter().any(|(t, _)| t == "Servers (ctrl+b S)"), "{reference:?}");
        assert!(reference.iter().any(|(t, _)| t == "Copy mode"));
    }

    #[test]
    fn the_prefix_twice_sends_it_whatever_it_is() {
        let (km, warnings) = Keymap::build(&cfg("[keys]\nprefix = [\"ctrl+a\", \"ctrl+space\"]\n").keys);
        assert!(warnings.is_empty(), "{warnings:?}");
        let ctrl = |c: char| Key { code: KeyCode::Char(c), mods: Mods::CTRL, raw: Vec::new() };
        assert_eq!(km.lookup(&[ctrl('a')]), Lookup::Run(Command::Action(SendPrefix)));
        assert_eq!(km.lookup(&[ctrl(' ')]), Lookup::Run(Command::Action(SendPrefix)));
        assert_eq!(km.lookup(&[ctrl('b')]), Lookup::Nothing);
    }

    #[test]
    fn menus_move_like_actions() {
        let (km, warnings) = Keymap::build(&cfg("[keys.leader]\nmenu_servers = [\"M\"]\nmenu_view = []\n").keys);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(km.lookup(&[key('M'), key('u')]), Lookup::Run(Command::Action(Upload)));
        assert_eq!(km.lookup(&[key('S')]), Lookup::Nothing);
        assert_eq!(km.group_title(&[KeySpec::parse("M").unwrap()]), Some("Servers"));
        // Without its menu, the View theme keeps its single keys.
        assert_eq!(km.lookup(&[key('V')]), Lookup::Nothing);
        assert_eq!(km.lookup(&[key('v')]), Lookup::Run(Command::Action(ScrollMode)));
        assert!(!km.is_main(ScrollMode));
        let (_, warnings) = Keymap::build(&cfg("[keys.leader]\nmenu_nope = [\"N\"]\n").keys);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        // A menu on a key taken by an action is reported.
        let (_, warnings) = Keymap::build(&cfg("[keys.leader]\nmenu_tabs = [\"n\"]\n").keys);
        assert!(!warnings.is_empty());
    }

    #[test]
    fn user_bindings_replace_the_preset_and_collisions_are_reported() {
        let (km, warnings) = Keymap::build(&cfg("[keys.leader]\nsplit_right = [\"%\"]\nnew_tab = [\"P\"]\n").keys);
        assert_eq!(km.lookup(&[key('%')]), Lookup::Run(Command::Action(SplitRight)));
        assert!(km.all_hints(&Command::Action(SplitRight)).iter().all(|h| !h.contains("right")));
        assert_eq!(warnings.len(), 1, "P is the Panes menu: {warnings:?}");
        // The older table name still works.
        let (km, warnings) = Keymap::build(&cfg("[keys.prefixed]\ntoggle_sync = [\"y\"]\n").keys);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(km.lookup(&[key('y')]), Lookup::Run(Command::Action(BroadcastToggle)));
        let (_, warnings) = Keymap::build(&cfg("[keys]\npreset = \"emacs\"\n").keys);
        assert_eq!(warnings.len(), 1);
    }

    #[test]
    fn tools_go_in_the_run_menu() {
        let c = cfg("[tools.lazygit]\nkey = \"l\"\n[tools.mine]\ncommand = \"tig\"\nkey = \"g\"\n");
        let (mut km, _) = Keymap::build(&c.keys);
        let warnings = km.bind_tools(&c.tools);
        assert_eq!(warnings.len(), 1, "R g is git: {warnings:?}");
        assert_eq!(km.lookup(&[key('R'), key('l')]), Lookup::Run(Command::Tool("lazygit".into())));
        // Classic: a tool key follows the prefix directly, and may not take a command's key.
        let classic_cfg = cfg(
            "[keys]\npreset = \"classic\"\n[tools.lazygit]\nkey = \"i\"\n[tools.mine]\ncommand = \"tig\"\nkey = \"l\"\n",
        );
        let (mut classic, _) = Keymap::build(&classic_cfg.keys);
        let warnings = classic.bind_tools(&classic_cfg.tools);
        assert!(warnings.len() == 1 && warnings[0].contains("mine"), "l is focus right: {warnings:?}");
        assert_eq!(classic.lookup(&[key('i')]), Lookup::Run(Command::Tool("lazygit".into())));
        assert_eq!(classic.lookup(&[key('l')]), Lookup::Run(Command::Action(FocusRight)));
        // Keys that send the same byte collide (ctrl+m is enter).
        let c = cfg("[tools.mine]\ncommand = \"tig\"\nkey = \"ctrl+m\"\n");
        let (mut km, _) = Keymap::build(&c.keys);
        assert_eq!(km.bind_tools(&c.tools).len(), 1, "R ctrl+m is R enter");
        let (_, warnings) = Keymap::build(&cfg("[keys.direct]\nnew_tab = [\"ctrl+b\"]\n").keys);
        assert!(warnings.iter().any(|w| w.contains("prefix")), "{warnings:?}");
    }

    #[test]
    fn keys_by_their_place_on_the_keyboard() {
        let received = |bytes: &[u8]| match crate::input::InputParser::new().feed(bytes).as_slice() {
            [crate::input::InputEvent::Key(k)] => k.clone(),
            other => panic!("{other:?}"),
        };
        // AZERTY: `&` at the place of `1` is tab 1 in a keymap that does not bind `&`.
        let (km, _) = Keymap::build(&cfg("[keys.leader]\nnew_tab = [\"k\"]\n").keys);
        let amp = received(b"\x1b[38::49;;38u");
        let one = km.leader_key(&[], amp.clone());
        assert_eq!(km.lookup(&[one]), Lookup::Run(Command::Action(Tab(1))));
        // One that binds `&` keeps the key for it: a place never takes a key from a character.
        let (classic, _) = Keymap::build(&cfg("[keys]\npreset = \"classic\"\n").keys);
        let typed = classic.leader_key(&[], amp);
        assert_eq!(classic.lookup(&[typed]), Lookup::Run(Command::Action(CloseTab)));
        // A Russian layout: `л` at the place of `k`, Ctrl+`и` at the place of Ctrl+B.
        let l = km.leader_key(&[], received(b"\x1b[1083::107;;1083u"));
        assert_eq!(km.lookup(&[l]), Lookup::Run(Command::Action(NewTab)));
        assert!(km.is_prefix(&received(b"\x1b[1080::98;5u")));
        assert!(!km.is_prefix(&received(b"\x1b[1080;5u")), "without its place, a Russian letter is itself");
        // Direct keys too: Alt+`т` at the place of Alt+N.
        assert_eq!(km.direct(&received(b"\x1b[1090::110;3u")), Some(NewPane));
        // A Latin letter is the letter it types, wherever it is: AZERTY's `a` at the place of `q`.
        let a = km.leader_key(&[], received(b"\x1b[97::113;;97u"));
        assert_eq!(a.code, KeyCode::Char('a'));
        // Before the terminal says where keys are, AZERTY's digit row still reads as digits,
        // unless the character itself is bound.
        let one = km.leader_key(&[], received(b"&"));
        assert_eq!(km.lookup(&[one]), Lookup::Run(Command::Action(Tab(1))));
        let typed = classic.leader_key(&[], received(b"&"));
        assert_eq!(classic.lookup(&[typed]), Lookup::Run(Command::Action(CloseTab)));
        // Not when the terminal said where the key is: Shift+7 on a US keyboard types `&`.
        let shifted = km.leader_key(&[], received(b"\x1b[55:38:55;2;38u"));
        assert_ne!(km.lookup(&[shifted]), Lookup::Run(Command::Action(Tab(1))));
    }
}