keymap_file.rs

  1use anyhow::{Result, anyhow};
  2use collections::{BTreeMap, HashMap, IndexMap};
  3use fs::Fs;
  4use gpui::{
  5    Action, ActionBuildError, App, InvalidKeystrokeError, KEYSTROKE_PARSE_EXPECTED_MESSAGE,
  6    KeyBinding, KeyBindingContextPredicate, NoAction, SharedString,
  7};
  8use schemars::{
  9    JsonSchema,
 10    r#gen::{SchemaGenerator, SchemaSettings},
 11    schema::{ArrayValidation, InstanceType, Schema, SchemaObject, SubschemaValidation},
 12};
 13use serde::Deserialize;
 14use serde_json::Value;
 15use std::{any::TypeId, fmt::Write, rc::Rc, sync::Arc, sync::LazyLock};
 16use util::{asset_str, markdown::MarkdownString};
 17
 18use crate::{SettingsAssets, settings_store::parse_json_with_comments};
 19
 20pub trait KeyBindingValidator: Send + Sync {
 21    fn action_type_id(&self) -> TypeId;
 22    fn validate(&self, binding: &KeyBinding) -> Result<(), MarkdownString>;
 23}
 24
 25pub struct KeyBindingValidatorRegistration(pub fn() -> Box<dyn KeyBindingValidator>);
 26
 27inventory::collect!(KeyBindingValidatorRegistration);
 28
 29pub(crate) static KEY_BINDING_VALIDATORS: LazyLock<BTreeMap<TypeId, Box<dyn KeyBindingValidator>>> =
 30    LazyLock::new(|| {
 31        let mut validators = BTreeMap::new();
 32        for validator_registration in inventory::iter::<KeyBindingValidatorRegistration> {
 33            let validator = validator_registration.0();
 34            validators.insert(validator.action_type_id(), validator);
 35        }
 36        validators
 37    });
 38
 39// Note that the doc comments on these are shown by json-language-server when editing the keymap, so
 40// they should be considered user-facing documentation. Documentation is not handled well with
 41// schemars-0.8 - when there are newlines, it is rendered as plaintext (see
 42// https://github.com/GREsau/schemars/issues/38#issuecomment-2282883519). So for now these docs
 43// avoid newlines.
 44//
 45// TODO: Update to schemars-1.0 once it's released, and add more docs as newlines would be
 46// supported. Tracking issue is https://github.com/GREsau/schemars/issues/112.
 47
 48/// Keymap configuration consisting of sections. Each section may have a context predicate which
 49/// determines whether its bindings are used.
 50#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
 51#[serde(transparent)]
 52pub struct KeymapFile(Vec<KeymapSection>);
 53
 54/// Keymap section which binds keystrokes to actions.
 55#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
 56pub struct KeymapSection {
 57    /// Determines when these bindings are active. When just a name is provided, like `Editor` or
 58    /// `Workspace`, the bindings will be active in that context. Boolean expressions like `X && Y`,
 59    /// `X || Y`, `!X` are also supported. Some more complex logic including checking OS and the
 60    /// current file extension are also supported - see [the
 61    /// documentation](https://zed.dev/docs/key-bindings#contexts) for more details.
 62    #[serde(default)]
 63    context: String,
 64    /// This option enables specifying keys based on their position on a QWERTY keyboard, by using
 65    /// position-equivalent mappings for some non-QWERTY keyboards. This is currently only supported
 66    /// on macOS. See the documentation for more details.
 67    #[serde(default)]
 68    use_key_equivalents: bool,
 69    /// This keymap section's bindings, as a JSON object mapping keystrokes to actions. The
 70    /// keystrokes key is a string representing a sequence of keystrokes to type, where the
 71    /// keystrokes are separated by whitespace. Each keystroke is a sequence of modifiers (`ctrl`,
 72    /// `alt`, `shift`, `fn`, `cmd`, `super`, or `win`) followed by a key, separated by `-`. The
 73    /// order of bindings does matter. When the same keystrokes are bound at the same context depth,
 74    /// the binding that occurs later in the file is preferred. For displaying keystrokes in the UI,
 75    /// the later binding for the same action is preferred.
 76    #[serde(default)]
 77    bindings: Option<IndexMap<String, KeymapAction>>,
 78    #[serde(flatten)]
 79    unrecognized_fields: IndexMap<String, Value>,
 80    // This struct intentionally uses permissive types for its fields, rather than validating during
 81    // deserialization. The purpose of this is to allow loading the portion of the keymap that doesn't
 82    // have errors. The downside of this is that the errors are not reported with line+column info.
 83    // Unfortunately the implementations of the `Spanned` types for preserving this information are
 84    // highly inconvenient (`serde_spanned`) and in some cases don't work at all here
 85    // (`json_spanned_>value`). Serde should really have builtin support for this.
 86}
 87
 88impl KeymapSection {
 89    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = (&String, &KeymapAction)> {
 90        self.bindings.iter().flatten()
 91    }
 92}
 93
 94/// Keymap action as a JSON value, since it can either be null for no action, or the name of the
 95/// action, or an array of the name of the action and the action input.
 96///
 97/// Unlike the other json types involved in keymaps (including actions), this doc-comment will not
 98/// be included in the generated JSON schema, as it manually defines its `JsonSchema` impl. The
 99/// actual schema used for it is automatically generated in `KeymapFile::generate_json_schema`.
100#[derive(Debug, Deserialize, Default, Clone)]
101#[serde(transparent)]
102pub struct KeymapAction(Value);
103
104impl std::fmt::Display for KeymapAction {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        match &self.0 {
107            Value::String(s) => write!(f, "{}", s),
108            Value::Array(arr) => {
109                let strings: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
110                write!(f, "{}", strings.join(", "))
111            }
112            _ => write!(f, "{}", self.0),
113        }
114    }
115}
116
117impl JsonSchema for KeymapAction {
118    /// This is used when generating the JSON schema for the `KeymapAction` type, so that it can
119    /// reference the keymap action schema.
120    fn schema_name() -> String {
121        "KeymapAction".into()
122    }
123
124    /// This schema will be replaced with the full action schema in
125    /// `KeymapFile::generate_json_schema`.
126    fn json_schema(_: &mut SchemaGenerator) -> Schema {
127        Schema::Bool(true)
128    }
129}
130
131#[derive(Debug)]
132#[must_use]
133pub enum KeymapFileLoadResult {
134    Success {
135        key_bindings: Vec<KeyBinding>,
136    },
137    SomeFailedToLoad {
138        key_bindings: Vec<KeyBinding>,
139        error_message: MarkdownString,
140    },
141    JsonParseFailure {
142        error: anyhow::Error,
143    },
144}
145
146impl KeymapFile {
147    pub fn parse(content: &str) -> anyhow::Result<Self> {
148        parse_json_with_comments::<Self>(content)
149    }
150
151    pub fn load_asset(asset_path: &str, cx: &App) -> anyhow::Result<Vec<KeyBinding>> {
152        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
153            KeymapFileLoadResult::Success { key_bindings } => Ok(key_bindings),
154            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => Err(anyhow!(
155                "Error loading built-in keymap \"{asset_path}\": {error_message}"
156            )),
157            KeymapFileLoadResult::JsonParseFailure { error } => Err(anyhow!(
158                "JSON parse error in built-in keymap \"{asset_path}\": {error}"
159            )),
160        }
161    }
162
163    #[cfg(feature = "test-support")]
164    pub fn load_asset_allow_partial_failure(
165        asset_path: &str,
166        cx: &App,
167    ) -> anyhow::Result<Vec<KeyBinding>> {
168        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
169            KeymapFileLoadResult::SomeFailedToLoad {
170                key_bindings,
171                error_message,
172                ..
173            } if key_bindings.is_empty() => Err(anyhow!(
174                "Error loading built-in keymap \"{asset_path}\": {error_message}"
175            )),
176            KeymapFileLoadResult::Success { key_bindings, .. }
177            | KeymapFileLoadResult::SomeFailedToLoad { key_bindings, .. } => Ok(key_bindings),
178            KeymapFileLoadResult::JsonParseFailure { error } => Err(anyhow!(
179                "JSON parse error in built-in keymap \"{asset_path}\": {error}"
180            )),
181        }
182    }
183
184    #[cfg(feature = "test-support")]
185    pub fn load_panic_on_failure(content: &str, cx: &App) -> Vec<KeyBinding> {
186        match Self::load(content, cx) {
187            KeymapFileLoadResult::Success { key_bindings, .. } => key_bindings,
188            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => {
189                panic!("{error_message}");
190            }
191            KeymapFileLoadResult::JsonParseFailure { error } => {
192                panic!("JSON parse error: {error}");
193            }
194        }
195    }
196
197    pub fn load(content: &str, cx: &App) -> KeymapFileLoadResult {
198        let key_equivalents = crate::key_equivalents::get_key_equivalents(&cx.keyboard_layout());
199
200        if content.is_empty() {
201            return KeymapFileLoadResult::Success {
202                key_bindings: Vec::new(),
203            };
204        }
205        let keymap_file = match parse_json_with_comments::<Self>(content) {
206            Ok(keymap_file) => keymap_file,
207            Err(error) => {
208                return KeymapFileLoadResult::JsonParseFailure { error };
209            }
210        };
211
212        // Accumulate errors in order to support partial load of user keymap in the presence of
213        // errors in context and binding parsing.
214        let mut errors = Vec::new();
215        let mut key_bindings = Vec::new();
216
217        for KeymapSection {
218            context,
219            use_key_equivalents,
220            bindings,
221            unrecognized_fields,
222        } in keymap_file.0.iter()
223        {
224            let context_predicate: Option<Rc<KeyBindingContextPredicate>> = if context.is_empty() {
225                None
226            } else {
227                match KeyBindingContextPredicate::parse(context) {
228                    Ok(context_predicate) => Some(context_predicate.into()),
229                    Err(err) => {
230                        // Leading space is to separate from the message indicating which section
231                        // the error occurred in.
232                        errors.push((
233                            context,
234                            format!(" Parse error in section `context` field: {}", err),
235                        ));
236                        continue;
237                    }
238                }
239            };
240
241            let key_equivalents = if *use_key_equivalents {
242                key_equivalents.as_ref()
243            } else {
244                None
245            };
246
247            let mut section_errors = String::new();
248
249            if !unrecognized_fields.is_empty() {
250                write!(
251                    section_errors,
252                    "\n\n - Unrecognized fields: {}",
253                    MarkdownString::inline_code(&format!("{:?}", unrecognized_fields.keys()))
254                )
255                .unwrap();
256            }
257
258            if let Some(bindings) = bindings {
259                for (keystrokes, action) in bindings {
260                    let result = Self::load_keybinding(
261                        keystrokes,
262                        action,
263                        context_predicate.clone(),
264                        key_equivalents,
265                        cx,
266                    );
267                    match result {
268                        Ok(key_binding) => {
269                            key_bindings.push(key_binding);
270                        }
271                        Err(err) => {
272                            let mut lines = err.lines();
273                            let mut indented_err = lines.next().unwrap().to_string();
274                            for line in lines {
275                                indented_err.push_str("  ");
276                                indented_err.push_str(line);
277                                indented_err.push_str("\n");
278                            }
279                            write!(
280                                section_errors,
281                                "\n\n- In binding {}, {indented_err}",
282                                inline_code_string(keystrokes),
283                            )
284                            .unwrap();
285                        }
286                    }
287                }
288            }
289
290            if !section_errors.is_empty() {
291                errors.push((context, section_errors))
292            }
293        }
294
295        if errors.is_empty() {
296            KeymapFileLoadResult::Success { key_bindings }
297        } else {
298            let mut error_message = "Errors in user keymap file.\n".to_owned();
299            for (context, section_errors) in errors {
300                if context.is_empty() {
301                    write!(error_message, "\n\nIn section without context predicate:").unwrap()
302                } else {
303                    write!(
304                        error_message,
305                        "\n\nIn section with {}:",
306                        MarkdownString::inline_code(&format!("context = \"{}\"", context))
307                    )
308                    .unwrap()
309                }
310                write!(error_message, "{section_errors}").unwrap();
311            }
312            KeymapFileLoadResult::SomeFailedToLoad {
313                key_bindings,
314                error_message: MarkdownString(error_message),
315            }
316        }
317    }
318
319    fn load_keybinding(
320        keystrokes: &str,
321        action: &KeymapAction,
322        context: Option<Rc<KeyBindingContextPredicate>>,
323        key_equivalents: Option<&HashMap<char, char>>,
324        cx: &App,
325    ) -> std::result::Result<KeyBinding, String> {
326        let (build_result, action_input_string) = match &action.0 {
327            Value::Array(items) => {
328                if items.len() != 2 {
329                    return Err(format!(
330                        "expected two-element array of `[name, input]`. \
331                        Instead found {}.",
332                        MarkdownString::inline_code(&action.0.to_string())
333                    ));
334                }
335                let serde_json::Value::String(ref name) = items[0] else {
336                    return Err(format!(
337                        "expected two-element array of `[name, input]`, \
338                        but the first element is not a string in {}.",
339                        MarkdownString::inline_code(&action.0.to_string())
340                    ));
341                };
342                let action_input = items[1].clone();
343                let action_input_string = action_input.to_string();
344                (
345                    cx.build_action(&name, Some(action_input)),
346                    Some(action_input_string),
347                )
348            }
349            Value::String(name) => (cx.build_action(&name, None), None),
350            Value::Null => (Ok(NoAction.boxed_clone()), None),
351            _ => {
352                return Err(format!(
353                    "expected two-element array of `[name, input]`. \
354                    Instead found {}.",
355                    MarkdownString::inline_code(&action.0.to_string())
356                ));
357            }
358        };
359
360        let action = match build_result {
361            Ok(action) => action,
362            Err(ActionBuildError::NotFound { name }) => {
363                return Err(format!(
364                    "didn't find an action named {}.",
365                    inline_code_string(&name)
366                ));
367            }
368            Err(ActionBuildError::BuildError { name, error }) => match action_input_string {
369                Some(action_input_string) => {
370                    return Err(format!(
371                        "can't build {} action from input value {}: {}",
372                        inline_code_string(&name),
373                        MarkdownString::inline_code(&action_input_string),
374                        MarkdownString::escape(&error.to_string())
375                    ));
376                }
377                None => {
378                    return Err(format!(
379                        "can't build {} action - it requires input data via [name, input]: {}",
380                        inline_code_string(&name),
381                        MarkdownString::escape(&error.to_string())
382                    ));
383                }
384            },
385        };
386
387        let key_binding = match KeyBinding::load(keystrokes, action, context, key_equivalents) {
388            Ok(key_binding) => key_binding,
389            Err(InvalidKeystrokeError { keystroke }) => {
390                return Err(format!(
391                    "invalid keystroke {}. {}",
392                    inline_code_string(&keystroke),
393                    KEYSTROKE_PARSE_EXPECTED_MESSAGE
394                ));
395            }
396        };
397
398        if let Some(validator) = KEY_BINDING_VALIDATORS.get(&key_binding.action().type_id()) {
399            match validator.validate(&key_binding) {
400                Ok(()) => Ok(key_binding),
401                Err(error) => Err(error.0),
402            }
403        } else {
404            Ok(key_binding)
405        }
406    }
407
408    pub fn generate_json_schema_for_registered_actions(cx: &mut App) -> Value {
409        let mut generator = SchemaSettings::draft07()
410            .with(|settings| settings.option_add_null_type = false)
411            .into_generator();
412
413        let action_schemas = cx.action_schemas(&mut generator);
414        let deprecations = cx.action_deprecations();
415        KeymapFile::generate_json_schema(generator, action_schemas, deprecations)
416    }
417
418    fn generate_json_schema(
419        generator: SchemaGenerator,
420        action_schemas: Vec<(SharedString, Option<Schema>)>,
421        deprecations: &HashMap<SharedString, SharedString>,
422    ) -> serde_json::Value {
423        fn set<I, O>(input: I) -> Option<O>
424        where
425            I: Into<O>,
426        {
427            Some(input.into())
428        }
429
430        fn add_deprecation(schema_object: &mut SchemaObject, message: String) {
431            schema_object.extensions.insert(
432                // deprecationMessage is not part of the JSON Schema spec,
433                // but json-language-server recognizes it.
434                "deprecationMessage".to_owned(),
435                Value::String(message),
436            );
437        }
438
439        fn add_deprecation_preferred_name(schema_object: &mut SchemaObject, new_name: &str) {
440            add_deprecation(schema_object, format!("Deprecated, use {new_name}"));
441        }
442
443        fn add_description(schema_object: &mut SchemaObject, description: String) {
444            schema_object
445                .metadata
446                .get_or_insert(Default::default())
447                .description = Some(description);
448        }
449
450        let empty_object: SchemaObject = SchemaObject {
451            instance_type: set(InstanceType::Object),
452            ..Default::default()
453        };
454
455        // This is a workaround for a json-language-server issue where it matches the first
456        // alternative that matches the value's shape and uses that for documentation.
457        //
458        // In the case of the array validations, it would even provide an error saying that the name
459        // must match the name of the first alternative.
460        let mut plain_action = SchemaObject {
461            instance_type: set(InstanceType::String),
462            const_value: Some(Value::String("".to_owned())),
463            ..Default::default()
464        };
465        let no_action_message = "No action named this.";
466        add_description(&mut plain_action, no_action_message.to_owned());
467        add_deprecation(&mut plain_action, no_action_message.to_owned());
468        let mut matches_action_name = SchemaObject {
469            const_value: Some(Value::String("".to_owned())),
470            ..Default::default()
471        };
472        let no_action_message = "No action named this that takes input.";
473        add_description(&mut matches_action_name, no_action_message.to_owned());
474        add_deprecation(&mut matches_action_name, no_action_message.to_owned());
475        let action_with_input = SchemaObject {
476            instance_type: set(InstanceType::Array),
477            array: set(ArrayValidation {
478                items: set(vec![
479                    matches_action_name.into(),
480                    // Accept any value, as we want this to be the preferred match when there is a
481                    // typo in the name.
482                    Schema::Bool(true),
483                ]),
484                min_items: Some(2),
485                max_items: Some(2),
486                ..Default::default()
487            }),
488            ..Default::default()
489        };
490        let mut keymap_action_alternatives = vec![plain_action.into(), action_with_input.into()];
491
492        for (name, action_schema) in action_schemas.iter() {
493            let schema = if let Some(Schema::Object(schema)) = action_schema {
494                Some(schema.clone())
495            } else {
496                None
497            };
498
499            let description = schema.as_ref().and_then(|schema| {
500                schema
501                    .metadata
502                    .as_ref()
503                    .and_then(|metadata| metadata.description.clone())
504            });
505
506            let deprecation = if name == NoAction.name() {
507                Some("null")
508            } else {
509                deprecations.get(name).map(|new_name| new_name.as_ref())
510            };
511
512            // Add an alternative for plain action names.
513            let mut plain_action = SchemaObject {
514                instance_type: set(InstanceType::String),
515                const_value: Some(Value::String(name.to_string())),
516                ..Default::default()
517            };
518            if let Some(new_name) = deprecation {
519                add_deprecation_preferred_name(&mut plain_action, new_name);
520            }
521            if let Some(description) = description.clone() {
522                add_description(&mut plain_action, description);
523            }
524            keymap_action_alternatives.push(plain_action.into());
525
526            // Add an alternative for actions with data specified as a [name, data] array.
527            //
528            // When a struct with no deserializable fields is added with impl_actions! /
529            // impl_actions_as! an empty object schema is produced. The action should be invoked
530            // without data in this case.
531            if let Some(schema) = schema {
532                if schema != empty_object {
533                    let mut matches_action_name = SchemaObject {
534                        const_value: Some(Value::String(name.to_string())),
535                        ..Default::default()
536                    };
537                    if let Some(description) = description.clone() {
538                        add_description(&mut matches_action_name, description.to_string());
539                    }
540                    if let Some(new_name) = deprecation {
541                        add_deprecation_preferred_name(&mut matches_action_name, new_name);
542                    }
543                    let action_with_input = SchemaObject {
544                        instance_type: set(InstanceType::Array),
545                        array: set(ArrayValidation {
546                            items: set(vec![matches_action_name.into(), schema.into()]),
547                            min_items: Some(2),
548                            max_items: Some(2),
549                            ..Default::default()
550                        }),
551                        ..Default::default()
552                    };
553                    keymap_action_alternatives.push(action_with_input.into());
554                }
555            }
556        }
557
558        // Placing null first causes json-language-server to default assuming actions should be
559        // null, so place it last.
560        keymap_action_alternatives.push(
561            SchemaObject {
562                instance_type: set(InstanceType::Null),
563                ..Default::default()
564            }
565            .into(),
566        );
567
568        let action_schema = SchemaObject {
569            subschemas: set(SubschemaValidation {
570                one_of: Some(keymap_action_alternatives),
571                ..Default::default()
572            }),
573            ..Default::default()
574        }
575        .into();
576
577        // The `KeymapSection` schema will reference the `KeymapAction` schema by name, so replacing
578        // the definition of `KeymapAction` results in the full action schema being used.
579        let mut root_schema = generator.into_root_schema_for::<KeymapFile>();
580        root_schema
581            .definitions
582            .insert(KeymapAction::schema_name(), action_schema);
583
584        // This and other json schemas can be viewed via `debug: open language server logs` ->
585        // `json-language-server` -> `Server Info`.
586        serde_json::to_value(root_schema).unwrap()
587    }
588
589    pub fn sections(&self) -> impl DoubleEndedIterator<Item = &KeymapSection> {
590        self.0.iter()
591    }
592
593    pub async fn load_keymap_file(fs: &Arc<dyn Fs>) -> Result<String> {
594        match fs.load(paths::keymap_file()).await {
595            result @ Ok(_) => result,
596            Err(err) => {
597                if let Some(e) = err.downcast_ref::<std::io::Error>() {
598                    if e.kind() == std::io::ErrorKind::NotFound {
599                        return Ok(crate::initial_keymap_content().to_string());
600                    }
601                }
602                Err(err)
603            }
604        }
605    }
606}
607
608// Double quotes a string and wraps it in backticks for markdown inline code..
609fn inline_code_string(text: &str) -> MarkdownString {
610    MarkdownString::inline_code(&format!("\"{}\"", text))
611}
612
613#[cfg(test)]
614mod tests {
615    use crate::KeymapFile;
616
617    #[test]
618    fn can_deserialize_keymap_with_trailing_comma() {
619        let json = indoc::indoc! {"[
620              // Standard macOS bindings
621              {
622                \"bindings\": {
623                  \"up\": \"menu::SelectPrevious\",
624                },
625              },
626            ]
627                  "
628        };
629        KeymapFile::parse(json).unwrap();
630    }
631}