Lines
98.52 %
Functions
84.62 %
Branches
100 %
//! Key-event translation: crossterm [`KeyEvent`] → [`Intent`], through the
//! preset keymap and the scope chain `scopes::chain` builds from focus.
use crate::app::{App, button_of_key};
use crate::event::{Intent, apply};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use scopes::{SCOPES, Scopes, in_typing_chain};
use std::time::Instant;
use tvui::keymap::{Chord, Keymap, Pending, Resolved, Written, written_entries};
mod help;
mod scopes;
mod shown;
pub use help::{help_lines, help_topic};
pub use shown::{
Hint, KeyView, here, hinted, in_form, in_modal, in_rows, in_view, in_view_all, in_window,
};
/// A keymap file: its name for error messages and its text.
type Layer<'a> = (&'a str, &'a str);
const BASE: Layer<'static> = ("base.keys", include_str!("keymap/base.keys"));
const EMACS: Layer<'static> = ("emacs.keys", include_str!("keymap/emacs.keys"));
const CUA: Layer<'static> = ("cua.keys", include_str!("keymap/cua.keys"));
const VIM: Layer<'static> = ("vim.keys", include_str!("keymap/vim.keys"));
/// A preset: the layers it is built from, each over the previous, and its vim state.
struct Preset {
name: &'static str,
layers: &'static [Layer<'static>],
vim: VimState,
}
/// The preset used when neither the command line nor the config names one.
pub const DEFAULT_KEYMAP: &str = "cua";
const PRESETS: &[Preset] = &[
Preset {
name: "cua",
layers: &[BASE, CUA],
vim: VimState::Off,
},
name: "emacs",
layers: &[BASE, EMACS],
name: "vim",
layers: &[BASE, EMACS, VIM],
vim: VimState::Insert,
];
/// Where the vim preset is: typing or normal mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VimState {
/// The preset has no vim state.
Off,
Normal,
Insert,
/// The preset keymap, the chords typed so far and the vim state.
pub struct Keys {
map: Keymap<Intent>,
pending: Pending,
chain: Vec<&'static str>,
/// What a user override may not bind: a printable key, which would stop typing.
fn bound_printable(entry: &Written<'_>, user: bool) -> bool {
let first = entry.chords.split_whitespace().next();
let printable = first.and_then(|chord| chord.parse::<Chord>().ok());
entry.action != "none"
&& printable.is_some_and(Chord::is_printable)
&& (entry.scope == "global" || (user && in_typing_chain(entry.scope)))
/// # Errors
/// The first entry of `text` binding an unknown scope, or a printable key where it would stop
/// typing: always in `global`, and for a `user` override in any scope that types text.
fn check_scopes(text: &str, user: bool) -> Result<(), String> {
for entry in written_entries(text) {
let Written { line, scope, .. } = entry;
if !SCOPES.iter().any(|known| known.name == scope) {
return Err(format!("line {line}: unknown scope `{scope}`"));
if bound_printable(&entry, user) {
let key = entry.chords;
return Err(format!(
"line {line}: `{scope}` cannot bind the printable key `{key}`"
));
Ok(())
/// `text` over `lower`, or alone for the first layer.
fn read_layer(
lower: Option<&Keymap<Intent>>,
(file, text): &Layer<'_>,
user: bool,
) -> Result<Keymap<Intent>, String> {
check_scopes(text, user).map_err(|err| format!("{file}: {err}"))?;
let read = match lower {
Some(lower) => lower.overridden(text),
None => Keymap::parse(text),
read.map_err(|err| format!("{file}: {err}"))
impl Keys {
/// Whether `other` is the same preset binding the same keys, whatever the typing state.
#[must_use]
pub fn same_bindings(&self, other: &Keys) -> bool {
self.name == other.name && self.map == other.map
/// The names of the built-in keymaps.
pub fn preset_names() -> impl Iterator<Item = &'static str> {
PRESETS.iter().map(|preset| preset.name)
/// The message for an unknown preset or one that does not parse.
pub fn preset(name: &str) -> Result<Keys, String> {
let Some(preset) = PRESETS.iter().find(|preset| preset.name == name) else {
let known: Vec<_> = PRESETS.iter().map(|preset| preset.name).collect();
"unknown keymap `{name}`; known: {}",
known.join(", ")
Keys::layered(preset.name, preset.vim, preset.layers)
.map_err(|err| format!("{name} keymap: {err}"))
/// These keys with the entries of `text` rebound or unbound.
///
/// The message for an entry that does not parse, names an unknown scope or binds a
/// printable key where it would stop typing.
pub fn overridden(&self, text: &str) -> Result<Keys, String> {
let map = read_layer(Some(&self.map), &("overrides", text), true)?;
Ok(Keys {
name: self.name,
map,
pending: Pending::default(),
chain: Vec::new(),
vim: self.vim,
})
fn layered(name: &'static str, vim: VimState, layers: &[Layer<'_>]) -> Result<Keys, String> {
let mut map = None;
for layer in layers {
map = Some(read_layer(map.as_ref(), layer, false)?);
name,
map: map.ok_or("no layers")?,
vim,
pub fn vim(&self) -> VimState {
self.vim
/// Switch the vim state; the emacs preset has none.
pub fn set_vim(&mut self, state: VimState) {
if self.vim != VimState::Off {
self.vim = state;
/// Whether the last key was resolved in a vim mode scope.
fn in_vim_scope(&self) -> bool {
self.chain
.first()
.is_some_and(|scope| scope.starts_with("vim-"))
pub fn indicator(&self) -> &'static str {
match self.vim {
VimState::Off => self.name,
VimState::Normal => "vim:normal",
VimState::Insert => "vim:insert",
/// A half-typed binding does not survive a move to other scopes.
fn resolve(&mut self, scopes: Scopes, key: KeyEvent) -> Resolved<Intent> {
if self.chain != scopes.names {
self.pending = Pending::default();
self.chain = scopes.names;
match self
.map
.resolve(&self.chain, scopes.text, &mut self.pending, key)
{
Resolved::Text(c) => Resolved::Action(Intent::InsertChar(c)),
other => other,
/// Chooses the open menu's entry the typed `key` names, if any.
fn choose_by_mnemonic(app: &mut App, key: KeyEvent) {
if let Some(at) = app.menu_mnemonic(key) {
app.select_menu_item(at);
apply(app, Intent::MenuSelect);
/// Applies `intent` of `key`, a button's press by a key first being drawn down.
fn act(app: &mut App, key: KeyEvent, intent: Intent) {
match button_of_key(app, key, intent) {
Some((index, spec)) => app.hold_button_by_key(index, spec, Instant::now()),
None => apply(app, intent),
fn run(app: &mut App, key: KeyEvent) -> Resolved<Intent> {
app.flush_key_press();
app.cancel_press();
let scopes = scopes::chain(app);
let resolved = app.keys.resolve(scopes, key);
match &resolved {
Resolved::Action(intent) => act(app, key, *intent),
Resolved::Unbound if app.menu.is_some() => choose_by_mnemonic(app, key),
_ => {}
resolved
/// Translate the key and apply it. Over SSH an Esc followed within 40 ms by a
/// key arrives as `M-key`; where vim binds Esc, an unbound `M-key` is both.
pub fn handle_key(app: &mut App, key: KeyEvent) {
if run(app, key) != Resolved::Unbound {
return;
let vim_focus = app.keys.in_vim_scope();
let split = matches!(key.code, KeyCode::Char(_) | KeyCode::Enter)
&& key.modifiers.contains(KeyModifiers::ALT);
if vim_focus && split {
run(app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
run(
app,
KeyEvent::new(key.code, key.modifiers - KeyModifiers::ALT),
);
#[cfg(test)]
mod arrow_tests;
mod builder_tests;
mod button_hold_tests;
mod button_tests;
mod confirm_tests;
mod console_tests;
mod cua_tests;
mod cursor_tests;
mod field_tests;
mod form_hints_tests;
mod grid_edit_tests;
mod help_tests;
mod hints_tests;
mod list_page_tests;
mod menu_tests;
mod preset_tests;
mod tab_tests;
mod tests;
mod vim_list_tests;
mod vim_tests;