Skip to main content

tvui/
keymap.rs

1//! Data-driven key bindings: `scope: chord [chord …] = action [arg]` lines
2//! resolved against the scope chain the application builds.
3
4mod chord;
5#[cfg(test)]
6mod chord_tests;
7#[cfg(test)]
8mod hint_tests;
9#[cfg(test)]
10mod tests;
11
12use std::collections::{HashMap, HashSet};
13
14use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
15
16pub use chord::Chord;
17
18use crate::error::ParseError;
19
20/// What a binding line names: `action [arg]`.
21pub trait Action: Sized {
22    /// # Errors
23    /// The message for an unknown action or a missing, surplus or bad argument.
24    fn parse(name: &str, arg: Option<&str>) -> Result<Self, String>;
25}
26
27/// The chords typed so far of a multi-chord binding.
28#[derive(Debug, Clone, Default, PartialEq, Eq)]
29pub struct Pending(Vec<Chord>);
30
31/// What a key press means.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum Resolved<A> {
34    Action(A),
35    /// A printable character no binding claims, when text is wanted.
36    Text(char),
37    /// A prefix of a longer binding; the next key continues it.
38    Pending,
39    Unbound,
40}
41
42/// The bindings of every scope.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Keymap<A> {
45    scopes: HashMap<String, Vec<Binding<A>>>,
46    hints: HashMap<String, Vec<A>>,
47}
48
49#[derive(Debug, Clone, PartialEq)]
50struct Binding<A> {
51    chords: Vec<Chord>,
52    action: A,
53}
54
55enum Entry<A> {
56    Bind {
57        scope: String,
58        chords: Vec<Chord>,
59        /// `None` unbinds.
60        action: Option<A>,
61    },
62    Hints {
63        scope: String,
64        actions: Vec<A>,
65    },
66}
67
68enum Found<A> {
69    Exact(A),
70    Prefix,
71}
72
73impl<A: Action + Clone> Keymap<A> {
74    /// Parse `scope: chord [chord …] = action [arg]` entries, one per line or separated by `;`;
75    /// `#` starts a comment line. The action `none` unbinds. `scope: hint = action …` lists the
76    /// actions the scope offers as hints; `none` empties the list.
77    ///
78    /// # Errors
79    /// The first malformed entry, a binding written twice, or a binding that is
80    /// a strict prefix of another in its scope.
81    pub fn parse(text: &str) -> Result<Keymap<A>, ParseError> {
82        let mut keymap = Keymap {
83            scopes: HashMap::new(),
84            hints: HashMap::new(),
85        };
86        keymap.apply(text)?;
87        Ok(keymap)
88    }
89
90    /// This keymap with the bindings `text` writes replaced or unbound; same
91    /// grammar as [`Keymap::parse`].
92    ///
93    /// # Errors
94    /// As [`Keymap::parse`].
95    pub fn overridden(&self, text: &str) -> Result<Keymap<A>, ParseError> {
96        let mut keymap = self.clone();
97        keymap.apply(text)?;
98        Ok(keymap)
99    }
100
101    fn apply(&mut self, text: &str) -> Result<(), ParseError> {
102        let mut written = HashSet::new();
103        for (number, entry) in entries(text) {
104            match parse_entry::<A>(number, entry)? {
105                Entry::Hints { scope, actions } => {
106                    if !written.insert((scope.clone(), Vec::new())) {
107                        let message = format!("duplicate hint list for `{scope}`");
108                        return Err(ParseError::at(number, message));
109                    }
110                    self.hints.insert(scope, actions);
111                }
112                Entry::Bind {
113                    scope,
114                    chords,
115                    action,
116                } => {
117                    if !written.insert((scope.clone(), chords.clone())) {
118                        let message = format!("duplicate binding `{scope}: {}`", show(&chords));
119                        return Err(ParseError::at(number, message));
120                    }
121                    self.bind(number, scope, chords, action)?;
122                }
123            }
124        }
125        Ok(())
126    }
127
128    fn bind(
129        &mut self,
130        number: usize,
131        scope: String,
132        chords: Vec<Chord>,
133        action: Option<A>,
134    ) -> Result<(), ParseError> {
135        let bindings = self.scopes.entry(scope).or_default();
136        bindings.retain(|binding| binding.chords != chords);
137        let Some(action) = action else {
138            return Ok(());
139        };
140        let clash = bindings
141            .iter()
142            .map(|binding| &binding.chords)
143            .find(|other| other.starts_with(&chords) || chords.starts_with(other));
144        if let Some(other) = clash {
145            let (short, long) = match other.len() < chords.len() {
146                true => (other, &chords),
147                false => (&chords, other),
148            };
149            let message = format!("`{}` is a prefix of `{}`", show(short), show(long));
150            return Err(ParseError::at(number, message));
151        }
152        bindings.push(Binding { chords, action });
153        Ok(())
154    }
155
156    /// The bindings of `scope` in file order: chords and action.
157    pub fn bindings(&self, scope: &str) -> impl Iterator<Item = (&[Chord], &A)> {
158        let bindings = self.scopes.get(scope).map_or(&[][..], Vec::as_slice);
159        bindings.iter().map(|b| (b.chords.as_slice(), &b.action))
160    }
161
162    /// The actions `scope` offers as hints, in the order its hint list gives.
163    #[must_use]
164    pub fn hinted(&self, scope: &str) -> &[A] {
165        self.hints.get(scope).map_or(&[], Vec::as_slice)
166    }
167
168    /// Resolve `key` against the scope `chain`, innermost first; the first scope
169    /// with a binding or a binding prefix for the typed chords wins. `text` says
170    /// whether an unbound printable character is typed text.
171    pub fn resolve(
172        &self,
173        chain: &[&str],
174        text: bool,
175        pending: &mut Pending,
176        key: KeyEvent,
177    ) -> Resolved<A> {
178        if key.kind == KeyEventKind::Release {
179            return Resolved::Unbound;
180        }
181        let chord = Chord::from_event(key);
182        let typing = text && chord.is_printable();
183        if !pending.0.is_empty() && cancels(chord) {
184            pending.0.clear();
185            return Resolved::Unbound;
186        }
187        let continuing = !pending.0.is_empty();
188        pending.0.push(chord);
189        match self.find(chain, &pending.0) {
190            Some(Found::Exact(action)) => {
191                pending.0.clear();
192                Resolved::Action(action)
193            }
194            Some(Found::Prefix) => Resolved::Pending,
195            None => {
196                pending.0.clear();
197                match (continuing, typing, chord.code) {
198                    (false, true, KeyCode::Char(c)) => Resolved::Text(c),
199                    _ => Resolved::Unbound,
200                }
201            }
202        }
203    }
204
205    fn find(&self, chain: &[&str], typed: &[Chord]) -> Option<Found<A>> {
206        chain.iter().find_map(|scope| {
207            let bindings = self.scopes.get(*scope)?;
208            match bindings.iter().find(|binding| binding.chords == typed) {
209                Some(binding) => Some(Found::Exact(binding.action.clone())),
210                None => bindings
211                    .iter()
212                    .any(|binding| binding.chords.starts_with(typed))
213                    .then_some(Found::Prefix),
214            }
215        })
216    }
217}
218
219/// The 1-based line number and text of each entry of `text`.
220fn entries(text: &str) -> impl Iterator<Item = (usize, &str)> {
221    text.lines()
222        .enumerate()
223        .filter(|(_, line)| !line.trim_start().starts_with('#'))
224        .flat_map(|(index, line)| {
225            line.split(';')
226                .map(str::trim)
227                .filter(|entry| !entry.is_empty())
228                .map(move |entry| (index + 1, entry))
229        })
230}
231
232/// An entry of a keymap text, split but not parsed.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub struct Written<'a> {
235    pub line: usize,
236    pub scope: &'a str,
237    pub chords: &'a str,
238    pub action: &'a str,
239}
240
241/// The well-shaped entries of `text`; a malformed one is left for [`Keymap::parse`] to report.
242pub fn written_entries(text: &str) -> impl Iterator<Item = Written<'_>> {
243    entries(text).filter_map(|(line, entry)| {
244        let (scope, rest) = entry.split_once(':')?;
245        let (chords, action) = rest.split_once('=')?;
246        Some(Written {
247            line,
248            scope: scope.trim(),
249            chords: chords.trim(),
250            action: action.trim(),
251        })
252    })
253}
254
255/// Esc and C-g abandon a half-typed binding.
256fn cancels(chord: Chord) -> bool {
257    let control_g = chord.code == KeyCode::Char('g') && chord.modifiers == KeyModifiers::CONTROL;
258    control_g || (chord.code == KeyCode::Esc && chord.modifiers.is_empty())
259}
260
261fn show(chords: &[Chord]) -> String {
262    let names: Vec<String> = chords.iter().map(Chord::to_string).collect();
263    names.join(" ")
264}
265
266fn parse_entry<A: Action>(number: usize, entry: &str) -> Result<Entry<A>, ParseError> {
267    let fail = |message: String| ParseError::at(number, message);
268    let shape = || fail("expected `scope: chord = action [arg]`".to_string());
269    let (scope, rest) = entry.split_once(':').ok_or_else(shape)?;
270    let (chords, action) = rest.split_once('=').ok_or_else(shape)?;
271    let scope = scope.trim();
272    if scope.is_empty() || scope.contains(char::is_whitespace) {
273        return Err(fail(format!("bad scope name `{scope}`")));
274    }
275    if chords.trim() == "hint" {
276        let actions = parse_hints(action).map_err(fail)?;
277        return Ok(Entry::Hints {
278            scope: scope.to_string(),
279            actions,
280        });
281    }
282    let chords = chords
283        .split_whitespace()
284        .map(str::parse::<Chord>)
285        .collect::<Result<Vec<_>, _>>()
286        .map_err(fail)?;
287    if chords.is_empty() {
288        return Err(fail("no chord before `=`".to_string()));
289    }
290    if chords.iter().skip(1).copied().any(cancels) {
291        return Err(fail(
292            "Esc and C-g cancel a sequence, so they cannot continue one".to_string(),
293        ));
294    }
295    let mut words = action.split_whitespace();
296    let (name, arg) = (words.next().unwrap_or_default(), words.next());
297    if let Some(extra) = words.next() {
298        return Err(fail(format!("unexpected `{extra}` after the argument")));
299    }
300    let action = match (name, arg) {
301        ("none", None) => None,
302        ("none", Some(_)) => return Err(fail("`none` takes no argument".to_string())),
303        ("", _) => return Err(fail("no action after `=`".to_string())),
304        (name, arg) => Some(A::parse(name, arg).map_err(fail)?),
305    };
306    Ok(Entry::Bind {
307        scope: scope.to_string(),
308        chords,
309        action,
310    })
311}
312
313/// The actions of a hint list; they take no argument.
314fn parse_hints<A: Action>(text: &str) -> Result<Vec<A>, String> {
315    let words: Vec<&str> = text.split_whitespace().collect();
316    match words.as_slice() {
317        [] => Err("no action after `=`".to_string()),
318        ["none"] => Ok(Vec::new()),
319        _ => words.iter().map(|word| A::parse(word, None)).collect(),
320    }
321}