rustyline/
keys.rs

1//! Key constants
2
3/// #[non_exhaustive]
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub enum KeyPress {
6    UnknownEscSeq,
7    Backspace, // Ctrl('H')
8    BackTab,
9    Char(char),
10    ControlDown,
11    ControlLeft,
12    ControlRight,
13    ControlUp,
14    Ctrl(char),
15    Delete,
16    Down,
17    End,
18    Enter, // Ctrl('M')
19    Esc,   // Ctrl('[')
20    F(u8),
21    Home,
22    Insert,
23    Left,
24    Meta(char),
25    Null,
26    PageDown,
27    PageUp,
28    Right,
29    ShiftDown,
30    ShiftLeft,
31    ShiftRight,
32    ShiftUp,
33    Tab, // Ctrl('I')
34    Up,
35}
36
37//#[allow(clippy::match_same_arms)]
38pub fn char_to_key_press(c: char) -> KeyPress {
39    if !c.is_control() {
40        return KeyPress::Char(c);
41    }
42    match c {
43        '\x00' => KeyPress::Ctrl(' '),
44        '\x01' => KeyPress::Ctrl('A'),
45        '\x02' => KeyPress::Ctrl('B'),
46        '\x03' => KeyPress::Ctrl('C'),
47        '\x04' => KeyPress::Ctrl('D'),
48        '\x05' => KeyPress::Ctrl('E'),
49        '\x06' => KeyPress::Ctrl('F'),
50        '\x07' => KeyPress::Ctrl('G'),
51        '\x08' => KeyPress::Backspace, // '\b'
52        '\x09' => KeyPress::Tab,       // '\t'
53        '\x0a' => KeyPress::Ctrl('J'), // '\n' (10)
54        '\x0b' => KeyPress::Ctrl('K'),
55        '\x0c' => KeyPress::Ctrl('L'),
56        '\x0d' => KeyPress::Enter, // '\r' (13)
57        '\x0e' => KeyPress::Ctrl('N'),
58        '\x0f' => KeyPress::Ctrl('O'),
59        '\x10' => KeyPress::Ctrl('P'),
60        '\x12' => KeyPress::Ctrl('R'),
61        '\x13' => KeyPress::Ctrl('S'),
62        '\x14' => KeyPress::Ctrl('T'),
63        '\x15' => KeyPress::Ctrl('U'),
64        '\x16' => KeyPress::Ctrl('V'),
65        '\x17' => KeyPress::Ctrl('W'),
66        '\x18' => KeyPress::Ctrl('X'),
67        '\x19' => KeyPress::Ctrl('Y'),
68        '\x1a' => KeyPress::Ctrl('Z'),
69        '\x1b' => KeyPress::Esc, // Ctrl-[
70        '\x1c' => KeyPress::Ctrl('\\'),
71        '\x1d' => KeyPress::Ctrl(']'),
72        '\x1e' => KeyPress::Ctrl('^'),
73        '\x1f' => KeyPress::Ctrl('_'),
74        '\x7f' => KeyPress::Backspace, // Rubout
75        _ => KeyPress::Null,
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::{char_to_key_press, KeyPress};
82
83    #[test]
84    fn char_to_key() {
85        assert_eq!(KeyPress::Esc, char_to_key_press('\x1b'));
86    }
87}