Skip to main content

tui/
keymap.rs

1//! Key-event translation: crossterm [`KeyEvent`] → [`Intent`], through the
2//! preset keymap and the scope chain `scopes::chain` builds from focus.
3
4use crate::app::{App, button_of_key};
5use crate::event::{Intent, apply};
6use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
7use scopes::{SCOPES, Scopes, in_typing_chain};
8use std::time::Instant;
9use tvui::keymap::{Chord, Keymap, Pending, Resolved, Written, written_entries};
10
11mod help;
12mod scopes;
13mod shown;
14
15pub use help::{help_lines, help_topic};
16pub use shown::{
17    Hint, KeyView, here, hinted, in_form, in_modal, in_rows, in_view, in_view_all, in_window,
18};
19
20/// A keymap file: its name for error messages and its text.
21type Layer<'a> = (&'a str, &'a str);
22
23const BASE: Layer<'static> = ("base.keys", include_str!("keymap/base.keys"));
24const EMACS: Layer<'static> = ("emacs.keys", include_str!("keymap/emacs.keys"));
25const CUA: Layer<'static> = ("cua.keys", include_str!("keymap/cua.keys"));
26const VIM: Layer<'static> = ("vim.keys", include_str!("keymap/vim.keys"));
27
28/// A preset: the layers it is built from, each over the previous, and its vim state.
29struct Preset {
30    name: &'static str,
31    layers: &'static [Layer<'static>],
32    vim: VimState,
33}
34
35/// The preset used when neither the command line nor the config names one.
36pub const DEFAULT_KEYMAP: &str = "cua";
37
38const PRESETS: &[Preset] = &[
39    Preset {
40        name: "cua",
41        layers: &[BASE, CUA],
42        vim: VimState::Off,
43    },
44    Preset {
45        name: "emacs",
46        layers: &[BASE, EMACS],
47        vim: VimState::Off,
48    },
49    Preset {
50        name: "vim",
51        layers: &[BASE, EMACS, VIM],
52        vim: VimState::Insert,
53    },
54];
55
56/// Where the vim preset is: typing or normal mode.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum VimState {
59    /// The preset has no vim state.
60    Off,
61    Normal,
62    Insert,
63}
64
65/// The preset keymap, the chords typed so far and the vim state.
66pub struct Keys {
67    name: &'static str,
68    map: Keymap<Intent>,
69    pending: Pending,
70    chain: Vec<&'static str>,
71    vim: VimState,
72}
73
74/// What a user override may not bind: a printable key, which would stop typing.
75fn bound_printable(entry: &Written<'_>, user: bool) -> bool {
76    let first = entry.chords.split_whitespace().next();
77    let printable = first.and_then(|chord| chord.parse::<Chord>().ok());
78    entry.action != "none"
79        && printable.is_some_and(Chord::is_printable)
80        && (entry.scope == "global" || (user && in_typing_chain(entry.scope)))
81}
82
83/// # Errors
84/// The first entry of `text` binding an unknown scope, or a printable key where it would stop
85/// typing: always in `global`, and for a `user` override in any scope that types text.
86fn check_scopes(text: &str, user: bool) -> Result<(), String> {
87    for entry in written_entries(text) {
88        let Written { line, scope, .. } = entry;
89        if !SCOPES.iter().any(|known| known.name == scope) {
90            return Err(format!("line {line}: unknown scope `{scope}`"));
91        }
92        if bound_printable(&entry, user) {
93            let key = entry.chords;
94            return Err(format!(
95                "line {line}: `{scope}` cannot bind the printable key `{key}`"
96            ));
97        }
98    }
99    Ok(())
100}
101
102/// `text` over `lower`, or alone for the first layer.
103fn read_layer(
104    lower: Option<&Keymap<Intent>>,
105    (file, text): &Layer<'_>,
106    user: bool,
107) -> Result<Keymap<Intent>, String> {
108    check_scopes(text, user).map_err(|err| format!("{file}: {err}"))?;
109    let read = match lower {
110        Some(lower) => lower.overridden(text),
111        None => Keymap::parse(text),
112    };
113    read.map_err(|err| format!("{file}: {err}"))
114}
115
116impl Keys {
117    /// Whether `other` is the same preset binding the same keys, whatever the typing state.
118    #[must_use]
119    pub fn same_bindings(&self, other: &Keys) -> bool {
120        self.name == other.name && self.map == other.map
121    }
122
123    /// The names of the built-in keymaps.
124    pub fn preset_names() -> impl Iterator<Item = &'static str> {
125        PRESETS.iter().map(|preset| preset.name)
126    }
127
128    /// # Errors
129    /// The message for an unknown preset or one that does not parse.
130    pub fn preset(name: &str) -> Result<Keys, String> {
131        let Some(preset) = PRESETS.iter().find(|preset| preset.name == name) else {
132            let known: Vec<_> = PRESETS.iter().map(|preset| preset.name).collect();
133            return Err(format!(
134                "unknown keymap `{name}`; known: {}",
135                known.join(", ")
136            ));
137        };
138        Keys::layered(preset.name, preset.vim, preset.layers)
139            .map_err(|err| format!("{name} keymap: {err}"))
140    }
141
142    /// These keys with the entries of `text` rebound or unbound.
143    ///
144    /// # Errors
145    /// The message for an entry that does not parse, names an unknown scope or binds a
146    /// printable key where it would stop typing.
147    pub fn overridden(&self, text: &str) -> Result<Keys, String> {
148        let map = read_layer(Some(&self.map), &("overrides", text), true)?;
149        Ok(Keys {
150            name: self.name,
151            map,
152            pending: Pending::default(),
153            chain: Vec::new(),
154            vim: self.vim,
155        })
156    }
157
158    fn layered(name: &'static str, vim: VimState, layers: &[Layer<'_>]) -> Result<Keys, String> {
159        let mut map = None;
160        for layer in layers {
161            map = Some(read_layer(map.as_ref(), layer, false)?);
162        }
163        Ok(Keys {
164            name,
165            map: map.ok_or("no layers")?,
166            pending: Pending::default(),
167            chain: Vec::new(),
168            vim,
169        })
170    }
171
172    pub fn vim(&self) -> VimState {
173        self.vim
174    }
175
176    /// Switch the vim state; the emacs preset has none.
177    pub fn set_vim(&mut self, state: VimState) {
178        if self.vim != VimState::Off {
179            self.vim = state;
180        }
181    }
182
183    /// Whether the last key was resolved in a vim mode scope.
184    fn in_vim_scope(&self) -> bool {
185        self.chain
186            .first()
187            .is_some_and(|scope| scope.starts_with("vim-"))
188    }
189
190    pub fn indicator(&self) -> &'static str {
191        match self.vim {
192            VimState::Off => self.name,
193            VimState::Normal => "vim:normal",
194            VimState::Insert => "vim:insert",
195        }
196    }
197
198    /// A half-typed binding does not survive a move to other scopes.
199    fn resolve(&mut self, scopes: Scopes, key: KeyEvent) -> Resolved<Intent> {
200        if self.chain != scopes.names {
201            self.pending = Pending::default();
202            self.chain = scopes.names;
203        }
204        match self
205            .map
206            .resolve(&self.chain, scopes.text, &mut self.pending, key)
207        {
208            Resolved::Text(c) => Resolved::Action(Intent::InsertChar(c)),
209            other => other,
210        }
211    }
212}
213
214/// Chooses the open menu's entry the typed `key` names, if any.
215fn choose_by_mnemonic(app: &mut App, key: KeyEvent) {
216    if let Some(at) = app.menu_mnemonic(key) {
217        app.select_menu_item(at);
218        apply(app, Intent::MenuSelect);
219    }
220}
221
222/// Applies `intent` of `key`, a button's press by a key first being drawn down.
223fn act(app: &mut App, key: KeyEvent, intent: Intent) {
224    match button_of_key(app, key, intent) {
225        Some((index, spec)) => app.hold_button_by_key(index, spec, Instant::now()),
226        None => apply(app, intent),
227    }
228}
229
230fn run(app: &mut App, key: KeyEvent) -> Resolved<Intent> {
231    app.flush_key_press();
232    app.cancel_press();
233    let scopes = scopes::chain(app);
234    let resolved = app.keys.resolve(scopes, key);
235    match &resolved {
236        Resolved::Action(intent) => act(app, key, *intent),
237        Resolved::Unbound if app.menu.is_some() => choose_by_mnemonic(app, key),
238        _ => {}
239    }
240    resolved
241}
242
243/// Translate the key and apply it. Over SSH an Esc followed within 40 ms by a
244/// key arrives as `M-key`; where vim binds Esc, an unbound `M-key` is both.
245pub fn handle_key(app: &mut App, key: KeyEvent) {
246    if run(app, key) != Resolved::Unbound {
247        return;
248    }
249    let vim_focus = app.keys.in_vim_scope();
250    let split = matches!(key.code, KeyCode::Char(_) | KeyCode::Enter)
251        && key.modifiers.contains(KeyModifiers::ALT);
252    if vim_focus && split {
253        run(app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
254        run(
255            app,
256            KeyEvent::new(key.code, key.modifiers - KeyModifiers::ALT),
257        );
258    }
259}
260
261#[cfg(test)]
262mod arrow_tests;
263#[cfg(test)]
264mod builder_tests;
265#[cfg(test)]
266mod button_hold_tests;
267#[cfg(test)]
268mod button_tests;
269#[cfg(test)]
270mod confirm_tests;
271#[cfg(test)]
272mod console_tests;
273#[cfg(test)]
274mod cua_tests;
275#[cfg(test)]
276mod cursor_tests;
277#[cfg(test)]
278mod field_tests;
279#[cfg(test)]
280mod form_hints_tests;
281#[cfg(test)]
282mod grid_edit_tests;
283#[cfg(test)]
284mod help_tests;
285#[cfg(test)]
286mod hints_tests;
287#[cfg(test)]
288mod list_page_tests;
289#[cfg(test)]
290mod menu_tests;
291#[cfg(test)]
292mod preset_tests;
293#[cfg(test)]
294mod tab_tests;
295#[cfg(test)]
296mod tests;
297#[cfg(test)]
298mod vim_list_tests;
299#[cfg(test)]
300mod vim_tests;