Skip to main content

tvui/keymap/
chord.rs

1use std::fmt;
2use std::str::FromStr;
3
4use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
5
6/// One key press with its modifiers, as written in a keymap file: `C-x`, `M-x`,
7/// `S-Tab`, `Enter`, `q`, `N`.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct Chord {
10    pub code: KeyCode,
11    pub modifiers: KeyModifiers,
12}
13
14/// `;` separates entries and `=` the action, so they are written by name.
15const NAMED: [(&str, KeyCode); 17] = [
16    ("Enter", KeyCode::Enter),
17    ("Esc", KeyCode::Esc),
18    ("Tab", KeyCode::Tab),
19    ("Backspace", KeyCode::Backspace),
20    ("Delete", KeyCode::Delete),
21    ("Insert", KeyCode::Insert),
22    ("Up", KeyCode::Up),
23    ("Down", KeyCode::Down),
24    ("Left", KeyCode::Left),
25    ("Right", KeyCode::Right),
26    ("Home", KeyCode::Home),
27    ("End", KeyCode::End),
28    ("PageUp", KeyCode::PageUp),
29    ("PageDown", KeyCode::PageDown),
30    ("Space", KeyCode::Char(' ')),
31    ("Semicolon", KeyCode::Char(';')),
32    ("Equals", KeyCode::Char('=')),
33];
34
35const MODIFIERS: [(char, KeyModifiers); 3] = [
36    ('C', KeyModifiers::CONTROL),
37    ('M', KeyModifiers::ALT),
38    ('S', KeyModifiers::SHIFT),
39];
40
41impl Chord {
42    /// A character typed with no modifier: text, unless a binding claims it.
43    #[must_use]
44    pub fn is_printable(self) -> bool {
45        matches!(self.code, KeyCode::Char(c) if !c.is_control()) && self.modifiers.is_empty()
46    }
47
48    /// The chord of a key event: the case of a character carries Shift (a Ctrl
49    /// letter is always lower case), and BackTab is Shift-Tab.
50    #[must_use]
51    pub fn from_event(event: KeyEvent) -> Chord {
52        match event.code {
53            KeyCode::BackTab => Chord {
54                code: KeyCode::Tab,
55                modifiers: event.modifiers | KeyModifiers::SHIFT,
56            },
57            KeyCode::Char(c) => Chord {
58                code: KeyCode::Char(match event.modifiers.contains(KeyModifiers::CONTROL) {
59                    true => c.to_ascii_lowercase(),
60                    false => c,
61                }),
62                modifiers: event.modifiers - KeyModifiers::SHIFT,
63            },
64            code => Chord {
65                code,
66                modifiers: event.modifiers,
67            },
68        }
69    }
70}
71
72/// The modifier of a leading `C-`, `M-` or `S-` that is followed by a key.
73fn prefix_modifier(text: &str) -> Option<KeyModifiers> {
74    let mut chars = text.chars();
75    let (letter, dash) = (chars.next()?, chars.next()?);
76    if dash != '-' || chars.as_str().is_empty() {
77        return None;
78    }
79    MODIFIERS
80        .iter()
81        .find(|(l, _)| *l == letter)
82        .map(|(_, flag)| *flag)
83}
84
85fn parse_key(word: &str) -> Result<KeyCode, String> {
86    if let Some((_, code)) = NAMED.iter().find(|(name, _)| *name == word) {
87        return Ok(*code);
88    }
89    if let Some(number) = word.strip_prefix('F').and_then(|n| n.parse::<u8>().ok())
90        && (1..=12).contains(&number)
91    {
92        return Ok(KeyCode::F(number));
93    }
94    let mut chars = word.chars();
95    match (chars.next(), chars.next()) {
96        (Some(c), None) => Ok(KeyCode::Char(c)),
97        _ => Err(format!("unknown key `{word}`")),
98    }
99}
100
101impl FromStr for Chord {
102    type Err = String;
103
104    fn from_str(text: &str) -> Result<Chord, String> {
105        let mut rest = text;
106        let mut modifiers = KeyModifiers::NONE;
107        while let Some(flag) = prefix_modifier(rest) {
108            modifiers |= flag;
109            rest = &rest[2..];
110        }
111        let code = parse_key(rest)?;
112        if matches!(code, KeyCode::Char(_)) && modifiers.contains(KeyModifiers::SHIFT) {
113            return Err(format!(
114                "`{text}`: write the shifted character itself, not `S-`"
115            ));
116        }
117        if matches!(code, KeyCode::Char(c) if c.is_ascii_uppercase())
118            && modifiers.contains(KeyModifiers::CONTROL)
119        {
120            return Err(format!("`{text}`: Ctrl letters are written in lower case"));
121        }
122        Ok(Chord { code, modifiers })
123    }
124}
125
126fn key_name(code: KeyCode) -> String {
127    if let KeyCode::F(number) = code {
128        return format!("F{number}");
129    }
130    let named = NAMED.iter().find(|(_, known)| *known == code);
131    match (named, code) {
132        (Some((name, _)), _) => (*name).to_string(),
133        (None, KeyCode::Char(c)) => c.to_string(),
134        (None, other) => format!("{other:?}"),
135    }
136}
137
138impl fmt::Display for Chord {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        for (letter, flag) in MODIFIERS {
141            if self.modifiers.contains(flag) {
142                write!(f, "{letter}-")?;
143            }
144        }
145        f.write_str(&key_name(self.code))
146    }
147}