hjkl-keymap 0.32.0

Backend-agnostic modal keymap: chord parsing, trie dispatch, leader/chord resolution for the hjkl editor stack
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
//! Integration tests for hjkl-keymap.

use hjkl_keymap::{Chord, ChordParseError, KeyCode, KeyEvent, KeyModifiers, KeyResolve, Keymap};
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};
use std::time::Instant;

/// Test-local mode discriminator. `Mode` is now a trait — consumers pick their
/// own concrete type. These two variants cover what the test suite needs.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
enum TestMode {
    Normal,
    Insert,
}

use TestMode as Mode;

// ── Helpers ───────────────────────────────────────────────────────────────────

fn char_ev(c: char) -> KeyEvent {
    KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
}

fn ctrl_ev(c: char) -> KeyEvent {
    KeyEvent::new(KeyCode::Char(c), KeyModifiers::CTRL)
}

// ── Chord parse round-trips ───────────────────────────────────────────────────

#[test]
fn round_trip_leader_gs() {
    let leader = ' ';
    let chord = Chord::parse("<leader>gs", leader).unwrap();
    assert_eq!(chord.to_notation(leader), "<leader>gs");
}

#[test]
fn round_trip_ctrl_x() {
    let leader = ' ';
    let chord = Chord::parse("<C-x>", leader).unwrap();
    assert_eq!(chord.to_notation(leader), "<C-x>");
}

#[test]
fn round_trip_shift_tab() {
    let leader = ' ';
    let chord = Chord::parse("<S-Tab>", leader).unwrap();
    assert_eq!(chord.to_notation(leader), "<S-Tab>");
}

#[test]
fn round_trip_ctrl_shift_tab() {
    let leader = ' ';
    let chord = Chord::parse("<C-S-Tab>", leader).unwrap();
    // Modifiers can be in either order in the representation.
    let notation = chord.to_notation(leader);
    assert!(
        notation == "<C-S-Tab>" || notation == "<S-C-Tab>",
        "unexpected notation: {notation}"
    );
}

#[test]
fn round_trip_mixed() {
    let leader = ' ';
    let chord = Chord::parse("<C-w>h", leader).unwrap();
    assert_eq!(chord.to_notation(leader), "<C-w>h");
}

#[test]
fn parse_error_unclosed() {
    let result = Chord::parse("<C-w", ' ');
    assert!(matches!(result, Err(ChordParseError::UnclosedAngle(_))));
}

// ── Keymap::add + feed leaf chord ─────────────────────────────────────────────

#[test]
fn leaf_chord_matches() {
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "gd", "goto_def", "goto definition")
        .unwrap();

    let now = Instant::now();
    let r1 = km.feed(Mode::Normal, char_ev('g'), now);
    assert!(
        matches!(r1, KeyResolve::Pending),
        "expected Pending after 'g'"
    );

    let r2 = km.feed(Mode::Normal, char_ev('d'), now);
    assert!(
        matches!(r2, KeyResolve::Match(b) if b.action == "goto_def"),
        "expected Match(goto_def)"
    );
}

// ── Pending then match ────────────────────────────────────────────────────────

#[test]
fn pending_then_match() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "gd", 1, "gd").unwrap();

    let now = Instant::now();
    let r = km.feed(Mode::Normal, char_ev('g'), now);
    assert!(matches!(r, KeyResolve::Pending));

    let r = km.feed(Mode::Normal, char_ev('d'), now);
    assert!(matches!(r, KeyResolve::Match(b) if b.action == 1));
}

// ── Unbound dead-end ─────────────────────────────────────────────────────────

#[test]
fn unbound_gj_when_only_gd_bound() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "gd", 1, "gd").unwrap();

    let now = Instant::now();
    km.feed(Mode::Normal, char_ev('g'), now);
    let r = km.feed(Mode::Normal, char_ev('j'), now);

    match r {
        KeyResolve::Unbound(keys) => {
            assert_eq!(keys.len(), 2, "expected both g and j in unbound list");
            assert_eq!(keys[0], char_ev('g'));
            assert_eq!(keys[1], char_ev('j'));
        }
        other => panic!("expected Unbound, got {other:?}"),
    }
}

// ── Ambiguous resolution ─────────────────────────────────────────────────────

#[test]
fn ambiguous_when_both_g_and_gd_bound() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "g", 10, "g action").unwrap();
    km.add(Mode::Normal, "gd", 20, "gd action").unwrap();

    let now = Instant::now();
    let r = km.feed(Mode::Normal, char_ev('g'), now);
    assert!(
        matches!(r, KeyResolve::Ambiguous),
        "expected Ambiguous after g"
    );

    // Feed 'd' — should match gd.
    let r = km.feed(Mode::Normal, char_ev('d'), now);
    assert!(matches!(r, KeyResolve::Match(b) if b.action == 20));
}

#[test]
fn timeout_after_ambiguous_resolves_shorter() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "g", 10, "g action").unwrap();
    km.add(Mode::Normal, "gd", 20, "gd action").unwrap();

    let now = Instant::now();
    let r = km.feed(Mode::Normal, char_ev('g'), now);
    assert!(matches!(r, KeyResolve::Ambiguous));

    // Timeout without another key — should resolve to Match(g action).
    let r = km.timeout_resolve(Mode::Normal);
    assert!(matches!(r, KeyResolve::Match(b) if b.action == 10));
}

// ── children for which-key ────────────────────────────────────────────────────

#[test]
fn children_lists_gd_gt() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "gd", 1, "goto def").unwrap();
    km.add(Mode::Normal, "gt", 2, "next tab").unwrap();
    km.add(Mode::Normal, "gT", 3, "prev tab").unwrap();

    let prefix = Chord::parse("g", ' ').unwrap();
    let mut children = km.children(Mode::Normal, &prefix);
    children.sort_by_key(|(ev, _)| match ev.code {
        hjkl_keymap::KeyCode::Char(c) => c,
        _ => '\0',
    });

    assert_eq!(children.len(), 3);
    let codes: Vec<char> = children
        .iter()
        .filter_map(|(ev, _)| {
            if let hjkl_keymap::KeyCode::Char(c) = ev.code {
                Some(c)
            } else {
                None
            }
        })
        .collect();
    assert!(codes.contains(&'d'), "missing gd");
    assert!(codes.contains(&'t'), "missing gt");
    assert!(codes.contains(&'T'), "missing gT");
}

// ── Keymap::pop ───────────────────────────────────────────────────────────────

#[test]
fn pop_removes_last_key() {
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "<leader>gs", "git_status", "git status")
        .unwrap();

    let now = Instant::now();
    // Feed leader then 'g' — buffer has two keys.
    km.feed(Mode::Normal, char_ev(' '), now);
    km.feed(Mode::Normal, char_ev('g'), now);
    assert_eq!(km.pending(Mode::Normal).len(), 2);

    // Pop should remove 'g' and return it.
    let removed = km.pop(Mode::Normal);
    assert_eq!(removed, Some(char_ev('g')));
    assert_eq!(km.pending(Mode::Normal).len(), 1);
    assert_eq!(km.pending(Mode::Normal)[0], char_ev(' '));
}

#[test]
fn pop_returns_none_on_empty_buffer() {
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    // No keys fed — buffer is empty.
    let result = km.pop(Mode::Normal);
    assert_eq!(result, None);
}

// ── Mode isolation ────────────────────────────────────────────────────────────

#[test]
fn normal_binding_not_visible_from_insert() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "gd", 1, "goto def").unwrap();

    let now = Instant::now();
    km.feed(Mode::Insert, char_ev('g'), now);
    let r = km.feed(Mode::Insert, char_ev('d'), now);

    assert!(
        matches!(r, KeyResolve::Unbound(_)),
        "insert mode should not see normal binding"
    );
}

// ── Leader chords ────────────────────────────────────────────────────────────

#[test]
fn leader_chord_resolves() {
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "<leader>gs", "git_status", "git status")
        .unwrap();

    let now = Instant::now();
    km.feed(Mode::Normal, char_ev(' '), now); // leader
    km.feed(Mode::Normal, char_ev('g'), now);
    let r = km.feed(Mode::Normal, char_ev('s'), now);

    assert!(matches!(r, KeyResolve::Match(b) if b.action == "git_status"));
}

#[test]
fn ctrl_w_chord_resolves() {
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "<C-w>h", "focus_left", "focus left")
        .unwrap();

    let now = Instant::now();
    km.feed(Mode::Normal, ctrl_ev('w'), now);
    let r = km.feed(Mode::Normal, char_ev('h'), now);

    assert!(matches!(r, KeyResolve::Match(b) if b.action == "focus_left"));
}

// ── timeout_resolve semantics ──────────────────────────────────────────────────

#[test]
fn timeout_resolve_keeps_buffer_when_pure_prefix() {
    // Buffer = "<leader>" (prefix-only — only "<leader>g" is bound).
    // timeout_resolve must NOT drain: user is mid-chord.
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "<leader>g", "git", "git submenu")
        .unwrap();

    let now = Instant::now();
    let leader = KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE);
    km.feed(Mode::Normal, leader, now);
    assert_eq!(km.pending(Mode::Normal).len(), 1);

    let r = km.timeout_resolve(Mode::Normal);
    assert!(
        matches!(r, KeyResolve::Unbound(ref v) if v.is_empty()),
        "pure-prefix timeout_resolve must return Unbound(empty), got {r:?}"
    );
    assert_eq!(
        km.pending(Mode::Normal).len(),
        1,
        "buffer must be preserved for pure-prefix state"
    );
}

#[test]
fn timeout_resolve_fires_ambiguous_shorter_binding() {
    // Buffer = "g" where both "g" (terminal) and "gd" (deeper) are bound.
    // timeout_resolve must fire the shorter "g" binding.
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "g", "g_action", "g").unwrap();
    km.add(Mode::Normal, "gd", "gd_action", "gd").unwrap();

    let now = Instant::now();
    km.feed(Mode::Normal, char_ev('g'), now);
    assert_eq!(km.pending(Mode::Normal).len(), 1);

    let r = km.timeout_resolve(Mode::Normal);
    assert!(
        matches!(r, KeyResolve::Match(ref b) if b.action == "g_action"),
        "ambiguous timeout_resolve must fire the terminal binding, got {r:?}"
    );
    assert!(
        km.pending(Mode::Normal).is_empty(),
        "buffer must be drained"
    );
}

#[test]
fn timeout_resolve_empty_buffer_returns_unbound_empty() {
    let mut km: Keymap<&str, TestMode> = Keymap::new(' ');
    km.add(Mode::Normal, "<leader>g", "git", "git").unwrap();
    let r = km.timeout_resolve(Mode::Normal);
    assert!(matches!(r, KeyResolve::Unbound(ref v) if v.is_empty()));
}

// ── Predicate-gated bindings (Phase 1 — issue #120) ──────────────────────────

/// Predicate false → binding is unbound; key not consumed.
#[test]
fn predicate_false_binding_is_unbound() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add_if(Mode::Normal, "x", 42, "gated", || false).unwrap();

    let now = Instant::now();
    let r = km.feed(Mode::Normal, char_ev('x'), now);
    assert!(
        matches!(r, KeyResolve::Unbound(_)),
        "predicate=false must yield Unbound, got {r:?}"
    );
}

/// Predicate true → binding fires normally.
#[test]
fn predicate_true_binding_fires() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    km.add_if(Mode::Normal, "x", 99, "gated", || true).unwrap();

    let now = Instant::now();
    let r = km.feed(Mode::Normal, char_ev('x'), now);
    assert!(
        matches!(r, KeyResolve::Match(ref b) if b.action == 99),
        "predicate=true must yield Match, got {r:?}"
    );
}

/// Predicate state changes between resolve calls: first false → unbound,
/// then true → fires.
#[test]
fn predicate_state_change_between_resolves() {
    let flag = Arc::new(AtomicBool::new(false));

    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    let flag_clone = Arc::clone(&flag);
    km.add_if(Mode::Normal, "x", 7, "togglable", move || {
        flag_clone.load(Ordering::SeqCst)
    })
    .unwrap();

    let now = Instant::now();

    // Predicate false: unbound.
    let r = km.feed(Mode::Normal, char_ev('x'), now);
    assert!(
        matches!(r, KeyResolve::Unbound(_)),
        "expected Unbound when predicate=false, got {r:?}"
    );

    // Flip flag.
    flag.store(true, Ordering::SeqCst);

    // Predicate true: fires.
    let r = km.feed(Mode::Normal, char_ev('x'), now);
    assert!(
        matches!(r, KeyResolve::Match(ref b) if b.action == 7),
        "expected Match when predicate=true, got {r:?}"
    );
}

/// Ambiguous chord where the complete-arm has a false predicate: the
/// ambiguous terminal is treated as absent, so the result is Pending
/// (not Ambiguous) — the chord must be extended to resolve.
#[test]
fn ambiguous_predicate_false_complete_arm_falls_through_to_pending() {
    let mut km: Keymap<u32, TestMode> = Keymap::new(' ');
    // Both "g" (terminal, predicate false) and "gd" (deeper, unconditional).
    km.add_if(Mode::Normal, "g", 10, "g-gated", || false)
        .unwrap();
    km.add(Mode::Normal, "gd", 20, "gd unconditional").unwrap();

    let now = Instant::now();
    // Feeding "g": exact match exists but predicate is false; deeper binding
    // exists. The result must be Pending (not Ambiguous) because the
    // complete arm is invisible.
    let r = km.feed(Mode::Normal, char_ev('g'), now);
    assert!(
        matches!(r, KeyResolve::Pending),
        "false-predicate complete arm must yield Pending (not Ambiguous), got {r:?}"
    );

    // Extending to "gd" must fire the unconditional binding.
    let r = km.feed(Mode::Normal, char_ev('d'), now);
    assert!(
        matches!(r, KeyResolve::Match(ref b) if b.action == 20),
        "gd must fire unconditionally, got {r:?}"
    );
}

// ── Non-vim mode discriminators (issue #1) ───────────────────────────────────

#[test]
fn keymap_works_with_helix_style_mode_set() {
    // Helix has Normal / Select / Insert — no OpPending, no CommandLine.
    // Proves the generic Mode trait accommodates non-vim modal vocabularies.
    #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
    enum HelixMode {
        Normal,
        Select,
        Insert,
    }

    let mut km: Keymap<&str, HelixMode> = Keymap::new(' ');
    km.add(HelixMode::Normal, "w", "next-word", "next word")
        .unwrap();
    km.add(
        HelixMode::Select,
        "w",
        "select-next-word",
        "select next word",
    )
    .unwrap();

    let now = Instant::now();
    let r = km.feed(HelixMode::Normal, char_ev('w'), now);
    assert!(matches!(r, KeyResolve::Match(ref b) if b.action == "next-word"));

    let r = km.feed(HelixMode::Select, char_ev('w'), now);
    assert!(matches!(r, KeyResolve::Match(ref b) if b.action == "select-next-word"));

    // Insert mode has no bindings; should return Unbound.
    let r = km.feed(HelixMode::Insert, char_ev('w'), now);
    assert!(matches!(r, KeyResolve::Unbound(_)));
}