1
//! Data-driven key bindings: `scope: chord [chord …] = action [arg]` lines
2
//! resolved against the scope chain the application builds.
3

            
4
mod chord;
5
#[cfg(test)]
6
mod chord_tests;
7
#[cfg(test)]
8
mod hint_tests;
9
#[cfg(test)]
10
mod tests;
11

            
12
use std::collections::{HashMap, HashSet};
13

            
14
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
15

            
16
pub use chord::Chord;
17

            
18
use crate::error::ParseError;
19

            
20
/// What a binding line names: `action [arg]`.
21
pub 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)]
29
pub struct Pending(Vec<Chord>);
30

            
31
/// What a key press means.
32
#[derive(Debug, Clone, PartialEq, Eq)]
33
pub 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)]
44
pub struct Keymap<A> {
45
    scopes: HashMap<String, Vec<Binding<A>>>,
46
    hints: HashMap<String, Vec<A>>,
47
}
48

            
49
#[derive(Debug, Clone, PartialEq)]
50
struct Binding<A> {
51
    chords: Vec<Chord>,
52
    action: A,
53
}
54

            
55
enum 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

            
68
enum Found<A> {
69
    Exact(A),
70
    Prefix,
71
}
72

            
73
impl<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
2864
    pub fn parse(text: &str) -> Result<Keymap<A>, ParseError> {
82
2864
        let mut keymap = Keymap {
83
2864
            scopes: HashMap::new(),
84
2864
            hints: HashMap::new(),
85
2864
        };
86
2864
        keymap.apply(text)?;
87
2845
        Ok(keymap)
88
2864
    }
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
3198
    pub fn overridden(&self, text: &str) -> Result<Keymap<A>, ParseError> {
96
3198
        let mut keymap = self.clone();
97
3198
        keymap.apply(text)?;
98
3050
        Ok(keymap)
99
3198
    }
100

            
101
6062
    fn apply(&mut self, text: &str) -> Result<(), ParseError> {
102
6062
        let mut written = HashSet::new();
103
6062
        for (number, entry) in entries(text) {
104
747205
            match parse_entry::<A>(number, entry)? {
105
                Entry::Hints { scope, actions } => {
106
75880
                    if !written.insert((scope.clone(), Vec::new())) {
107
1
                        let message = format!("duplicate hint list for `{scope}`");
108
1
                        return Err(ParseError::at(number, message));
109
75879
                    }
110
75879
                    self.hints.insert(scope, actions);
111
                }
112
                Entry::Bind {
113
                    scope,
114
                    chords,
115
                    action,
116
                } => {
117
671164
                    if !written.insert((scope.clone(), chords.clone())) {
118
2
                        let message = format!("duplicate binding `{scope}: {}`", show(&chords));
119
2
                        return Err(ParseError::at(number, message));
120
671162
                    }
121
671162
                    self.bind(number, scope, chords, action)?;
122
                }
123
            }
124
        }
125
5895
        Ok(())
126
6062
    }
127

            
128
671162
    fn bind(
129
671162
        &mut self,
130
671162
        number: usize,
131
671162
        scope: String,
132
671162
        chords: Vec<Chord>,
133
671162
        action: Option<A>,
134
671162
    ) -> Result<(), ParseError> {
135
671162
        let bindings = self.scopes.entry(scope).or_default();
136
3619262
        bindings.retain(|binding| binding.chords != chords);
137
671162
        let Some(action) = action else {
138
13
            return Ok(());
139
        };
140
671149
        let clash = bindings
141
671149
            .iter()
142
3618986
            .map(|binding| &binding.chords)
143
3618986
            .find(|other| other.starts_with(&chords) || chords.starts_with(other));
144
671149
        if let Some(other) = clash {
145
3
            let (short, long) = match other.len() < chords.len() {
146
1
                true => (other, &chords),
147
2
                false => (&chords, other),
148
            };
149
3
            let message = format!("`{}` is a prefix of `{}`", show(short), show(long));
150
3
            return Err(ParseError::at(number, message));
151
671146
        }
152
671146
        bindings.push(Binding { chords, action });
153
671146
        Ok(())
154
671162
    }
155

            
156
    /// The bindings of `scope` in file order: chords and action.
157
251072
    pub fn bindings(&self, scope: &str) -> impl Iterator<Item = (&[Chord], &A)> {
158
251072
        let bindings = self.scopes.get(scope).map_or(&[][..], Vec::as_slice);
159
2068799
        bindings.iter().map(|b| (b.chords.as_slice(), &b.action))
160
251072
    }
161

            
162
    /// The actions `scope` offers as hints, in the order its hint list gives.
163
    #[must_use]
164
4714
    pub fn hinted(&self, scope: &str) -> &[A] {
165
4714
        self.hints.get(scope).map_or(&[], Vec::as_slice)
166
4714
    }
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
3415
    pub fn resolve(
172
3415
        &self,
173
3415
        chain: &[&str],
174
3415
        text: bool,
175
3415
        pending: &mut Pending,
176
3415
        key: KeyEvent,
177
3415
    ) -> Resolved<A> {
178
3415
        if key.kind == KeyEventKind::Release {
179
1
            return Resolved::Unbound;
180
3414
        }
181
3414
        let chord = Chord::from_event(key);
182
3414
        let typing = text && chord.is_printable();
183
3414
        if !pending.0.is_empty() && cancels(chord) {
184
2
            pending.0.clear();
185
2
            return Resolved::Unbound;
186
3412
        }
187
3412
        let continuing = !pending.0.is_empty();
188
3412
        pending.0.push(chord);
189
3412
        match self.find(chain, &pending.0) {
190
            Some(Found::Exact(action)) => {
191
2092
                pending.0.clear();
192
2092
                Resolved::Action(action)
193
            }
194
17
            Some(Found::Prefix) => Resolved::Pending,
195
            None => {
196
1303
                pending.0.clear();
197
1303
                match (continuing, typing, chord.code) {
198
1153
                    (false, true, KeyCode::Char(c)) => Resolved::Text(c),
199
150
                    _ => Resolved::Unbound,
200
                }
201
            }
202
        }
203
3415
    }
204

            
205
3412
    fn find(&self, chain: &[&str], typed: &[Chord]) -> Option<Found<A>> {
206
8116
        chain.iter().find_map(|scope| {
207
8116
            let bindings = self.scopes.get(*scope)?;
208
64482
            match bindings.iter().find(|binding| binding.chords == typed) {
209
2092
                Some(binding) => Some(Found::Exact(binding.action.clone())),
210
6000
                None => bindings
211
6000
                    .iter()
212
53304
                    .any(|binding| binding.chords.starts_with(typed))
213
6000
                    .then_some(Found::Prefix),
214
            }
215
8116
        })
216
3412
    }
217
}
218

            
219
/// The 1-based line number and text of each entry of `text`.
220
35836
fn entries(text: &str) -> impl Iterator<Item = (usize, &str)> {
221
35836
    text.lines()
222
35836
        .enumerate()
223
1486667
        .filter(|(_, line)| !line.trim_start().starts_with('#'))
224
1401529
        .flat_map(|(index, line)| {
225
1401529
            line.split(';')
226
1401529
                .map(str::trim)
227
1714320
                .filter(|entry| !entry.is_empty())
228
1494304
                .map(move |entry| (index + 1, entry))
229
1401529
        })
230
35836
}
231

            
232
/// An entry of a keymap text, split but not parsed.
233
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234
pub 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.
242
17923
pub fn written_entries(text: &str) -> impl Iterator<Item = Written<'_>> {
243
747099
    entries(text).filter_map(|(line, entry)| {
244
747099
        let (scope, rest) = entry.split_once(':')?;
245
747042
        let (chords, action) = rest.split_once('=')?;
246
747005
        Some(Written {
247
747005
            line,
248
747005
            scope: scope.trim(),
249
747005
            chords: chords.trim(),
250
747005
            action: action.trim(),
251
747005
        })
252
747099
    })
253
17923
}
254

            
255
/// Esc and C-g abandon a half-typed binding.
256
1893
fn cancels(chord: Chord) -> bool {
257
1893
    let control_g = chord.code == KeyCode::Char('g') && chord.modifiers == KeyModifiers::CONTROL;
258
1893
    control_g || (chord.code == KeyCode::Esc && chord.modifiers.is_empty())
259
1893
}
260

            
261
10
fn show(chords: &[Chord]) -> String {
262
10
    let names: Vec<String> = chords.iter().map(Chord::to_string).collect();
263
10
    names.join(" ")
264
10
}
265

            
266
747205
fn parse_entry<A: Action>(number: usize, entry: &str) -> Result<Entry<A>, ParseError> {
267
161
    let fail = |message: String| ParseError::at(number, message);
268
94
    let shape = || fail("expected `scope: chord = action [arg]`".to_string());
269
747205
    let (scope, rest) = entry.split_once(':').ok_or_else(shape)?;
270
747149
    let (chords, action) = rest.split_once('=').ok_or_else(shape)?;
271
747111
    let scope = scope.trim();
272
747111
    if scope.is_empty() || scope.contains(char::is_whitespace) {
273
1
        return Err(fail(format!("bad scope name `{scope}`")));
274
747110
    }
275
747110
    if chords.trim() == "hint" {
276
75883
        let actions = parse_hints(action).map_err(fail)?;
277
75880
        return Ok(Entry::Hints {
278
75880
            scope: scope.to_string(),
279
75880
            actions,
280
75880
        });
281
671227
    }
282
671227
    let chords = chords
283
671227
        .split_whitespace()
284
671227
        .map(str::parse::<Chord>)
285
671227
        .collect::<Result<Vec<_>, _>>()
286
671227
        .map_err(fail)?;
287
671226
    if chords.is_empty() {
288
1
        return Err(fail("no chord before `=`".to_string()));
289
671225
    }
290
671225
    if chords.iter().skip(1).copied().any(cancels) {
291
2
        return Err(fail(
292
2
            "Esc and C-g cancel a sequence, so they cannot continue one".to_string(),
293
2
        ));
294
671223
    }
295
671223
    let mut words = action.split_whitespace();
296
671223
    let (name, arg) = (words.next().unwrap_or_default(), words.next());
297
671223
    if let Some(extra) = words.next() {
298
1
        return Err(fail(format!("unexpected `{extra}` after the argument")));
299
671222
    }
300
671222
    let action = match (name, arg) {
301
13
        ("none", None) => None,
302
1
        ("none", Some(_)) => return Err(fail("`none` takes no argument".to_string())),
303
13
        ("", _) => return Err(fail("no action after `=`".to_string())),
304
671195
        (name, arg) => Some(A::parse(name, arg).map_err(fail)?),
305
    };
306
671164
    Ok(Entry::Bind {
307
671164
        scope: scope.to_string(),
308
671164
        chords,
309
671164
        action,
310
671164
    })
311
747205
}
312

            
313
/// The actions of a hint list; they take no argument.
314
75883
fn parse_hints<A: Action>(text: &str) -> Result<Vec<A>, String> {
315
75883
    let words: Vec<&str> = text.split_whitespace().collect();
316
75883
    match words.as_slice() {
317
1
        [] => Err("no action after `=`".to_string()),
318
1
        ["none"] => Ok(Vec::new()),
319
168614
        _ => words.iter().map(|word| A::parse(word, None)).collect(),
320
    }
321
75883
}