Skip to main content

basic_lookup/
basic_lookup.rs

1//! Bind some keys, then resolve inputs. A miss (`None`) is the "pass it through"
2//! signal for the same-process case.
3//!
4//! Run with: `cargo run -p keymap-core --example basic_lookup`
5
6use keymap_core::{Key, KeyInput, Keymap, Modifiers};
7
8#[derive(Clone, Debug, PartialEq)]
9enum Action {
10    Quit,
11    Save,
12    SplitPane,
13}
14
15fn main() {
16    let mut keymap = Keymap::new();
17    keymap.bind(KeyInput::new(Key::Char('q'), Modifiers::CTRL), Action::Quit);
18    keymap.bind(KeyInput::new(Key::Char('s'), Modifiers::CTRL), Action::Save);
19    keymap.bind(
20        KeyInput::new(Key::Char('1'), Modifiers::SUPER),
21        Action::SplitPane,
22    );
23
24    // In a real app these come from the terminal backend (see the `crossterm`
25    // feature's `TryFrom<KeyEvent>`); here we construct them directly.
26    let inputs = [
27        KeyInput::new(Key::Char('q'), Modifiers::CTRL),
28        KeyInput::new(Key::Char('1'), Modifiers::SUPER),
29        KeyInput::new(Key::Char('x'), Modifiers::NONE),
30    ];
31
32    for input in inputs {
33        match keymap.get(&input) {
34            Some(action) => println!("{input:>8}  ->  consume {action:?}"),
35            None => println!("{input:>8}  ->  pass through"),
36        }
37    }
38}