Lines
98.7 %
Functions
100 %
Branches
use std::fmt;
use std::str::FromStr;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
/// One key press with its modifiers, as written in a keymap file: `C-x`, `M-x`,
/// `S-Tab`, `Enter`, `q`, `N`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Chord {
pub code: KeyCode,
pub modifiers: KeyModifiers,
}
/// `;` separates entries and `=` the action, so they are written by name.
const NAMED: [(&str, KeyCode); 17] = [
("Enter", KeyCode::Enter),
("Esc", KeyCode::Esc),
("Tab", KeyCode::Tab),
("Backspace", KeyCode::Backspace),
("Delete", KeyCode::Delete),
("Insert", KeyCode::Insert),
("Up", KeyCode::Up),
("Down", KeyCode::Down),
("Left", KeyCode::Left),
("Right", KeyCode::Right),
("Home", KeyCode::Home),
("End", KeyCode::End),
("PageUp", KeyCode::PageUp),
("PageDown", KeyCode::PageDown),
("Space", KeyCode::Char(' ')),
("Semicolon", KeyCode::Char(';')),
("Equals", KeyCode::Char('=')),
];
const MODIFIERS: [(char, KeyModifiers); 3] = [
('C', KeyModifiers::CONTROL),
('M', KeyModifiers::ALT),
('S', KeyModifiers::SHIFT),
impl Chord {
/// A character typed with no modifier: text, unless a binding claims it.
#[must_use]
pub fn is_printable(self) -> bool {
matches!(self.code, KeyCode::Char(c) if !c.is_control()) && self.modifiers.is_empty()
/// The chord of a key event: the case of a character carries Shift (a Ctrl
/// letter is always lower case), and BackTab is Shift-Tab.
pub fn from_event(event: KeyEvent) -> Chord {
match event.code {
KeyCode::BackTab => Chord {
code: KeyCode::Tab,
modifiers: event.modifiers | KeyModifiers::SHIFT,
},
KeyCode::Char(c) => Chord {
code: KeyCode::Char(match event.modifiers.contains(KeyModifiers::CONTROL) {
true => c.to_ascii_lowercase(),
false => c,
}),
modifiers: event.modifiers - KeyModifiers::SHIFT,
code => Chord {
code,
modifiers: event.modifiers,
/// The modifier of a leading `C-`, `M-` or `S-` that is followed by a key.
fn prefix_modifier(text: &str) -> Option<KeyModifiers> {
let mut chars = text.chars();
let (letter, dash) = (chars.next()?, chars.next()?);
if dash != '-' || chars.as_str().is_empty() {
return None;
MODIFIERS
.iter()
.find(|(l, _)| *l == letter)
.map(|(_, flag)| *flag)
fn parse_key(word: &str) -> Result<KeyCode, String> {
if let Some((_, code)) = NAMED.iter().find(|(name, _)| *name == word) {
return Ok(*code);
if let Some(number) = word.strip_prefix('F').and_then(|n| n.parse::<u8>().ok())
&& (1..=12).contains(&number)
{
return Ok(KeyCode::F(number));
let mut chars = word.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => Ok(KeyCode::Char(c)),
_ => Err(format!("unknown key `{word}`")),
impl FromStr for Chord {
type Err = String;
fn from_str(text: &str) -> Result<Chord, String> {
let mut rest = text;
let mut modifiers = KeyModifiers::NONE;
while let Some(flag) = prefix_modifier(rest) {
modifiers |= flag;
rest = &rest[2..];
let code = parse_key(rest)?;
if matches!(code, KeyCode::Char(_)) && modifiers.contains(KeyModifiers::SHIFT) {
return Err(format!(
"`{text}`: write the shifted character itself, not `S-`"
));
if matches!(code, KeyCode::Char(c) if c.is_ascii_uppercase())
&& modifiers.contains(KeyModifiers::CONTROL)
return Err(format!("`{text}`: Ctrl letters are written in lower case"));
Ok(Chord { code, modifiers })
fn key_name(code: KeyCode) -> String {
if let KeyCode::F(number) = code {
return format!("F{number}");
let named = NAMED.iter().find(|(_, known)| *known == code);
match (named, code) {
(Some((name, _)), _) => (*name).to_string(),
(None, KeyCode::Char(c)) => c.to_string(),
(None, other) => format!("{other:?}"),
impl fmt::Display for Chord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (letter, flag) in MODIFIERS {
if self.modifiers.contains(flag) {
write!(f, "{letter}-")?;
f.write_str(&key_name(self.code))