Load all key bindings that parse and use markdown in error notifications (#23113)

* Collects and reports all parse errors

* Shares parsed `KeyBindingContextPredicate` among the actions.

* Updates gpui keybinding and action parsing to return structured
errors.

* Renames "block" to "section" to match the docs, as types like
`KeymapSection` are shown in `json-language-server` hovers.

* Removes wrapping of `context` and `use_key_equivalents` fields so that
`json-language-server` auto-inserts `""` and `false` instead of `null`.

* Updates `add_to_cx` to take `&self`, so that the user keymap doesn't
get unnecessarily cloned.

In retrospect I wish I'd just switched to using TreeSitter to do the
parsing and provide proper diagnostics. This is tracked in #23333

Release Notes:

- Improved handling of errors within the user keymap file. Parse errors
within context, keystrokes, or actions no longer prevent loading the key
bindings that do parse.
This commit is contained in:
Michael Sloan 2025-01-18 15:27:08 -07:00 committed by GitHub
parent c929533e00
commit 711dc21eb2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 552 additions and 196 deletions

View file

@ -1,14 +1,15 @@
use std::rc::Rc;
use collections::HashMap;
use crate::{Action, KeyBindingContextPredicate, Keystroke};
use anyhow::Result;
use crate::{Action, InvalidKeystrokeError, KeyBindingContextPredicate, Keystroke};
use smallvec::SmallVec;
/// A keybinding and its associated metadata, from the keymap.
pub struct KeyBinding {
pub(crate) action: Box<dyn Action>,
pub(crate) keystrokes: SmallVec<[Keystroke; 2]>,
pub(crate) context_predicate: Option<KeyBindingContextPredicate>,
pub(crate) context_predicate: Option<Rc<KeyBindingContextPredicate>>,
}
impl Clone for KeyBinding {
@ -22,8 +23,13 @@ impl Clone for KeyBinding {
}
impl KeyBinding {
/// Construct a new keybinding from the given data.
pub fn new<A: Action>(keystrokes: &str, action: A, context_predicate: Option<&str>) -> Self {
/// Construct a new keybinding from the given data. Panics on parse error.
pub fn new<A: Action>(keystrokes: &str, action: A, context: Option<&str>) -> Self {
let context_predicate = if let Some(context) = context {
Some(KeyBindingContextPredicate::parse(context).unwrap().into())
} else {
None
};
Self::load(keystrokes, Box::new(action), context_predicate, None).unwrap()
}
@ -31,19 +37,13 @@ impl KeyBinding {
pub fn load(
keystrokes: &str,
action: Box<dyn Action>,
context: Option<&str>,
context_predicate: Option<Rc<KeyBindingContextPredicate>>,
key_equivalents: Option<&HashMap<char, char>>,
) -> Result<Self> {
let context = if let Some(context) = context {
Some(KeyBindingContextPredicate::parse(context)?)
} else {
None
};
) -> std::result::Result<Self, InvalidKeystrokeError> {
let mut keystrokes: SmallVec<[Keystroke; 2]> = keystrokes
.split_whitespace()
.map(Keystroke::parse)
.collect::<Result<_>>()?;
.collect::<std::result::Result<_, _>>()?;
if let Some(equivalents) = key_equivalents {
for keystroke in keystrokes.iter_mut() {
@ -58,7 +58,7 @@ impl KeyBinding {
Ok(Self {
keystrokes,
action,
context_predicate: context,
context_predicate,
})
}
@ -88,8 +88,8 @@ impl KeyBinding {
}
/// Get the predicate used to match this binding
pub fn predicate(&self) -> Option<&KeyBindingContextPredicate> {
self.context_predicate.as_ref()
pub fn predicate(&self) -> Option<Rc<KeyBindingContextPredicate>> {
self.context_predicate.as_ref().map(|rc| rc.clone())
}
}

View file

@ -244,7 +244,7 @@ impl KeyBindingContextPredicate {
let source = skip_whitespace(source);
let (predicate, rest) = Self::parse_expr(source, 0)?;
if let Some(next) = rest.chars().next() {
Err(anyhow!("unexpected character {next:?}"))
Err(anyhow!("unexpected character '{next:?}'"))
} else {
Ok(predicate)
}
@ -333,7 +333,7 @@ impl KeyBindingContextPredicate {
let next = source
.chars()
.next()
.ok_or_else(|| anyhow!("unexpected eof"))?;
.ok_or_else(|| anyhow!("unexpected end"))?;
match next {
'(' => {
source = skip_whitespace(&source[1..]);
@ -369,7 +369,7 @@ impl KeyBindingContextPredicate {
source,
))
}
_ => Err(anyhow!("unexpected character {next:?}")),
_ => Err(anyhow!("unexpected character '{next:?}'")),
}
}
@ -389,7 +389,7 @@ impl KeyBindingContextPredicate {
if let (Self::Identifier(left), Self::Identifier(right)) = (self, other) {
Ok(Self::Equal(left, right))
} else {
Err(anyhow!("operands must be identifiers"))
Err(anyhow!("operands of == must be identifiers"))
}
}
@ -397,7 +397,7 @@ impl KeyBindingContextPredicate {
if let (Self::Identifier(left), Self::Identifier(right)) = (self, other) {
Ok(Self::NotEqual(left, right))
} else {
Err(anyhow!("operands must be identifiers"))
Err(anyhow!("operands of != must be identifiers"))
}
}
}
@ -504,7 +504,7 @@ mod tests {
KeyBindingContextPredicate::parse("c == !d")
.unwrap_err()
.to_string(),
"operands must be identifiers"
"operands of == must be identifiers"
);
}