plannotator-tui 0.11.6

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
//! Key bindings: every key the viewer acts on, by action name, rebindable under `[keys]`.
//!
//! An action keeps its name wherever it applies, so `down = ["n", "Down"]` moves down in the
//! document, the tree, the notes and every picker. A context lists the actions one mode
//! dispatches, in the order it tries them; two actions that read the keyboard at the same
//! time may not share a key, and a config that binds one twice is an error that names both.

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Action {
    Up,
    Down,
    Left,
    Right,
    WordForward,
    WordBack,
    WordEnd,
    LineStart,
    LineEnd,
    PageDown,
    PageUp,
    Top,
    Bottom,
    Confirm,
    Back,
    Quit,
    Interrupt,
    CycleFocus,
    Send,
    SendAndClose,
    Approve,
    ToggleTree,
    Reload,
    OpenInEditor,
    PickMessage,
    QuickOpen,
    /// Choose which agent Send goes to: a Pi session or a Herdr agent (`docs/spec-pi-link.md`).
    PickTarget,
    ReviewMenu,
    ResendAll,
    FinishReview,
    UndoFinish,
    Archive,
    ToggleHidden,
    Edit,
    Remove,
    AttachImage,
    RemoveImage,
    Visual,
    VisualLine,
    MoveCursor,
    Comment,
    ClearBlock,
    ClearAll,
    LooksGood,
    Delete,
    /// Copy the waiting selection to the clipboard.
    #[serde(rename = "copy")]
    CopySelection,
    /// Copy the selected lines of the code review's diff. Its own action, so the keys a
    /// config gave the diff before it existed keep their meaning; it takes `copy`'s keys
    /// when only those are set.
    CopyLines,
    Yes,
    No,
    // Code review (`plannotator-tui review`).
    /// Suggest replacement code for the selected new-side lines.
    Suggest,
    /// Comment on the whole file under the cursor.
    FileComment,
    /// Comment on the whole change: a review-level note on no file.
    ChangeComment,
    NextHunk,
    PreviousHunk,
    NextFile,
    PreviousFile,
    /// Split or unified diff.
    ToggleLayout,
    ToggleWrap,
    /// Hide the code review's changes that only touch whitespace, or show them again.
    ToggleWhitespace,
    /// Show the diff's file list and move to it, or close it from there.
    ToggleFiles,
    /// Filter the code review's file list by name.
    FilterFiles,
    /// Pick the kinds of file the code review shows: code, tests, docs, config, generated.
    FilterKinds,
    /// Hide the files marked viewed from the code review, or show them again.
    HideViewed,
    /// Mark the file under the cursor viewed, or not (`docs/spec-review-progress.md`).
    ToggleViewed,
    /// The next or previous file not marked viewed, wrapping around.
    NextUnviewed,
    PreviousUnviewed,
    Help,
    /// The reading column, by eight columns.
    NarrowColumn,
    WidenColumn,
    /// The code review's file list, by four columns. Its own action, so a config that gave
    /// `<` or `>` to a code review key before the list existed keeps the reading column's.
    NarrowFiles,
    WidenFiles,
    /// The code review's notes panel, by four columns.
    NarrowNotes,
    WidenNotes,
    /// The whole file under the cursor as it is now, or back to the diff.
    WholeFile,
    /// The whole file as it was before the change (its base), or back to the diff.
    WholeBase,
    /// Hide the notes rail, or show it again, in the document and in the code review.
    ToggleNotes,
    /// Find text in the open document.
    Search,
    /// The next or previous match of the last search, wrapping at either end.
    NextMatch,
    PreviousMatch,
    /// Search for the identifier on the line and go to its definition.
    GoToDefinition,
    /// Back to the place before a jump, and forward again.
    JumpBack,
    JumpForward,
    /// The code review's diff settings: layout, wrap, line numbers, colours, split ratio.
    DiffSettings,
    /// Move the line between a split diff's sides left or right: less or more of the old side.
    SplitLeft,
    SplitRight,
}

use Action::{
    Approve, Archive, AttachImage, Back, Bottom, ClearAll, ClearBlock, Comment, Confirm, CopyLines,
    CopySelection, CycleFocus, Delete, Down, Edit, FinishReview, Interrupt, Left, LineEnd, LineStart,
    LooksGood, MoveCursor, No, OpenInEditor, PageDown, PageUp, PickMessage, PickTarget, QuickOpen, Quit,
    Reload, Remove, RemoveImage, ResendAll, ReviewMenu, Right, Send, SendAndClose, ToggleHidden, ToggleTree,
    Top, UndoFinish, Up, Visual, VisualLine, WordBack, WordEnd, WordForward, Yes,
};
use Action::{
    ChangeComment, FileComment, Help, NextFile, NextHunk, NextMatch, NextUnviewed, PreviousFile,
    PreviousHunk, PreviousMatch, PreviousUnviewed, Search, Suggest, ToggleFiles, ToggleLayout, ToggleViewed,
    ToggleWrap, WholeBase, WholeFile,
};
use Action::{DiffSettings, SplitLeft, SplitRight, ToggleWhitespace};
use Action::{FilterFiles, FilterKinds, GoToDefinition, HideViewed, JumpBack, JumpForward};
use Action::{NarrowColumn, NarrowFiles, NarrowNotes, ToggleNotes, WidenColumn, WidenFiles, WidenNotes};

/// Browsing, before the focused pane gets the key.
pub(crate) const GLOBAL: &[Action] = &[
    Quit,
    Interrupt,
    CycleFocus,
    Send,
    SendAndClose,
    Approve,
    ReviewMenu,
    ResendAll,
    FinishReview,
    UndoFinish,
    Archive,
    ToggleTree,
    Reload,
    OpenInEditor,
    QuickOpen,
    PickMessage,
    PickTarget,
    ToggleNotes,
];
pub(crate) const TREE: &[Action] = &[Down, Up, Confirm, Right, ToggleHidden, Back];
pub(crate) const RAIL: &[Action] = &[Down, Up, Confirm, Edit, Remove, AttachImage, RemoveImage, Back];
/// `attach-image` and `remove-image` act on the selected block's note here.
pub(crate) const DOCUMENT: &[Action] = &[
    Back,
    Visual,
    VisualLine,
    MoveCursor,
    Down,
    Up,
    Left,
    Right,
    PageDown,
    PageUp,
    Top,
    Bottom,
    Comment,
    Confirm,
    ClearBlock,
    ClearAll,
    AttachImage,
    RemoveImage,
    NarrowColumn,
    WidenColumn,
    Search,
    NextMatch,
    PreviousMatch,
];
/// Marking the selected block, tried only when no `DOCUMENT` action claims the key. They sit
/// outside `SHARED` so a config that gave `a` or `d` to a document action keeps loading.
pub(crate) const BLOCK_MARKS: &[Action] = &[LooksGood, Delete];
/// Cursor motions, in visual mode and while moving the cursor (`move-cursor`).
pub(crate) const MOTION: &[Action] =
    &[Left, Right, Down, Up, WordForward, WordBack, WordEnd, LineStart, LineEnd];
/// While a keyboard selection grows; any other key is a motion.
pub(crate) const VISUAL: &[Action] = &[Back, Confirm, Visual, VisualLine];
/// While a finished selection waits for its kind.
pub(crate) const TOOLBAR: &[Action] = &[LooksGood, Comment, Delete, CopySelection];
pub(crate) const CONFIRM_QUIT: &[Action] = &[Yes, Confirm, No, Back];
/// Before `clear-all` empties the document. Only `yes` clears: `confirm` would let a slip
/// followed by Enter wipe every note.
pub(crate) const CONFIRM_CLEAR: &[Action] = &[Yes, No, Back];
pub(crate) const MENU: &[Action] =
    &[Down, Up, Confirm, Back, ReviewMenu, Interrupt, ResendAll, FinishReview, UndoFinish, Archive];
pub(crate) const PICK: &[Action] = &[Down, Up, PageDown, PageUp, Top, Bottom, Confirm, Back, Quit];
/// The agent picker: up and down as in the message picker; `pick-target` again closes it.
pub(crate) const PICK_TARGET: &[Action] = &[Down, Up, Confirm, Back, PickTarget, Interrupt];
pub(crate) const ARCHIVE: &[Action] = &[Down, Up, Confirm, Back, Archive, Quit, Interrupt];

/// A code review, before the focused pane gets the key.
pub(crate) const REVIEW_GLOBAL: &[Action] = &[
    Quit,
    Interrupt,
    CycleFocus,
    Send,
    SendAndClose,
    ReviewMenu,
    ResendAll,
    FinishReview,
    UndoFinish,
    ChangeComment,
    Reload,
    PickTarget,
    Help,
    ToggleNotes,
    NarrowNotes,
    WidenNotes,
    DiffSettings,
];
/// The diff. `left` and `right` pick the old and the new side.
pub(crate) const DIFF: &[Action] = &[
    Back,
    Visual,
    VisualLine,
    Comment,
    Suggest,
    FileComment,
    Down,
    Up,
    PageDown,
    PageUp,
    Top,
    Bottom,
    NextHunk,
    PreviousHunk,
    NextFile,
    PreviousFile,
    Left,
    Right,
    ToggleLayout,
    ToggleWrap,
    ToggleWhitespace,
    ToggleFiles,
    FilterFiles,
    FilterKinds,
    HideViewed,
    ToggleViewed,
    NextUnviewed,
    PreviousUnviewed,
    WholeFile,
    WholeBase,
    GoToDefinition,
    JumpBack,
    JumpForward,
    NarrowFiles,
    WidenFiles,
    SplitLeft,
    SplitRight,
    Confirm,
    CopyLines,
];
/// The code review's file list.
pub(crate) const FILES: &[Action] = &[
    Down,
    Up,
    PageDown,
    PageUp,
    Top,
    Bottom,
    Confirm,
    Back,
    Left,
    Right,
    ToggleFiles,
    FilterFiles,
    FilterKinds,
    HideViewed,
    ToggleViewed,
    NarrowFiles,
    WidenFiles,
];
/// The kind picker over the file list; Space turns a row on or off.
pub(crate) const KINDS: &[Action] = &[Down, Up, Confirm, Back, FilterKinds, Interrupt];
/// The code review's notes rail.
pub(crate) const NOTES: &[Action] = &[Down, Up, Confirm, Edit, Remove, Back];
pub(crate) const REVIEW_MENU: &[Action] =
    &[Down, Up, Confirm, Back, ReviewMenu, Interrupt, ChangeComment, ResendAll, FinishReview, UndoFinish];
/// The code review's diff settings: up and down pick a setting, left and right change it,
/// Enter (and Space) moves it on; the settings key again closes the menu.
pub(crate) const SETTINGS: &[Action] = &[Down, Up, Left, Right, Confirm, Back, DiffSettings, Interrupt];
/// The code review's key help: the motions scroll it when it does not fit; the rest close it.
pub(crate) const HELP: &[Action] = &[Back, Help, Quit, Interrupt, Down, Up, PageDown, PageUp];

/// Contexts that read the same keypress: the global keys come first while browsing, and
/// roaming tries the motions before the document's own keys.
const SHARED: &[&[&[Action]]] = &[
    &[GLOBAL, TREE],
    &[GLOBAL, RAIL],
    &[GLOBAL, DOCUMENT],
    &[GLOBAL, MOTION],
    &[GLOBAL, VISUAL, MOTION],
    &[GLOBAL, TOOLBAR],
    &[CONFIRM_QUIT],
    &[CONFIRM_CLEAR],
    &[MENU],
    &[PICK],
    &[ARCHIVE],
    &[REVIEW_GLOBAL, DIFF],
    &[REVIEW_GLOBAL, NOTES],
    &[REVIEW_GLOBAL, FILES],
    &[KINDS],
    &[REVIEW_MENU],
    &[SETTINGS],
    &[HELP],
];

/// Named keys, spelled as the config file writes them.
const NAMED: [(&str, KeyCode); 13] = [
    ("Up", KeyCode::Up),
    ("Down", KeyCode::Down),
    ("Left", KeyCode::Left),
    ("Right", KeyCode::Right),
    ("Home", KeyCode::Home),
    ("End", KeyCode::End),
    ("PageUp", KeyCode::PageUp),
    ("PageDown", KeyCode::PageDown),
    ("Enter", KeyCode::Enter),
    ("Esc", KeyCode::Esc),
    ("Tab", KeyCode::Tab),
    ("Delete", KeyCode::Delete),
    ("Backspace", KeyCode::Backspace),
];

/// One binding: a character or a named key, optionally with Ctrl.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Key {
    code: KeyCode,
    ctrl: bool,
}

const fn ch(c: char) -> Key {
    Key { code: KeyCode::Char(c), ctrl: false }
}

const fn ctrl(c: char) -> Key {
    Key { code: KeyCode::Char(c), ctrl: true }
}

const fn named(code: KeyCode) -> Key {
    Key { code, ctrl: false }
}

impl Key {
    /// A Ctrl binding needs Ctrl alone. A plain binding allows Shift, as a shifted letter
    /// arrives with Shift set, but not Ctrl; Ctrl with Alt still counts as plain, because
    /// Windows reports `AltGr` that way and `AltGr` types ordinary characters.
    /// A terminal that reports Shift+e as `e` with Shift (a kitty `CSI 101;2u`) means `E`.
    fn matches(self, key: &KeyEvent) -> bool {
        let ctrl_or_alt = key.modifiers & (KeyModifiers::CONTROL | KeyModifiers::ALT);
        let held_ctrl = ctrl_or_alt == KeyModifiers::CONTROL;
        let code = match key.code {
            KeyCode::Char(c) if c.is_ascii_lowercase() && key.modifiers.contains(KeyModifiers::SHIFT) => {
                KeyCode::Char(c.to_ascii_uppercase())
            }
            code => code,
        };
        self.code == code && if self.ctrl { key.modifiers == KeyModifiers::CONTROL } else { !held_ctrl }
    }

    /// How the in-app hints spell the key: `j`, `G`, `enter`, `ctrl+d`.
    fn hint(self) -> String {
        match self.code {
            KeyCode::Char(_) => self.to_string(),
            _ => self.to_string().to_lowercase(),
        }
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.ctrl {
            f.write_str("ctrl+")?;
        }
        match (self.code, NAMED.iter().find(|(_, code)| *code == self.code)) {
            (_, Some((name, _))) => f.write_str(name),
            (KeyCode::Char(c), None) => write!(f, "{c}"),
            (other, None) => write!(f, "{other:?}"),
        }
    }
}

impl FromStr for Key {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> anyhow::Result<Self> {
        let (ctrl, rest) = s.strip_prefix("ctrl+").map_or((false, s), |rest| (true, rest));
        if let Some((_, code)) = NAMED.iter().find(|(name, _)| name.eq_ignore_ascii_case(rest)) {
            return Ok(Self { code: *code, ctrl });
        }
        let mut chars = rest.chars();
        if let (Some(c), None) = (chars.next(), chars.next()) {
            return Ok(Self { code: KeyCode::Char(c), ctrl });
        }
        let names: Vec<&str> = NAMED.iter().map(|(name, _)| *name).collect();
        anyhow::bail!(
            "unknown key {s:?}; expected one character, ctrl+<character>, or one of {}",
            names.join(", ")
        )
    }
}

impl Serialize for Key {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Key {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        text.parse().map_err(serde::de::Error::custom)
    }
}

const DEFAULTS: &[(Action, &[Key])] = &[
    (Up, &[ch('k'), named(KeyCode::Up)]),
    (Down, &[ch('j'), named(KeyCode::Down)]),
    (Left, &[ch('h'), named(KeyCode::Left)]),
    (Right, &[ch('l'), named(KeyCode::Right)]),
    (WordForward, &[ch('w')]),
    (WordBack, &[ch('b')]),
    (WordEnd, &[ch('e')]),
    (LineStart, &[ch('0'), named(KeyCode::Home)]),
    (LineEnd, &[ch('$'), named(KeyCode::End)]),
    (PageDown, &[ctrl('d'), named(KeyCode::PageDown)]),
    (PageUp, &[ctrl('u'), named(KeyCode::PageUp)]),
    (Top, &[ch('g'), named(KeyCode::Home)]),
    (Bottom, &[ch('G'), named(KeyCode::End)]),
    (Confirm, &[named(KeyCode::Enter)]),
    (Back, &[named(KeyCode::Esc)]),
    (Quit, &[ch('q')]),
    (Interrupt, &[ctrl('c')]),
    (CycleFocus, &[named(KeyCode::Tab)]),
    (Send, &[ch('E')]),
    (SendAndClose, &[ch('S')]),
    (Approve, &[ch('A')]),
    (ToggleTree, &[ch('t')]),
    (Reload, &[ch('r')]),
    (OpenInEditor, &[ch('o')]),
    (PickMessage, &[ch('p')]),
    (QuickOpen, &[ctrl('p')]),
    (PickTarget, &[ch('P')]),
    (ReviewMenu, &[ch('m')]),
    (ResendAll, &[ch('R')]),
    (FinishReview, &[ch('F')]),
    (UndoFinish, &[ch('U')]),
    (Archive, &[ch('H')]),
    (ToggleHidden, &[ch('.')]),
    (Edit, &[ch('e')]),
    (Remove, &[ch('x'), named(KeyCode::Delete)]),
    (AttachImage, &[ch('I')]),
    (RemoveImage, &[ch('D')]),
    (Visual, &[ch('v')]),
    (VisualLine, &[ch('V')]),
    (MoveCursor, &[ch('i')]),
    (Comment, &[ch('c')]),
    (ClearBlock, &[ch('x')]),
    (ClearAll, &[ch('X')]),
    (LooksGood, &[ch('a')]),
    (Delete, &[ch('d')]),
    (CopySelection, &[ch('y')]),
    (CopyLines, &[ch('y')]),
    (Yes, &[ch('y'), ch('Y')]),
    (No, &[ch('n'), ch('N')]),
    (Suggest, &[ch('s')]),
    (FileComment, &[ch('C')]),
    (ChangeComment, &[ch('M')]),
    (NextHunk, &[ch(']')]),
    (PreviousHunk, &[ch('[')]),
    (NextFile, &[ch('n')]),
    (PreviousFile, &[ch('N')]),
    (ToggleLayout, &[ch('u')]),
    (ToggleWrap, &[ch('w')]),
    (ToggleWhitespace, &[ch('W')]),
    (ToggleFiles, &[ch('f')]),
    (FilterFiles, &[ch('/')]),
    (FilterKinds, &[ch('t')]),
    (HideViewed, &[ch('H')]),
    (ToggleViewed, &[ch('x')]),
    // `n` with Ctrl: the next file, skipping viewed ones. Ctrl+Shift+N reaches most
    // terminals as Ctrl+N, so the backward jump has no default key.
    (NextUnviewed, &[ctrl('n')]),
    (PreviousUnviewed, &[]),
    (Help, &[ch('?')]),
    (NarrowColumn, &[ch('<')]),
    (WidenColumn, &[ch('>')]),
    (NarrowFiles, &[ch('<')]),
    (WidenFiles, &[ch('>')]),
    (NarrowNotes, &[ch('}')]),
    (WidenNotes, &[ch('{')]),
    (WholeFile, &[ch('o')]),
    (WholeBase, &[ch('O')]),
    (ToggleNotes, &[ch('z')]),
    (Search, &[ch('/')]),
    (NextMatch, &[ch('n')]),
    (PreviousMatch, &[ch('N')]),
    (GoToDefinition, &[ch('d')]),
    (JumpBack, &[ctrl('o')]),
    // Ctrl+I is Tab in terminals that do not tell them apart; there `cycle-focus` gets it.
    (JumpForward, &[ctrl('i')]),
    (DiffSettings, &[ch(',')]),
    (SplitLeft, &[ch('(')]),
    (SplitRight, &[ch(')')]),
];

/// Actions added after configs were written: `approve` (live only in a gated review), `copy`
/// (on a waiting selection), `word-end`, `visual-line`, the code review's own, the reading
/// column's, `toggle-notes` and search. The newest come first (`toggle-whitespace`, then
/// `diff-settings`, `split-left` and `split-right`, then `copy-lines`), so they yield a key
/// before an older action does.
const LATE: &[Action] = &[
    ToggleWhitespace,
    DiffSettings,
    SplitLeft,
    SplitRight,
    CopyLines,
    Approve,
    CopySelection,
    WordEnd,
    VisualLine,
    Suggest,
    FileComment,
    NextHunk,
    PreviousHunk,
    NextFile,
    PreviousFile,
    ToggleLayout,
    ToggleWrap,
    ToggleFiles,
    FilterFiles,
    FilterKinds,
    HideViewed,
    ToggleViewed,
    NextUnviewed,
    PreviousUnviewed,
    Help,
    ChangeComment,
    NarrowColumn,
    WidenColumn,
    NarrowFiles,
    WidenFiles,
    NarrowNotes,
    WidenNotes,
    WholeFile,
    WholeBase,
    ToggleNotes,
    Search,
    NextMatch,
    PreviousMatch,
    GoToDefinition,
    JumpBack,
    JumpForward,
];

/// The keys bound to each action. A `[keys]` entry replaces that action's keys and leaves the
/// others at their defaults; an empty list unbinds the action.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct Keymap(BTreeMap<Action, Vec<Key>>);

impl Default for Keymap {
    fn default() -> Self {
        Self(DEFAULTS.iter().map(|(action, keys)| (*action, keys.to_vec())).collect())
    }
}

impl<'de> Deserialize<'de> for Keymap {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let mut keymap = Self::default();
        let entries = BTreeMap::<Action, Vec<Key>>::deserialize(deserializer)?;
        let user_keys: Vec<Key> = entries.values().flatten().copied().collect();
        let unset: Vec<Action> = LATE.iter().copied().filter(|late| !entries.contains_key(late)).collect();
        // Copying in the diff follows the keys a config gave `copy`, unless it says otherwise.
        let copy = entries.get(&CopySelection).filter(|_| !entries.contains_key(&CopyLines)).cloned();
        keymap.0.extend(entries);
        if let Some(keys) = copy {
            keymap.0.insert(CopyLines, keys);
        }
        // Their default keys yield to a config that gives those keys to another action, so
        // a config that loaded before they existed still loads.
        for late in unset {
            let taken =
                keymap.0.get(&late).is_some_and(|keys| keys.iter().any(|key| user_keys.contains(key)));
            if taken && keymap.clashes(late) {
                keymap.0.insert(late, Vec::new());
            }
        }
        keymap.check().map_err(serde::de::Error::custom)?;
        Ok(keymap)
    }
}

impl Keymap {
    /// The first action in `context` bound to `key`.
    pub(crate) fn action(&self, key: &KeyEvent, context: &[Action]) -> Option<Action> {
        context.iter().copied().find(|&action| self.is(action, key))
    }

    pub(crate) fn is(&self, action: Action, key: &KeyEvent) -> bool {
        self.keys(action).iter().any(|k| k.matches(key))
    }

    /// The action's first key as the hints spell it; empty when it is unbound.
    pub(crate) fn hint(&self, action: Action) -> String {
        self.keys(action).first().map(|key| key.hint()).unwrap_or_default()
    }

    /// `key label` for a hint line, or nothing when the action is unbound, so an unbound
    /// action leaves no bare label behind.
    pub(crate) fn labelled(&self, action: Action, label: &str) -> Option<String> {
        let key = self.hint(action);
        (!key.is_empty()).then(|| format!("{key} {label}"))
    }

    /// The four cursor directions run together the way the hints show them: `hjkl`.
    pub(crate) fn directions_hint(&self) -> String {
        [Left, Down, Up, Right].map(|action| self.hint(action)).concat()
    }

    fn keys(&self, action: Action) -> &[Key] {
        self.0.get(&action).map_or(&[], Vec::as_slice)
    }

    /// Whether one of `action`'s keys means another action where both read the keypress.
    fn clashes(&self, action: Action) -> bool {
        SHARED.iter().any(|contexts| {
            let actions: Vec<Action> = contexts.iter().copied().flatten().copied().collect();
            actions.contains(&action)
                && self
                    .keys(action)
                    .iter()
                    .any(|key| actions.iter().any(|&other| other != action && self.keys(other).contains(key)))
        })
    }

    /// No key may mean two actions where both read the same keypress.
    fn check(&self) -> Result<(), String> {
        for contexts in SHARED {
            let mut seen: Vec<(Key, Action)> = Vec::new();
            for &action in contexts.iter().copied().flatten() {
                for &key in self.keys(action) {
                    match seen.iter().find(|(k, _)| *k == key) {
                        Some(&(_, other)) if other != action => {
                            return Err(format!(
                                "key {:?} is bound to both {} and {}",
                                key.to_string(),
                                other.as_str(),
                                action.as_str()
                            ));
                        }
                        Some(_) => {}
                        None => seen.push((key, action)),
                    }
                }
            }
        }
        Ok(())
    }
}

impl Action {
    /// The action's name as `[keys]` writes it.
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Left => "left",
            Self::Right => "right",
            Self::WordForward => "word-forward",
            Self::WordBack => "word-back",
            Self::WordEnd => "word-end",
            Self::LineStart => "line-start",
            Self::LineEnd => "line-end",
            Self::PageDown => "page-down",
            Self::PageUp => "page-up",
            Self::Top => "top",
            Self::Bottom => "bottom",
            Self::Confirm => "confirm",
            Self::Back => "back",
            Self::Quit => "quit",
            Self::Interrupt => "interrupt",
            Self::CycleFocus => "cycle-focus",
            Self::Send => "send",
            Self::SendAndClose => "send-and-close",
            Self::Approve => "approve",
            Self::ToggleTree => "toggle-tree",
            Self::Reload => "reload",
            Self::OpenInEditor => "open-in-editor",
            Self::PickMessage => "pick-message",
            Self::QuickOpen => "quick-open",
            Self::PickTarget => "pick-target",
            Self::ReviewMenu => "review-menu",
            Self::ResendAll => "resend-all",
            Self::FinishReview => "finish-review",
            Self::UndoFinish => "undo-finish",
            Self::Archive => "archive",
            Self::ToggleHidden => "toggle-hidden",
            Self::Edit => "edit",
            Self::Remove => "remove",
            Self::AttachImage => "attach-image",
            Self::RemoveImage => "remove-image",
            Self::Visual => "visual",
            Self::VisualLine => "visual-line",
            Self::MoveCursor => "move-cursor",
            Self::Comment => "comment",
            Self::ClearBlock => "clear-block",
            Self::ClearAll => "clear-all",
            Self::LooksGood => "looks-good",
            Self::Delete => "delete",
            Self::CopySelection => "copy",
            Self::CopyLines => "copy-lines",
            Self::Yes => "yes",
            Self::No => "no",
            Self::Suggest => "suggest",
            Self::FileComment => "file-comment",
            Self::ChangeComment => "change-comment",
            Self::NextHunk => "next-hunk",
            Self::PreviousHunk => "previous-hunk",
            Self::NextFile => "next-file",
            Self::PreviousFile => "previous-file",
            Self::ToggleLayout => "toggle-layout",
            Self::ToggleWrap => "toggle-wrap",
            Self::ToggleWhitespace => "toggle-whitespace",
            Self::ToggleFiles => "toggle-files",
            Self::FilterFiles => "filter-files",
            Self::FilterKinds => "filter-kinds",
            Self::HideViewed => "hide-viewed",
            Self::ToggleViewed => "toggle-viewed",
            Self::NextUnviewed => "next-unviewed",
            Self::PreviousUnviewed => "previous-unviewed",
            Self::Help => "help",
            Self::NarrowColumn => "narrow-column",
            Self::WidenColumn => "widen-column",
            Self::NarrowFiles => "narrow-files",
            Self::WidenFiles => "widen-files",
            Self::NarrowNotes => "narrow-notes",
            Self::WidenNotes => "widen-notes",
            Self::WholeFile => "whole-file",
            Self::WholeBase => "whole-base",
            Self::ToggleNotes => "toggle-notes",
            Self::Search => "search",
            Self::NextMatch => "next-match",
            Self::PreviousMatch => "previous-match",
            Self::GoToDefinition => "go-to-definition",
            Self::JumpBack => "jump-back",
            Self::JumpForward => "jump-forward",
            Self::DiffSettings => "diff-settings",
            Self::SplitLeft => "split-left",
            Self::SplitRight => "split-right",
        }
    }
}

#[cfg(test)]
mod tests;