tmprl-core 0.1.0

Pure domain logic for tmprl: modes, keymap, command registry
Documentation
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
//! Key resolution: chords in, command ids out.
//!
//! Three behaviours here are worth more than they look:
//!
//! * **Counts.** `7j` means seven, and it composes with any motion, because the count is
//!   accumulated by the resolver rather than by each command.
//! * **Prefixes.** An incomplete sequence resolves to [`Resolution::Pending`] carrying the
//!   keys that would complete it. That list is exactly what the which-key popup draws, so
//!   the popup can never disagree with the keymap.
//! * **Flushing.** An unmatched sequence returns the chords it swallowed. That is what lets
//!   `jk` leave Insert mode without eating a literal `j` typed before some other letter.

use crate::key::{Chord, ChordSeq, Key, KeyParseError};
use crate::mode::Mode;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
    pub mode: Mode,
    pub seq: ChordSeq,
    pub command: &'static str,
}

/// A key that could come next, for the which-key popup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingEntry {
    pub next: Chord,
    /// `Some` when this key completes a binding, `None` when it only opens a deeper prefix.
    pub command: Option<&'static str>,
    /// How many bindings live under this key. `> 1` means it is a group.
    pub bindings: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
    /// A digit was consumed into the count. Nothing to run yet.
    Count(u32),
    /// A prefix matched. `candidates` is what could come next.
    Pending { candidates: Vec<PendingEntry> },
    /// A binding matched.
    Run {
        id: &'static str,
        count: Option<u32>,
    },
    /// Nothing matched. `flushed` is every chord that was held, including this one, so the
    /// caller can treat them as literal input.
    Unbound { flushed: Vec<Chord> },
}

/// Keys held while waiting for a sequence to complete.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Pending {
    pub count: Option<u32>,
    pub chords: Vec<Chord>,
}

impl Pending {
    pub fn clear(&mut self) {
        self.count = None;
        self.chords.clear();
    }
    pub fn is_idle(&self) -> bool {
        self.count.is_none() && self.chords.is_empty()
    }
    /// What the statusline shows in the bottom right, like vim's pending-command indicator.
    pub fn display(&self) -> String {
        let mut s = String::new();
        if let Some(c) = self.count {
            s.push_str(&c.to_string());
        }
        for ch in &self.chords {
            s.push_str(&ch.to_string());
        }
        s
    }
}

pub struct Keymap {
    bindings: Vec<Binding>,
    leader: Chord,
}

/// Counts are capped so that a leaned-on digit key cannot ask for a motion of four billion.
const MAX_COUNT: u32 = 100_000;

impl Keymap {
    pub fn new(leader: Chord) -> Self {
        Self {
            bindings: Vec::new(),
            leader,
        }
    }

    pub fn bind(
        &mut self,
        mode: Mode,
        seq: &str,
        command: &'static str,
    ) -> Result<(), KeyParseError> {
        let seq = ChordSeq::parse(seq, self.leader)?;
        // Last binding wins, so a user keymap can override a default.
        self.bindings.retain(|b| !(b.mode == mode && b.seq == seq));
        self.bindings.push(Binding { mode, seq, command });
        Ok(())
    }

    pub fn leader(&self) -> Chord {
        self.leader
    }
    pub fn bindings(&self) -> &[Binding] {
        &self.bindings
    }

    /// Every chord sequence bound to a command, for the help overlay.
    pub fn keys_for(&self, command: &str) -> Vec<&Binding> {
        self.bindings
            .iter()
            .filter(|b| b.command == command)
            .collect()
    }

    pub fn resolve(&self, mode: Mode, pending: &mut Pending, chord: Chord) -> Resolution {
        // A digit starts or extends a count, but only when no sequence is in flight,
        // otherwise `<leader>1` could never be bound.
        if mode.takes_counts()
            && pending.chords.is_empty()
            && let Key::Char(c) = chord.key
            && chord.mods.is_none()
            && let Some(d) = c.to_digit(10)
            && !(d == 0 && pending.count.is_none())
        {
            let next = pending
                .count
                .unwrap_or(0)
                .saturating_mul(10)
                .saturating_add(d);
            pending.count = Some(next.min(MAX_COUNT));
            return Resolution::Count(pending.count.unwrap());
        }

        pending.chords.push(chord);

        if let Some(b) = self
            .bindings
            .iter()
            .find(|b| b.mode == mode && b.seq.0 == pending.chords)
        {
            let count = pending.count;
            pending.clear();
            return Resolution::Run {
                id: b.command,
                count,
            };
        }

        let depth = pending.chords.len();
        let mut candidates: Vec<PendingEntry> = Vec::new();
        for b in &self.bindings {
            if b.mode != mode || b.seq.len() <= depth || !b.seq.starts_with(&pending.chords) {
                continue;
            }
            let next = b.seq.0[depth];
            let completes = b.seq.len() == depth + 1;
            match candidates.iter_mut().find(|e| e.next == next) {
                Some(e) => {
                    e.bindings += 1;
                    if completes {
                        e.command = Some(b.command);
                    }
                }
                None => candidates.push(PendingEntry {
                    next,
                    command: completes.then_some(b.command),
                    bindings: 1,
                }),
            }
        }

        if !candidates.is_empty() {
            candidates.sort_by_key(|e| e.next);
            return Resolution::Pending { candidates };
        }

        let flushed = std::mem::take(&mut pending.chords);
        pending.count = None;
        Resolution::Unbound { flushed }
    }
}

/// The default keymap.
///
/// Only bindings whose commands actually do something are registered. Binding a key to a
/// feature that is not built yet would make the which-key popup advertise things that do
/// nothing, which is worse than an empty keymap.
///
/// `C-h/j/k/l` are deliberately absent. See `docs/INTERFACE.md`.
pub fn default_keymap() -> Keymap {
    let mut m = Keymap::new(Chord::ch(' '));
    let mut bind = |mode, seq, cmd| {
        m.bind(mode, seq, cmd)
            .unwrap_or_else(|e| panic!("bad default binding `{seq}`: {e}"));
    };

    for mode in [Mode::Normal, Mode::Visual, Mode::VisualLine] {
        bind(mode, "j", "motion.down");
        bind(mode, "k", "motion.up");
        bind(mode, "<Down>", "motion.down");
        bind(mode, "<Up>", "motion.up");
        bind(mode, "gg", "motion.top");
        bind(mode, "G", "motion.bottom");
        bind(mode, "<C-d>", "motion.half-down");
        bind(mode, "<C-u>", "motion.half-up");
        bind(mode, "y", "yank.field");
        bind(mode, "Y", "yank.record");
        bind(mode, "<Esc>", "app.cancel");
        bind(mode, ":", "app.command-line");
        bind(mode, "?", "app.help");
        bind(mode, "R", "app.refresh");
        bind(mode, "<leader>q", "app.quit");
        bind(mode, "<C-c>", "app.quit");
    }

    // `<CR>` opens in the visual modes too, where it means "open the selection": that is
    // how several namespaces become one merged workflow list. `-` stays Normal-only,
    // walking up a level while selecting rows has no sensible meaning.
    for mode in [Mode::Normal, Mode::Visual, Mode::VisualLine] {
        bind(mode, "<CR>", "nav.open");
    }
    bind(Mode::Normal, "-", "nav.up");
    // The jumplist. `<C-o>` and `<C-i>` are free here: neither is one of the four
    // chords tmux's pane navigation takes.
    //
    // `<Tab>` is bound alongside `<C-i>` because on a terminal they are the *same key*:
    // Ctrl+I is byte 0x09, which is what Tab sends, and crossterm reports it as
    // `KeyCode::Tab`. Binding only `<C-i>` gives a jump-forward that never fires outside
    // the few terminals speaking the Kitty keyboard protocol. Terminal vim has the same
    // collision and resolves it the same way.
    bind(Mode::Normal, "<C-o>", "nav.jump-back");
    bind(Mode::Normal, "<C-i>", "nav.jump-forward");
    bind(Mode::Normal, "<Tab>", "nav.jump-forward");
    // `g` is vim's goto prefix, so `gs` and `gw` switch between the two lists a namespace
    // holds.
    bind(Mode::Normal, "gs", "nav.schedules");
    bind(Mode::Normal, "gw", "nav.workflows");

    // Folds use vim's `z` family, so the which-key popup on `z` reads like vim's does.
    // `zp` is not a vim binding, but it sits in the same namespace as the folds it
    // resembles: it folds away the workflow-task plumbing.
    for mode in [Mode::Normal, Mode::Visual, Mode::VisualLine] {
        bind(mode, "za", "history.fold");
        bind(mode, "zR", "history.expand-all");
        bind(mode, "zM", "history.collapse-all");
        bind(mode, "zp", "history.plumbing");
        // vim-unimpaired's bracket motions: `]f` / `[f` for the next and previous failure.
        bind(mode, "]f", "history.next-failure");
        bind(mode, "[f", "history.prev-failure");
        bind(mode, "F", "history.follow");
        // `K` is vim's "look up what is under the cursor", which is exactly what the detail
        // pane does, it shows the payloads of the focused event or group.
        bind(mode, "K", "history.detail");
        // vim scrolls a window by a line with <C-e>/<C-y>; here they scroll the payload
        // pane, which is the only thing on screen tall enough to need it.
        bind(mode, "<C-e>", "history.detail-down");
        bind(mode, "<C-y>", "history.detail-up");
        // vim's filter operator. Here it filters the focused payloads rather than lines.
        bind(mode, "!", "payload.pipe");
        // Payload yanks live under a `<leader>y` prefix rather than on `y` itself: an exact
        // match wins over a prefix in `resolve`, so binding `<leader>y` as well would make
        // these three unreachable. The prefix also puts them in the which-key popup.
        bind(mode, "<leader>ya", "yank.payload");
        bind(mode, "<leader>yi", "yank.payload-input");
        bind(mode, "<leader>yr", "yank.payload-result");

        // Windows and tabs, with vim's bindings. `<C-w>` prefixes focus movement, never
        // bare `<C-h/j/k/l>`, which tmux's vim-tmux-navigator swallows before any
        // application sees them.
        bind(mode, "<leader>sv", "window.split-right");
        bind(mode, "<leader>sh", "window.split-down");
        bind(mode, "<leader>sx", "window.close");
        bind(mode, "<leader>se", "window.equalize");
        bind(mode, "<C-w>h", "window.focus-left");
        bind(mode, "<C-w>j", "window.focus-down");
        bind(mode, "<C-w>k", "window.focus-up");
        bind(mode, "<C-w>l", "window.focus-right");
        bind(mode, "<leader>rh", "window.grow-left");
        bind(mode, "<leader>rj", "window.grow-down");
        bind(mode, "<leader>rk", "window.grow-up");
        bind(mode, "<leader>rl", "window.grow-right");
        // Mutations live under `<leader>m`, for "mutate", and clear of bare `m`, which
        // marks reserve. Every one of them opens a confirmation rather than acting.
        bind(mode, "<leader>mc", "workflow.cancel");
        bind(mode, "<leader>mt", "workflow.terminate");
        bind(mode, "<leader>ms", "workflow.signal");
        bind(mode, "<leader>md", "workflow.delete");
        bind(mode, "<leader>mr", "workflow.reset");
        bind(mode, "<leader>mu", "workflow.update");
        bind(mode, "<leader>mp", "schedule.pause");
        bind(mode, "<leader>mg", "schedule.trigger");
        bind(mode, "<leader>mD", "schedule.delete");
        bind(mode, "<leader>mb", "schedule.backfill");
        bind(mode, "<leader>mn", "schedule.create");

        bind(mode, "<leader>to", "tab.new");
        bind(mode, "<leader>tx", "tab.close");
        bind(mode, "<leader>tn", "tab.next");
        bind(mode, "<leader>tp", "tab.previous");
    }

    // `/` `n` `N` as vim has them. Reverse-open (`?`) is not bound: `?` is the help
    // overlay here, and help is reached far more often than a backwards search is started.
    // `N` still walks backwards, which is the part that matters.
    bind(Mode::Normal, "/", "search.open");
    bind(Mode::Normal, "n", "search.next");
    bind(Mode::Normal, "N", "search.previous");

    // The `<leader>f` family, Telescope's `f` for find. Each is the same picker over a
    // different list, which is why they share a prefix rather than being spread across the
    // keyboard by what they happen to search.
    bind(Mode::Normal, "<leader>ff", "find.workflow");
    bind(Mode::Normal, "<leader>fl", "find.event");
    bind(Mode::Normal, "<leader>fb", "find.pane");
    bind(Mode::Normal, "<leader>fh", "find.command");
    bind(Mode::Normal, "<leader>fg", "find.filter");
    // `<leader>N` sits outside the `f` family on purpose: switching namespace is changing
    // *where you are*, not finding something inside where you already are.
    bind(Mode::Normal, "<leader>N", "find.namespace");
    bind(Mode::Normal, "<leader>xx", "list.problems");
    bind(Mode::Normal, "<leader>e", "payload.edit");

    bind(Mode::Normal, "i", "mode.insert");
    bind(Mode::Normal, "v", "mode.visual");
    bind(Mode::Normal, "V", "mode.visual-line");

    // `jk` is the escape hatch; `<Esc>` works too.
    bind(Mode::Insert, "jk", "mode.normal");
    bind(Mode::Insert, "<Esc>", "mode.normal");

    m
}

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

    fn map() -> Keymap {
        default_keymap()
    }

    fn feed(m: &Keymap, mode: Mode, p: &mut Pending, keys: &[Chord]) -> Resolution {
        let mut last = Resolution::Unbound { flushed: vec![] };
        for &c in keys {
            last = m.resolve(mode, p, c);
        }
        last
    }

    #[test]
    fn every_default_binding_names_a_command_that_exists() {
        // `Keymap::bind` validates the *chord* and panics on a bad one, but it has no
        // registry to check the command id against, so a typo in a default binding is a key
        // that silently does nothing. `keys.toml` is checked at load; this is the same
        // guarantee for the built-in map.
        let registry = crate::command::Registry::builtin();
        let map = map();
        let missing: Vec<&str> = map
            .bindings()
            .iter()
            .map(|b| b.command)
            .filter(|id| registry.get(id).is_none())
            .collect();
        assert!(missing.is_empty(), "bound to nothing: {missing:?}");
    }

    #[test]
    fn no_two_default_bindings_claim_the_same_keys_in_one_mode() {
        // A duplicate is not an error the keymap can raise, the later one simply wins, so
        // the earlier binding vanishes without a word.
        let map = map();
        let mut seen: Vec<(Mode, &ChordSeq)> = Vec::new();
        let mut clashes = Vec::new();
        for b in map.bindings() {
            if seen.iter().any(|(m, s)| *m == b.mode && *s == &b.seq) {
                clashes.push(format!("{:?} {:?} -> {}", b.mode, b.seq, b.command));
            }
            seen.push((b.mode, &b.seq));
        }
        assert!(clashes.is_empty(), "duplicate bindings: {clashes:?}");
    }

    #[test]
    fn resolves_a_single_key() {
        let (m, mut p) = (map(), Pending::default());
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('j')),
            Resolution::Run {
                id: "motion.down",
                count: None
            }
        );
        assert!(p.is_idle(), "pending state must reset after a match");
    }

    #[test]
    fn accumulates_multi_digit_counts() {
        let (m, mut p) = (map(), Pending::default());
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('1')),
            Resolution::Count(1)
        );
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('2')),
            Resolution::Count(12)
        );
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('j')),
            Resolution::Run {
                id: "motion.down",
                count: Some(12)
            }
        );
    }

    #[test]
    fn leading_zero_is_not_a_count() {
        // In vim `0` is a motion, not a count, it may only extend one already started.
        let (m, mut p) = (map(), Pending::default());
        assert!(matches!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('0')),
            Resolution::Unbound { .. }
        ));
        p.clear();
        m.resolve(Mode::Normal, &mut p, Chord::ch('1'));
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('0')),
            Resolution::Count(10)
        );
    }

    #[test]
    fn counts_are_capped() {
        let (m, mut p) = (map(), Pending::default());
        for _ in 0..12 {
            m.resolve(Mode::Normal, &mut p, Chord::ch('9'));
        }
        assert_eq!(p.count, Some(MAX_COUNT));
    }

    #[test]
    fn multi_key_sequences_report_pending_then_run() {
        let (m, mut p) = (map(), Pending::default());
        let r = m.resolve(Mode::Normal, &mut p, Chord::ch('g'));
        match r {
            Resolution::Pending { candidates } => {
                // `g` is vim's goto prefix and gains continuations over time, so the point
                // is that `gg` is among them, not how many there are.
                let gg = candidates
                    .iter()
                    .find(|c| c.next == Chord::ch('g'))
                    .expect("gg should be reachable from g");
                assert_eq!(gg.command, Some("motion.top"));
            }
            other => panic!("expected Pending, got {other:?}"),
        }
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('g')),
            Resolution::Run {
                id: "motion.top",
                count: None
            }
        );
    }

    #[test]
    fn leader_lists_its_candidates() {
        let (m, mut p) = (map(), Pending::default());
        match m.resolve(Mode::Normal, &mut p, Chord::ch(' ')) {
            Resolution::Pending { candidates } => {
                assert!(candidates.iter().any(|c| c.command == Some("app.quit")));
            }
            other => panic!("expected Pending, got {other:?}"),
        }
    }

    #[test]
    fn counts_survive_a_multi_key_sequence() {
        let (m, mut p) = (map(), Pending::default());
        let r = feed(
            &m,
            Mode::Normal,
            &mut p,
            &[Chord::ch('5'), Chord::ch('g'), Chord::ch('g')],
        );
        assert_eq!(
            r,
            Resolution::Run {
                id: "motion.top",
                count: Some(5)
            }
        );
    }

    #[test]
    fn jk_leaves_insert_mode() {
        let (m, mut p) = (map(), Pending::default());
        assert!(matches!(
            m.resolve(Mode::Insert, &mut p, Chord::ch('j')),
            Resolution::Pending { .. }
        ));
        assert_eq!(
            m.resolve(Mode::Insert, &mut p, Chord::ch('k')),
            Resolution::Run {
                id: "mode.normal",
                count: None
            }
        );
    }

    #[test]
    fn a_held_j_is_flushed_when_the_sequence_fails() {
        // Typing "ja" in Insert must insert both characters, not swallow the `j`.
        let (m, mut p) = (map(), Pending::default());
        m.resolve(Mode::Insert, &mut p, Chord::ch('j'));
        match m.resolve(Mode::Insert, &mut p, Chord::ch('a')) {
            Resolution::Unbound { flushed } => {
                assert_eq!(flushed, vec![Chord::ch('j'), Chord::ch('a')]);
            }
            other => panic!("expected Unbound with both chords, got {other:?}"),
        }
        assert!(p.is_idle());
    }

    #[test]
    fn insert_mode_ignores_counts() {
        let (m, mut p) = (map(), Pending::default());
        match m.resolve(Mode::Insert, &mut p, Chord::ch('7')) {
            Resolution::Unbound { flushed } => assert_eq!(flushed, vec![Chord::ch('7')]),
            other => panic!("digits must be literal in Insert, got {other:?}"),
        }
    }

    #[test]
    fn ctrl_hjkl_is_never_bound() {
        // tmux's vim-tmux-navigator consumes these before any application sees them.
        let m = map();
        for c in ['h', 'j', 'k', 'l'] {
            let chord = Chord::ctrl(c);
            assert!(
                !m.bindings().iter().any(|b| b.seq.0 == vec![chord]),
                "<C-{c}> must not be bound; tmux eats it"
            );
        }
    }

    #[test]
    fn later_bindings_override_earlier_ones() {
        let mut m = Keymap::new(Chord::ch(' '));
        m.bind(Mode::Normal, "j", "motion.down").unwrap();
        m.bind(Mode::Normal, "j", "motion.up").unwrap();
        assert_eq!(m.bindings().len(), 1);
        let mut p = Pending::default();
        assert_eq!(
            m.resolve(Mode::Normal, &mut p, Chord::ch('j')),
            Resolution::Run {
                id: "motion.up",
                count: None
            }
        );
    }

    #[test]
    fn pending_display_matches_what_was_typed() {
        let (m, mut p) = (map(), Pending::default());
        feed(&m, Mode::Normal, &mut p, &[Chord::ch('2'), Chord::ch('g')]);
        assert_eq!(p.display(), "2g");
    }

    #[test]
    fn every_bound_command_exists_in_the_registry() {
        // A binding to a non-existent id would be a key that silently does nothing.
        let reg = crate::command::Registry::builtin();
        for b in map().bindings() {
            assert!(
                reg.get(b.command).is_some(),
                "binding {} points at unknown command `{}`",
                b.seq,
                b.command
            );
        }
    }
}