Lines
100 %
Functions
74.17 %
Branches
//! Data-driven key bindings: `scope: chord [chord …] = action [arg]` lines
//! resolved against the scope chain the application builds.
mod chord;
#[cfg(test)]
mod chord_tests;
mod hint_tests;
mod tests;
use std::collections::{HashMap, HashSet};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
pub use chord::Chord;
use crate::error::ParseError;
/// What a binding line names: `action [arg]`.
pub trait Action: Sized {
/// # Errors
/// The message for an unknown action or a missing, surplus or bad argument.
fn parse(name: &str, arg: Option<&str>) -> Result<Self, String>;
}
/// The chords typed so far of a multi-chord binding.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Pending(Vec<Chord>);
/// What a key press means.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolved<A> {
Action(A),
/// A printable character no binding claims, when text is wanted.
Text(char),
/// A prefix of a longer binding; the next key continues it.
Pending,
Unbound,
/// The bindings of every scope.
#[derive(Debug, Clone, PartialEq)]
pub struct Keymap<A> {
scopes: HashMap<String, Vec<Binding<A>>>,
hints: HashMap<String, Vec<A>>,
struct Binding<A> {
chords: Vec<Chord>,
action: A,
enum Entry<A> {
Bind {
scope: String,
/// `None` unbinds.
action: Option<A>,
},
Hints {
actions: Vec<A>,
enum Found<A> {
Exact(A),
Prefix,
impl<A: Action + Clone> Keymap<A> {
/// Parse `scope: chord [chord …] = action [arg]` entries, one per line or separated by `;`;
/// `#` starts a comment line. The action `none` unbinds. `scope: hint = action …` lists the
/// actions the scope offers as hints; `none` empties the list.
///
/// The first malformed entry, a binding written twice, or a binding that is
/// a strict prefix of another in its scope.
pub fn parse(text: &str) -> Result<Keymap<A>, ParseError> {
let mut keymap = Keymap {
scopes: HashMap::new(),
hints: HashMap::new(),
};
keymap.apply(text)?;
Ok(keymap)
/// This keymap with the bindings `text` writes replaced or unbound; same
/// grammar as [`Keymap::parse`].
/// As [`Keymap::parse`].
pub fn overridden(&self, text: &str) -> Result<Keymap<A>, ParseError> {
let mut keymap = self.clone();
fn apply(&mut self, text: &str) -> Result<(), ParseError> {
let mut written = HashSet::new();
for (number, entry) in entries(text) {
match parse_entry::<A>(number, entry)? {
Entry::Hints { scope, actions } => {
if !written.insert((scope.clone(), Vec::new())) {
let message = format!("duplicate hint list for `{scope}`");
return Err(ParseError::at(number, message));
self.hints.insert(scope, actions);
Entry::Bind {
scope,
chords,
action,
} => {
if !written.insert((scope.clone(), chords.clone())) {
let message = format!("duplicate binding `{scope}: {}`", show(&chords));
self.bind(number, scope, chords, action)?;
Ok(())
fn bind(
&mut self,
number: usize,
) -> Result<(), ParseError> {
let bindings = self.scopes.entry(scope).or_default();
bindings.retain(|binding| binding.chords != chords);
let Some(action) = action else {
return Ok(());
let clash = bindings
.iter()
.map(|binding| &binding.chords)
.find(|other| other.starts_with(&chords) || chords.starts_with(other));
if let Some(other) = clash {
let (short, long) = match other.len() < chords.len() {
true => (other, &chords),
false => (&chords, other),
let message = format!("`{}` is a prefix of `{}`", show(short), show(long));
bindings.push(Binding { chords, action });
/// The bindings of `scope` in file order: chords and action.
pub fn bindings(&self, scope: &str) -> impl Iterator<Item = (&[Chord], &A)> {
let bindings = self.scopes.get(scope).map_or(&[][..], Vec::as_slice);
bindings.iter().map(|b| (b.chords.as_slice(), &b.action))
/// The actions `scope` offers as hints, in the order its hint list gives.
#[must_use]
pub fn hinted(&self, scope: &str) -> &[A] {
self.hints.get(scope).map_or(&[], Vec::as_slice)
/// Resolve `key` against the scope `chain`, innermost first; the first scope
/// with a binding or a binding prefix for the typed chords wins. `text` says
/// whether an unbound printable character is typed text.
pub fn resolve(
&self,
chain: &[&str],
text: bool,
pending: &mut Pending,
key: KeyEvent,
) -> Resolved<A> {
if key.kind == KeyEventKind::Release {
return Resolved::Unbound;
let chord = Chord::from_event(key);
let typing = text && chord.is_printable();
if !pending.0.is_empty() && cancels(chord) {
pending.0.clear();
let continuing = !pending.0.is_empty();
pending.0.push(chord);
match self.find(chain, &pending.0) {
Some(Found::Exact(action)) => {
Resolved::Action(action)
Some(Found::Prefix) => Resolved::Pending,
None => {
match (continuing, typing, chord.code) {
(false, true, KeyCode::Char(c)) => Resolved::Text(c),
_ => Resolved::Unbound,
fn find(&self, chain: &[&str], typed: &[Chord]) -> Option<Found<A>> {
chain.iter().find_map(|scope| {
let bindings = self.scopes.get(*scope)?;
match bindings.iter().find(|binding| binding.chords == typed) {
Some(binding) => Some(Found::Exact(binding.action.clone())),
None => bindings
.any(|binding| binding.chords.starts_with(typed))
.then_some(Found::Prefix),
})
/// The 1-based line number and text of each entry of `text`.
fn entries(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.lines()
.enumerate()
.filter(|(_, line)| !line.trim_start().starts_with('#'))
.flat_map(|(index, line)| {
line.split(';')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(move |entry| (index + 1, entry))
/// An entry of a keymap text, split but not parsed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Written<'a> {
pub line: usize,
pub scope: &'a str,
pub chords: &'a str,
pub action: &'a str,
/// The well-shaped entries of `text`; a malformed one is left for [`Keymap::parse`] to report.
pub fn written_entries(text: &str) -> impl Iterator<Item = Written<'_>> {
entries(text).filter_map(|(line, entry)| {
let (scope, rest) = entry.split_once(':')?;
let (chords, action) = rest.split_once('=')?;
Some(Written {
line,
scope: scope.trim(),
chords: chords.trim(),
action: action.trim(),
/// Esc and C-g abandon a half-typed binding.
fn cancels(chord: Chord) -> bool {
let control_g = chord.code == KeyCode::Char('g') && chord.modifiers == KeyModifiers::CONTROL;
control_g || (chord.code == KeyCode::Esc && chord.modifiers.is_empty())
fn show(chords: &[Chord]) -> String {
let names: Vec<String> = chords.iter().map(Chord::to_string).collect();
names.join(" ")
fn parse_entry<A: Action>(number: usize, entry: &str) -> Result<Entry<A>, ParseError> {
let fail = |message: String| ParseError::at(number, message);
let shape = || fail("expected `scope: chord = action [arg]`".to_string());
let (scope, rest) = entry.split_once(':').ok_or_else(shape)?;
let (chords, action) = rest.split_once('=').ok_or_else(shape)?;
let scope = scope.trim();
if scope.is_empty() || scope.contains(char::is_whitespace) {
return Err(fail(format!("bad scope name `{scope}`")));
if chords.trim() == "hint" {
let actions = parse_hints(action).map_err(fail)?;
return Ok(Entry::Hints {
scope: scope.to_string(),
actions,
});
let chords = chords
.split_whitespace()
.map(str::parse::<Chord>)
.collect::<Result<Vec<_>, _>>()
.map_err(fail)?;
if chords.is_empty() {
return Err(fail("no chord before `=`".to_string()));
if chords.iter().skip(1).copied().any(cancels) {
return Err(fail(
"Esc and C-g cancel a sequence, so they cannot continue one".to_string(),
));
let mut words = action.split_whitespace();
let (name, arg) = (words.next().unwrap_or_default(), words.next());
if let Some(extra) = words.next() {
return Err(fail(format!("unexpected `{extra}` after the argument")));
let action = match (name, arg) {
("none", None) => None,
("none", Some(_)) => return Err(fail("`none` takes no argument".to_string())),
("", _) => return Err(fail("no action after `=`".to_string())),
(name, arg) => Some(A::parse(name, arg).map_err(fail)?),
Ok(Entry::Bind {
/// The actions of a hint list; they take no argument.
fn parse_hints<A: Action>(text: &str) -> Result<Vec<A>, String> {
let words: Vec<&str> = text.split_whitespace().collect();
match words.as_slice() {
[] => Err("no action after `=`".to_string()),
["none"] => Ok(Vec::new()),
_ => words.iter().map(|word| A::parse(word, None)).collect(),