trail-fm 1.11.2

A terminal-first workspace for navigating, inspecting and acting on the filesystem
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
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
//! Default and user-configured key bindings.
//!
//! Resolves `[keymap]` TOML tables to `Action` values for each mode. Arrow
//! keys and Enter remain built-in aliases for ergonomic terminal navigation.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::actions::transfer::TransferKind;
use crate::actions::Action;
use crate::app::sort::SortBy;
use crate::app::state::AppState;
use crate::config::KeymapConfig;
use crate::input::InputCtx;

/// Translates a `KeyEvent` in Navigation Mode into an `Action`.
///
/// Configured bindings are resolved first from `state.config.keymap`. Built-in
/// non-text fallbacks such as arrows, Enter, and Backspace are then checked.
/// Multi-key sequences are represented by compact strings such as `gg`, `ya`,
/// and `dd`.
pub fn navigation(key: KeyEvent, _ctx: &mut InputCtx, state: &AppState) -> Option<Action> {
    if state.pending_delete {
        return match key.code {
            KeyCode::Enter | KeyCode::Char('y') => Some(Action::ConfirmDelete),
            KeyCode::Esc | KeyCode::Char('n') => Some(Action::CancelDelete),
            _ => None,
        };
    }

    if let Some(pending) = state.pending_nav_key {
        if let Some(sequence) = append_to_sequence(pending, key) {
            return nav_action_for_sequence(&state.config.keymap, &sequence);
        }
        return None;
    }

    if let Some(action) = configured_nav_action(key, &state.config.keymap) {
        return Some(action);
    }

    if let Some(prefix) = configured_nav_prefix(key, &state.config.keymap) {
        return Some(Action::SetPendingNavKey(prefix));
    }

    match key.code {
        // Shift+arrow scrolls the preview — checked before the bare arrows,
        // which match on the key code alone and would otherwise swallow it and
        // move the selection instead.
        KeyCode::Down if key.modifiers.contains(KeyModifiers::SHIFT) => {
            Some(Action::PreviewScrollDown)
        }
        KeyCode::Up if key.modifiers.contains(KeyModifiers::SHIFT) => Some(Action::PreviewScrollUp),
        KeyCode::Down => Some(Action::MoveDown),
        KeyCode::Up => Some(Action::MoveUp),
        KeyCode::Enter | KeyCode::Right => Some(Action::EnterOrOpen),
        KeyCode::Backspace | KeyCode::Left => Some(Action::GoParent),
        // Ctrl+C cancels Trail without writing --cwd-file.
        KeyCode::Char('c') if is_ctrl_chord(key.modifiers) => Some(Action::Cancel),
        // Phase 8: tab management built-in fallbacks.
        // These fire when not overridden by a configured keymap binding.
        KeyCode::Char('t') if is_ctrl_chord(key.modifiers) => Some(Action::NewTab),
        KeyCode::Char('w') if is_ctrl_chord(key.modifiers) => Some(Action::CloseTab),
        KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => Some(Action::SwitchTabPrev),
        KeyCode::Tab => Some(Action::SwitchTabNext),
        KeyCode::Esc => None,
        _ => None,
    }
}

/// Translates a `KeyEvent` in Visual Mode into an `Action`.
///
/// Visual mode shares Navigation Mode's bindings — `j`, `k`, `G`, `gg` and the
/// arrows move exactly as they do there, which is what extends the range — and
/// reinterprets the few that end it:
///
/// - `Space` and `v` add the range to the marks;
/// - `h`/`l` (and the other ways of leaving the directory) add it and then go;
/// - `Esc` abandons it, leaving the marks as they were;
/// - `dd` deletes it, after one confirmation.
///
/// Everything else is ignored: a yank or a paste in the middle of selecting is
/// more likely a slip than a request.
pub fn visual(key: KeyEvent, ctx: &mut InputCtx, state: &AppState) -> Option<Action> {
    let action = navigation(key, ctx, state)?;
    match action {
        Action::MoveDown
        | Action::MoveUp
        | Action::JumpTop
        | Action::JumpBottom
        | Action::SetPendingNavKey(_)
        | Action::BeginDelete
        | Action::ConfirmDelete
        | Action::CancelDelete
        | Action::Cancel
        | Action::PreviewScrollDown
        | Action::PreviewScrollUp
        | Action::PreviewPageDown
        | Action::PreviewPageUp
        | Action::PreviewScrollTop
        | Action::PreviewScrollBottom => Some(action),
        Action::ToggleMark | Action::EnterVisual => Some(Action::CommitVisual(None)),
        Action::GoParent
        | Action::EnterOrOpen
        | Action::HistoryBack
        | Action::HistoryForward
        | Action::ReturnFromJump => Some(Action::CommitVisual(Some(Box::new(action)))),
        Action::ClearMarks => Some(Action::ExitMode),
        _ => None,
    }
}

/// Translates a `KeyEvent` in Search Mode into an `Action`.
///
/// Search Mode is a typing mode, so an unmodified printable character is
/// **always** appended to the query — before the configured keymap is even
/// consulted. Binding a bare character to a movement action here would make
/// that character impossible to search for, which is exactly what the shipped
/// defaults used to do with `j` and `k`: the list moved and the letter never
/// reached the query.
///
/// Everything that is not text therefore drives the mode: arrows and
/// `Ctrl-n`/`Ctrl-p` move, Enter confirms, Esc leaves, Backspace deletes.
/// Those are what `[keymap.search]` may rebind, and
/// `TrailConfig::validate` rejects a single-character binding so the
/// shadowing cannot be reintroduced through config.
pub fn search(key: KeyEvent, keymap: &KeymapConfig) -> Option<Action> {
    if let KeyCode::Char(ch) = key.code {
        // Capitals (Shift) and AltGr characters (Ctrl+Alt on Windows) are text too.
        if super::is_text_modifiers(key.modifiers) {
            return Some(Action::SearchAppendChar(ch));
        }
    }

    if let Some(action) = configured_search_action(key, keymap) {
        return Some(action);
    }

    match key.code {
        KeyCode::Esc => Some(Action::ExitMode),
        KeyCode::Enter | KeyCode::Right => Some(Action::SearchConfirm),
        KeyCode::Down => Some(Action::SearchMoveDown),
        KeyCode::Up => Some(Action::SearchMoveUp),
        KeyCode::Backspace => Some(Action::SearchDeleteChar),
        // Readline-style chords, so the hands never have to leave the home row
        // now that j/k are text. Built-in aliases, like Ctrl-h for backspace.
        KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            Some(Action::SearchMoveDown)
        }
        KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            Some(Action::SearchMoveUp)
        }
        KeyCode::Char('h') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            Some(Action::SearchDeleteChar)
        }
        _ => None,
    }
}

fn configured_nav_action(key: KeyEvent, keymap: &KeymapConfig) -> Option<Action> {
    let key_text = key_to_config_string(key)?;
    nav_action_for_sequence(keymap, &key_text)
}

fn configured_search_action(key: KeyEvent, keymap: &KeymapConfig) -> Option<Action> {
    let key_text = key_to_config_string(key)?;
    keymap.search.iter().find_map(|(name, binding)| {
        if binding == &key_text {
            search_action_from_name(name)
        } else {
            None
        }
    })
}

/// Returns `ch` when it is the first key of a configured multi-key sequence
/// such as `gg` or `ya`, so the dispatcher waits for the second key.
///
/// Named-key bindings are excluded before the prefix test. A binding like
/// `tab` or `ctrl-r` is one key, not the letters it is spelled with; without
/// the exclusion `t` and `c` became prefixes that nothing could complete, and
/// each silently swallowed the keystroke after it.
fn configured_nav_prefix(key: KeyEvent, keymap: &KeymapConfig) -> Option<char> {
    let KeyCode::Char(ch) = key.code else {
        return None;
    };
    if is_ctrl_chord(key.modifiers) {
        return None;
    }
    keymap
        .navigation
        .values()
        .filter(|binding| !is_named_key(binding))
        .any(|binding| binding.len() > ch.len_utf8() && binding.starts_with(ch))
        .then_some(ch)
}

/// Whether a character key with `modifiers` is a Ctrl chord rather than a
/// typed character.
///
/// Ctrl **and** Alt together is how Windows reports AltGr, which Spanish,
/// Latin American, German and many other layouts need for `@`, `\`, `|`,
/// `~`, `{` and `[`. Read as Ctrl, AltGr+Q on es-MX arrived as `ctrl-@` and
/// matched nothing, so a binding of `@` could never be pressed there — the
/// same trap §2.18 fixed for Command and Search Mode.
fn is_ctrl_chord(modifiers: KeyModifiers) -> bool {
    modifiers.contains(KeyModifiers::CONTROL) && !super::is_text_modifiers(modifiers)
}

/// Every key name [`key_to_config_string`] can produce without a modifier.
const NAMED_KEYS: &[&str] = &[
    "enter",
    "esc",
    "backspace",
    "tab",
    "left",
    "right",
    "up",
    "down",
    "home",
    "end",
    "space",
];

/// Whether `binding` names a single key — `tab`, `ctrl-r`, `shift-end` — as
/// opposed to a sequence of typed characters.
///
/// Matches exactly the spellings [`key_to_config_string`] produces: a bare key
/// name, or one prefixed with `ctrl-` or `shift-`.
fn is_named_key(binding: &str) -> bool {
    let base = binding
        .strip_prefix("ctrl-")
        .or_else(|| binding.strip_prefix("shift-"))
        .unwrap_or(binding);
    binding != base || NAMED_KEYS.contains(&base)
}

fn nav_action_for_sequence(keymap: &KeymapConfig, sequence: &str) -> Option<Action> {
    keymap.navigation.iter().find_map(|(name, binding)| {
        if binding == sequence {
            nav_action_from_name(name)
        } else {
            None
        }
    })
}

fn nav_action_from_name(name: &str) -> Option<Action> {
    match name {
        "move_down" => Some(Action::MoveDown),
        "move_up" => Some(Action::MoveUp),
        "jump_top" => Some(Action::JumpTop),
        "jump_bottom" => Some(Action::JumpBottom),
        "enter_or_open" => Some(Action::EnterOrOpen),
        "go_parent" => Some(Action::GoParent),
        "history_back" => Some(Action::HistoryBack),
        "history_forward" => Some(Action::HistoryForward),
        "return_from_jump" => Some(Action::ReturnFromJump),
        "refresh" => Some(Action::Refresh),
        "toggle_hidden" => Some(Action::ToggleHidden),
        // Listing order. `s` is never bound on its own: `configured_nav_prefix`
        // makes any first character of a longer binding a prefix, so these six
        // give it its meaning without any change to the sequence machinery.
        "sort_name" => Some(Action::SetSortBy(SortBy::Name)),
        "sort_size" => Some(Action::SetSortBy(SortBy::Size)),
        "sort_time" => Some(Action::SetSortBy(SortBy::Modified)),
        "sort_extension" => Some(Action::SetSortBy(SortBy::Extension)),
        "sort_reverse" => Some(Action::ToggleSortReverse),
        "sort_dirs_first" => Some(Action::ToggleDirsFirst),
        "toggle_details" => Some(Action::CycleEntryDetails),
        "copy_absolute_path" => Some(Action::CopyAbsPath),
        "copy_relative_path" => Some(Action::CopyRelPath),
        "copy_filename" => Some(Action::CopyFilename),
        "copy_content" => Some(Action::CopyContent),
        "delete" => Some(Action::BeginDelete),
        "toggle_mark" => Some(Action::ToggleMark),
        "clear_marks" => Some(Action::ClearMarks),
        "paste_copy" => Some(Action::PasteMarks(TransferKind::Copy)),
        "paste_move" => Some(Action::PasteMarks(TransferKind::Move)),
        "enter_visual" => Some(Action::EnterVisual),
        "repeat_command" => Some(Action::RepeatLastCommand),
        "enter_search" => Some(Action::EnterSearch),
        "enter_command" => Some(Action::EnterCommand),
        "quit" => Some(Action::Quit),
        "open_with_os" => Some(Action::OpenWithOs),
        // Phase 8: tab management.
        "new_tab" => Some(Action::NewTab),
        "close_tab" => Some(Action::CloseTab),
        "switch_tab_next" => Some(Action::SwitchTabNext),
        "switch_tab_prev" => Some(Action::SwitchTabPrev),
        // Preview pane scrolling.
        "preview_scroll_down" => Some(Action::PreviewScrollDown),
        "preview_scroll_up" => Some(Action::PreviewScrollUp),
        "preview_page_down" => Some(Action::PreviewPageDown),
        "preview_page_up" => Some(Action::PreviewPageUp),
        "preview_scroll_top" => Some(Action::PreviewScrollTop),
        "preview_scroll_bottom" => Some(Action::PreviewScrollBottom),
        _ => None,
    }
}

fn search_action_from_name(name: &str) -> Option<Action> {
    match name {
        "exit" => Some(Action::ExitMode),
        "confirm" => Some(Action::SearchConfirm),
        "move_down" => Some(Action::SearchMoveDown),
        "move_up" => Some(Action::SearchMoveUp),
        "delete_char" => Some(Action::SearchDeleteChar),
        _ => None,
    }
}

fn append_to_sequence(prefix: char, key: KeyEvent) -> Option<String> {
    let KeyCode::Char(ch) = key.code else {
        return None;
    };
    if is_ctrl_chord(key.modifiers) {
        return None;
    }
    Some(format!("{prefix}{ch}"))
}

/// Renders `key` in the form `[keymap]` bindings are written in, or `None` for
/// a key with no config spelling.
///
/// A character carries its own shift: crossterm delivers `Shift`+`j` as
/// `Char('J')`, which is why `jump_bottom = "G"` works and why a `shift-`
/// prefix is added only to *named* keys — `shift-down`, `shift-end`. Without
/// that prefix every shifted arrow would be indistinguishable from the bare
/// one, and `Shift`+`↓` could not scroll the preview while `↓` moves the
/// selection.
fn key_to_config_string(key: KeyEvent) -> Option<String> {
    let named = match key.code {
        KeyCode::Char(ch) if is_ctrl_chord(key.modifiers) => {
            return Some(format!("ctrl-{ch}").to_ascii_lowercase());
        }
        // A space is spelled out: a binding of " " would be invisible in the
        // config file, and easy to take for an empty string.
        KeyCode::Char(' ') => "space",
        KeyCode::Char(ch) => return Some(ch.to_string()),
        KeyCode::Enter => "enter",
        KeyCode::Esc => "esc",
        KeyCode::Backspace => "backspace",
        KeyCode::Tab => "tab",
        // Terminals split on how they report Shift+Tab: some send Tab with the
        // shift modifier, others a distinct BackTab with no modifier. Both must
        // reach the same binding.
        KeyCode::BackTab => return Some("shift-tab".to_owned()),
        KeyCode::Left => "left",
        KeyCode::Right => "right",
        KeyCode::Up => "up",
        KeyCode::Down => "down",
        KeyCode::Home => "home",
        KeyCode::End => "end",
        _ => return None,
    };

    if key.modifiers.contains(KeyModifiers::SHIFT) {
        Some(format!("shift-{named}"))
    } else {
        Some(named.to_owned())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyEventKind, KeyEventState};

    /// The bug this guards: `tab` made `t` a prefix and `ctrl-r` made `c` one,
    /// so each waited for a second key that could never complete a sequence
    /// and swallowed it.
    #[test]
    fn a_named_key_binding_does_not_make_its_first_letter_a_prefix() {
        let keymap = crate::config::load(None).unwrap().keymap;
        assert_eq!(
            configured_nav_prefix(key(KeyCode::Char('t')), &keymap),
            None
        );
        assert_eq!(
            configured_nav_prefix(key(KeyCode::Char('c')), &keymap),
            None
        );
    }

    #[test]
    fn real_sequences_still_make_prefixes() {
        let keymap = crate::config::load(None).unwrap().keymap;
        for ch in ['g', 'y', 'd', 's'] {
            assert_eq!(
                configured_nav_prefix(key(KeyCode::Char(ch)), &keymap),
                Some(ch),
                "`{ch}` starts a default sequence"
            );
        }
    }

    /// `is_named_key` has to recognise every spelling the key translator can
    /// produce, or a new named key would reintroduce the swallowed keystroke.
    #[test]
    fn every_translated_named_key_is_recognised() {
        let codes = [
            KeyCode::Enter,
            KeyCode::Esc,
            KeyCode::Backspace,
            KeyCode::Tab,
            KeyCode::BackTab,
            KeyCode::Left,
            KeyCode::Right,
            KeyCode::Up,
            KeyCode::Down,
            KeyCode::Home,
            KeyCode::End,
            KeyCode::Char(' '),
        ];
        for code in codes {
            for modifiers in [KeyModifiers::NONE, KeyModifiers::SHIFT] {
                let event = KeyEvent {
                    modifiers,
                    ..key(code)
                };
                let name = key_to_config_string(event).expect("named key translates");
                assert!(is_named_key(&name), "`{name}` is not recognised as named");
            }
        }
        assert!(is_named_key("ctrl-r"));
        assert!(!is_named_key("gg"));
        assert!(!is_named_key("t"));
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }
    }

    #[test]
    fn parses_ctrl_key_binding() {
        let event = KeyEvent {
            code: KeyCode::Char('r'),
            modifiers: KeyModifiers::CONTROL,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        assert_eq!(key_to_config_string(event), Some("ctrl-r".to_owned()));
    }

    /// The bug this guards: `j` and `k` moved the selection instead of being
    /// typed, so neither letter could appear in a search query. A configured
    /// binding must not be able to reintroduce that.
    #[test]
    fn search_types_every_bare_character_even_when_bound() {
        let mut keymap = crate::config::load(None).unwrap().keymap;
        keymap.search.insert("move_down".to_owned(), "j".to_owned());
        keymap.search.insert("move_up".to_owned(), "k".to_owned());

        for ch in ['j', 'k', 'q', ':', '/', 'Z'] {
            assert_eq!(
                search(key(KeyCode::Char(ch)), &keymap),
                Some(Action::SearchAppendChar(ch)),
                "{ch} must reach the query"
            );
        }
    }

    #[test]
    fn search_moves_with_keys_that_are_not_text() {
        let keymap = crate::config::load(None).unwrap().keymap;
        let ctrl = |ch| KeyEvent {
            code: KeyCode::Char(ch),
            modifiers: KeyModifiers::CONTROL,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        assert_eq!(
            search(key(KeyCode::Down), &keymap),
            Some(Action::SearchMoveDown)
        );
        assert_eq!(
            search(key(KeyCode::Up), &keymap),
            Some(Action::SearchMoveUp)
        );
        assert_eq!(search(ctrl('n'), &keymap), Some(Action::SearchMoveDown));
        assert_eq!(search(ctrl('p'), &keymap), Some(Action::SearchMoveUp));
        assert_eq!(search(ctrl('h'), &keymap), Some(Action::SearchDeleteChar));
        assert_eq!(
            search(key(KeyCode::Enter), &keymap),
            Some(Action::SearchConfirm)
        );
        assert_eq!(search(key(KeyCode::Esc), &keymap), Some(Action::ExitMode));
    }

    #[test]
    fn shifted_characters_are_still_text() {
        let keymap = crate::config::load(None).unwrap().keymap;
        let shifted = KeyEvent {
            code: KeyCode::Char('K'),
            modifiers: KeyModifiers::SHIFT,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        assert_eq!(
            search(shifted, &keymap),
            Some(Action::SearchAppendChar('K'))
        );
    }

    /// Windows reports AltGr as Ctrl+Alt; on es-MX that is how `\` is typed.
    #[test]
    fn altgr_characters_are_text() {
        let keymap = crate::config::load(None).unwrap().keymap;
        let altgr = KeyEvent {
            code: KeyCode::Char('\\'),
            modifiers: KeyModifiers::CONTROL | KeyModifiers::ALT,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        assert_eq!(search(altgr, &keymap), Some(Action::SearchAppendChar('\\')));
    }

    /// A shifted character carries its own capital, so `J`/`K` reach the
    /// preview-scroll actions through the ordinary configured path — the same
    /// one that already serves `G`.
    #[test]
    fn preview_scroll_bindings_resolve_from_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let state = AppState::new(dir.path().to_owned()).unwrap();
        let mut ctx = InputCtx::default();
        let ctrl = |ch| KeyEvent {
            code: KeyCode::Char(ch),
            modifiers: KeyModifiers::CONTROL,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        let shifted = |code| KeyEvent {
            code,
            modifiers: KeyModifiers::SHIFT,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        for (event, expected) in [
            (key(KeyCode::Char('J')), Action::PreviewScrollDown),
            (key(KeyCode::Char('K')), Action::PreviewScrollUp),
            (ctrl('f'), Action::PreviewPageDown),
            (ctrl('b'), Action::PreviewPageUp),
            (shifted(KeyCode::Home), Action::PreviewScrollTop),
            (shifted(KeyCode::End), Action::PreviewScrollBottom),
        ] {
            assert_eq!(
                navigation(event, &mut ctx, &state),
                Some(expected.clone()),
                "{event:?} must map to {expected:?}"
            );
        }
    }

    /// The bug this guards: the built-in arrow fallbacks match on the key code
    /// alone, so `Shift+↓` used to move the selection. It must scroll the
    /// preview while the bare arrow still moves, and `j`/`k` must be untouched.
    #[test]
    fn shift_arrows_scroll_the_preview_and_bare_arrows_still_move() {
        let dir = tempfile::tempdir().unwrap();
        let state = AppState::new(dir.path().to_owned()).unwrap();
        let mut ctx = InputCtx::default();
        let shifted = |code| KeyEvent {
            code,
            modifiers: KeyModifiers::SHIFT,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        assert_eq!(
            navigation(shifted(KeyCode::Down), &mut ctx, &state),
            Some(Action::PreviewScrollDown)
        );
        assert_eq!(
            navigation(shifted(KeyCode::Up), &mut ctx, &state),
            Some(Action::PreviewScrollUp)
        );
        assert_eq!(
            navigation(key(KeyCode::Down), &mut ctx, &state),
            Some(Action::MoveDown)
        );
        assert_eq!(
            navigation(key(KeyCode::Up), &mut ctx, &state),
            Some(Action::MoveUp)
        );
        assert_eq!(
            navigation(key(KeyCode::Char('j')), &mut ctx, &state),
            Some(Action::MoveDown)
        );
        assert_eq!(
            navigation(key(KeyCode::Char('k')), &mut ctx, &state),
            Some(Action::MoveUp)
        );
    }

    #[test]
    fn shift_is_spelled_out_for_named_keys_only() {
        let shifted = |code| KeyEvent {
            code,
            modifiers: KeyModifiers::SHIFT,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        assert_eq!(
            key_to_config_string(shifted(KeyCode::Down)),
            Some("shift-down".to_owned())
        );
        assert_eq!(
            key_to_config_string(shifted(KeyCode::End)),
            Some("shift-end".to_owned())
        );
        assert_eq!(
            key_to_config_string(key(KeyCode::Home)),
            Some("home".to_owned())
        );
        // A capital is already the shifted form of the character.
        assert_eq!(
            key_to_config_string(shifted(KeyCode::Char('J'))),
            Some("J".to_owned())
        );
        // Terminals that send BackTab instead of Shift+Tab reach the same binding.
        assert_eq!(
            key_to_config_string(key(KeyCode::BackTab)),
            Some("shift-tab".to_owned())
        );
        assert_eq!(
            key_to_config_string(shifted(KeyCode::Tab)),
            Some("shift-tab".to_owned())
        );
    }

    #[test]
    fn mark_and_paste_bindings_resolve_from_defaults() {
        let dir = tempfile::tempdir().unwrap();
        let mut state = AppState::new(dir.path().to_owned()).unwrap();
        let mut ctx = InputCtx::default();

        assert_eq!(
            navigation(key(KeyCode::Char(' ')), &mut ctx, &state),
            Some(Action::ToggleMark)
        );
        assert_eq!(
            navigation(key(KeyCode::Esc), &mut ctx, &state),
            Some(Action::ClearMarks)
        );
        assert_eq!(
            navigation(key(KeyCode::Char('p')), &mut ctx, &state),
            Some(Action::SetPendingNavKey('p'))
        );
        state.pending_nav_key = Some('p');
        assert_eq!(
            navigation(key(KeyCode::Char('p')), &mut ctx, &state),
            Some(Action::PasteMarks(TransferKind::Copy))
        );
        assert_eq!(
            navigation(key(KeyCode::Char('m')), &mut ctx, &state),
            Some(Action::PasteMarks(TransferKind::Move))
        );
    }

    #[test]
    fn visual_mode_moves_commits_cancels_and_ignores_the_rest() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a"), b"").unwrap();
        let mut state = AppState::new(dir.path().to_owned()).unwrap();
        let mut ctx = InputCtx::default();
        assert_eq!(
            navigation(key(KeyCode::Char('v')), &mut ctx, &state),
            Some(Action::EnterVisual)
        );
        state.mode = crate::app::mode::Mode::Visual {
            anchor: state.entries[0].path.clone(),
        };

        let mut visual_key = |code| visual(key(code), &mut ctx, &state);
        assert_eq!(visual_key(KeyCode::Char('j')), Some(Action::MoveDown));
        assert_eq!(visual_key(KeyCode::Char('G')), Some(Action::JumpBottom));
        assert_eq!(
            visual_key(KeyCode::Char(' ')),
            Some(Action::CommitVisual(None))
        );
        assert_eq!(
            visual_key(KeyCode::Char('v')),
            Some(Action::CommitVisual(None))
        );
        assert_eq!(
            visual_key(KeyCode::Char('l')),
            Some(Action::CommitVisual(Some(Box::new(Action::EnterOrOpen))))
        );
        assert_eq!(visual_key(KeyCode::Esc), Some(Action::ExitMode));
        assert_eq!(
            visual_key(KeyCode::Char('q')),
            None,
            "no quitting mid-range"
        );
        assert_eq!(visual_key(KeyCode::Char('/')), None);
    }

    /// The maintainer types on Spanish (Latin America), where `@` is AltGr+Q
    /// and Windows reports AltGr as Ctrl+Alt. `@` has to work typed that way,
    /// with Shift (US English), and bare (a terminal that drops the modifier).
    #[test]
    fn at_repeats_the_last_command_on_every_layout() {
        let dir = tempfile::tempdir().unwrap();
        let state = AppState::new(dir.path().to_owned()).unwrap();
        let mut ctx = InputCtx::default();
        for modifiers in [
            KeyModifiers::CONTROL | KeyModifiers::ALT,
            KeyModifiers::SHIFT,
            KeyModifiers::NONE,
        ] {
            let at = KeyEvent {
                modifiers,
                ..key(KeyCode::Char('@'))
            };
            assert_eq!(
                navigation(at, &mut ctx, &state),
                Some(Action::RepeatLastCommand),
                "@ with {modifiers:?}"
            );
        }
    }

    /// AltGr must not make a character into a Ctrl chord — but a real Ctrl
    /// chord must stay one, or `Ctrl-c` would stop cancelling.
    #[test]
    fn altgr_is_text_and_ctrl_is_still_a_chord() {
        let event = |modifiers| KeyEvent {
            modifiers,
            ..key(KeyCode::Char('c'))
        };
        assert_eq!(
            key_to_config_string(event(KeyModifiers::CONTROL | KeyModifiers::ALT)),
            Some("c".to_owned())
        );
        assert_eq!(
            key_to_config_string(event(KeyModifiers::CONTROL)),
            Some("ctrl-c".to_owned())
        );
    }

    #[test]
    fn configured_binding_overrides_default_char() {
        let mut cfg = crate::config::load(None).unwrap();
        cfg.keymap
            .navigation
            .insert("move_down".to_owned(), "n".to_owned());
        let dir = tempfile::tempdir().unwrap();
        let state = AppState::with_config(dir.path().to_owned(), cfg).unwrap();
        let mut ctx = InputCtx::default();
        assert_eq!(
            navigation(key(KeyCode::Char('n')), &mut ctx, &state),
            Some(Action::MoveDown)
        );
    }
}