keymap_file.rs

   1use anyhow::{Context as _, Result};
   2use collections::{BTreeMap, HashMap, IndexMap};
   3use fs::Fs;
   4use gpui::{
   5    Action, ActionBuildError, App, InvalidKeystrokeError, KEYSTROKE_PARSE_EXPECTED_MESSAGE,
   6    KeyBinding, KeyBindingContextPredicate, KeyBindingMetaIndex, KeybindingKeystroke, Keystroke,
   7    NoAction, SharedString, register_action,
   8};
   9use schemars::{JsonSchema, json_schema};
  10use serde::Deserialize;
  11use serde_json::{Value, json};
  12use std::borrow::Cow;
  13use std::{any::TypeId, fmt::Write, rc::Rc, sync::Arc, sync::LazyLock};
  14use util::ResultExt as _;
  15use util::{
  16    asset_str,
  17    markdown::{MarkdownEscaped, MarkdownInlineCode, MarkdownString},
  18};
  19
  20use crate::{
  21    SettingsAssets, append_top_level_array_value_in_json_text, parse_json_with_comments,
  22    replace_top_level_array_value_in_json_text,
  23};
  24
  25pub trait KeyBindingValidator: Send + Sync {
  26    fn action_type_id(&self) -> TypeId;
  27    fn validate(&self, binding: &KeyBinding) -> Result<(), MarkdownString>;
  28}
  29
  30pub struct KeyBindingValidatorRegistration(pub fn() -> Box<dyn KeyBindingValidator>);
  31
  32inventory::collect!(KeyBindingValidatorRegistration);
  33
  34pub(crate) static KEY_BINDING_VALIDATORS: LazyLock<BTreeMap<TypeId, Box<dyn KeyBindingValidator>>> =
  35    LazyLock::new(|| {
  36        let mut validators = BTreeMap::new();
  37        for validator_registration in inventory::iter::<KeyBindingValidatorRegistration> {
  38            let validator = validator_registration.0();
  39            validators.insert(validator.action_type_id(), validator);
  40        }
  41        validators
  42    });
  43
  44// Note that the doc comments on these are shown by json-language-server when editing the keymap, so
  45// they should be considered user-facing documentation. Documentation is not handled well with
  46// schemars-0.8 - when there are newlines, it is rendered as plaintext (see
  47// https://github.com/GREsau/schemars/issues/38#issuecomment-2282883519). So for now these docs
  48// avoid newlines.
  49//
  50// TODO: Update to schemars-1.0 once it's released, and add more docs as newlines would be
  51// supported. Tracking issue is https://github.com/GREsau/schemars/issues/112.
  52
  53/// Keymap configuration consisting of sections. Each section may have a context predicate which
  54/// determines whether its bindings are used.
  55#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
  56#[serde(transparent)]
  57pub struct KeymapFile(Vec<KeymapSection>);
  58
  59/// Keymap section which binds keystrokes to actions.
  60#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
  61pub struct KeymapSection {
  62    /// Determines when these bindings are active. When just a name is provided, like `Editor` or
  63    /// `Workspace`, the bindings will be active in that context. Boolean expressions like `X && Y`,
  64    /// `X || Y`, `!X` are also supported. Some more complex logic including checking OS and the
  65    /// current file extension are also supported - see [the
  66    /// documentation](https://zed.dev/docs/key-bindings#contexts) for more details.
  67    #[serde(default)]
  68    pub context: String,
  69    /// This option enables specifying keys based on their position on a QWERTY keyboard, by using
  70    /// position-equivalent mappings for some non-QWERTY keyboards. This is currently only supported
  71    /// on macOS. See the documentation for more details.
  72    #[serde(default)]
  73    use_key_equivalents: bool,
  74    /// This keymap section's bindings, as a JSON object mapping keystrokes to actions. The
  75    /// keystrokes key is a string representing a sequence of keystrokes to type, where the
  76    /// keystrokes are separated by whitespace. Each keystroke is a sequence of modifiers (`ctrl`,
  77    /// `alt`, `shift`, `fn`, `cmd`, `super`, or `win`) followed by a key, separated by `-`. The
  78    /// order of bindings does matter. When the same keystrokes are bound at the same context depth,
  79    /// the binding that occurs later in the file is preferred. For displaying keystrokes in the UI,
  80    /// the later binding for the same action is preferred.
  81    #[serde(default)]
  82    bindings: Option<IndexMap<String, KeymapAction>>,
  83    #[serde(flatten)]
  84    unrecognized_fields: IndexMap<String, Value>,
  85    // This struct intentionally uses permissive types for its fields, rather than validating during
  86    // deserialization. The purpose of this is to allow loading the portion of the keymap that doesn't
  87    // have errors. The downside of this is that the errors are not reported with line+column info.
  88    // Unfortunately the implementations of the `Spanned` types for preserving this information are
  89    // highly inconvenient (`serde_spanned`) and in some cases don't work at all here
  90    // (`json_spanned_>value`). Serde should really have builtin support for this.
  91}
  92
  93impl KeymapSection {
  94    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = (&String, &KeymapAction)> {
  95        self.bindings.iter().flatten()
  96    }
  97}
  98
  99/// Keymap action as a JSON value, since it can either be null for no action, or the name of the
 100/// action, or an array of the name of the action and the action input.
 101///
 102/// Unlike the other json types involved in keymaps (including actions), this doc-comment will not
 103/// be included in the generated JSON schema, as it manually defines its `JsonSchema` impl. The
 104/// actual schema used for it is automatically generated in `KeymapFile::generate_json_schema`.
 105#[derive(Debug, Deserialize, Default, Clone)]
 106#[serde(transparent)]
 107pub struct KeymapAction(Value);
 108
 109impl std::fmt::Display for KeymapAction {
 110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 111        match &self.0 {
 112            Value::String(s) => write!(f, "{}", s),
 113            Value::Array(arr) => {
 114                let strings: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
 115                write!(f, "{}", strings.join(", "))
 116            }
 117            _ => write!(f, "{}", self.0),
 118        }
 119    }
 120}
 121
 122impl JsonSchema for KeymapAction {
 123    /// This is used when generating the JSON schema for the `KeymapAction` type, so that it can
 124    /// reference the keymap action schema.
 125    fn schema_name() -> Cow<'static, str> {
 126        "KeymapAction".into()
 127    }
 128
 129    /// This schema will be replaced with the full action schema in
 130    /// `KeymapFile::generate_json_schema`.
 131    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
 132        json_schema!(true)
 133    }
 134}
 135
 136#[derive(Debug)]
 137#[must_use]
 138pub enum KeymapFileLoadResult {
 139    Success {
 140        key_bindings: Vec<KeyBinding>,
 141    },
 142    SomeFailedToLoad {
 143        key_bindings: Vec<KeyBinding>,
 144        error_message: MarkdownString,
 145    },
 146    JsonParseFailure {
 147        error: anyhow::Error,
 148    },
 149}
 150
 151impl KeymapFile {
 152    pub fn parse(content: &str) -> anyhow::Result<Self> {
 153        parse_json_with_comments::<Self>(content)
 154    }
 155
 156    pub fn load_asset(
 157        asset_path: &str,
 158        source: Option<KeybindSource>,
 159        cx: &App,
 160    ) -> anyhow::Result<Vec<KeyBinding>> {
 161        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
 162            KeymapFileLoadResult::Success { mut key_bindings } => match source {
 163                Some(source) => Ok({
 164                    for key_binding in &mut key_bindings {
 165                        key_binding.set_meta(source.meta());
 166                    }
 167                    key_bindings
 168                }),
 169                None => Ok(key_bindings),
 170            },
 171            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => {
 172                anyhow::bail!("Error loading built-in keymap \"{asset_path}\": {error_message}",)
 173            }
 174            KeymapFileLoadResult::JsonParseFailure { error } => {
 175                anyhow::bail!("JSON parse error in built-in keymap \"{asset_path}\": {error}")
 176            }
 177        }
 178    }
 179
 180    pub fn load_asset_allow_partial_failure(
 181        asset_path: &str,
 182        cx: &App,
 183    ) -> anyhow::Result<Vec<KeyBinding>> {
 184        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
 185            KeymapFileLoadResult::SomeFailedToLoad {
 186                key_bindings,
 187                error_message,
 188                ..
 189            } if key_bindings.is_empty() => {
 190                anyhow::bail!("Error loading built-in keymap \"{asset_path}\": {error_message}",)
 191            }
 192            KeymapFileLoadResult::Success { key_bindings, .. }
 193            | KeymapFileLoadResult::SomeFailedToLoad { key_bindings, .. } => Ok(key_bindings),
 194            KeymapFileLoadResult::JsonParseFailure { error } => {
 195                anyhow::bail!("JSON parse error in built-in keymap \"{asset_path}\": {error}")
 196            }
 197        }
 198    }
 199
 200    #[cfg(feature = "test-support")]
 201    pub fn load_panic_on_failure(content: &str, cx: &App) -> Vec<KeyBinding> {
 202        match Self::load(content, cx) {
 203            KeymapFileLoadResult::Success { key_bindings, .. } => key_bindings,
 204            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => {
 205                panic!("{error_message}");
 206            }
 207            KeymapFileLoadResult::JsonParseFailure { error } => {
 208                panic!("JSON parse error: {error}");
 209            }
 210        }
 211    }
 212
 213    pub fn load(content: &str, cx: &App) -> KeymapFileLoadResult {
 214        if content.is_empty() {
 215            return KeymapFileLoadResult::Success {
 216                key_bindings: Vec::new(),
 217            };
 218        }
 219        let keymap_file = match Self::parse(content) {
 220            Ok(keymap_file) => keymap_file,
 221            Err(error) => {
 222                return KeymapFileLoadResult::JsonParseFailure { error };
 223            }
 224        };
 225
 226        // Accumulate errors in order to support partial load of user keymap in the presence of
 227        // errors in context and binding parsing.
 228        let mut errors = Vec::new();
 229        let mut key_bindings = Vec::new();
 230
 231        for KeymapSection {
 232            context,
 233            use_key_equivalents,
 234            bindings,
 235            unrecognized_fields,
 236        } in keymap_file.0.iter()
 237        {
 238            let context_predicate: Option<Rc<KeyBindingContextPredicate>> = if context.is_empty() {
 239                None
 240            } else {
 241                match KeyBindingContextPredicate::parse(context) {
 242                    Ok(context_predicate) => Some(context_predicate.into()),
 243                    Err(err) => {
 244                        // Leading space is to separate from the message indicating which section
 245                        // the error occurred in.
 246                        errors.push((
 247                            context,
 248                            format!(" Parse error in section `context` field: {}", err),
 249                        ));
 250                        continue;
 251                    }
 252                }
 253            };
 254
 255            let mut section_errors = String::new();
 256
 257            if !unrecognized_fields.is_empty() {
 258                write!(
 259                    section_errors,
 260                    "\n\n - Unrecognized fields: {}",
 261                    MarkdownInlineCode(&format!("{:?}", unrecognized_fields.keys()))
 262                )
 263                .unwrap();
 264            }
 265
 266            if let Some(bindings) = bindings {
 267                for (keystrokes, action) in bindings {
 268                    let result = Self::load_keybinding(
 269                        keystrokes,
 270                        action,
 271                        context_predicate.clone(),
 272                        *use_key_equivalents,
 273                        cx,
 274                    );
 275                    match result {
 276                        Ok(key_binding) => {
 277                            key_bindings.push(key_binding);
 278                        }
 279                        Err(err) => {
 280                            let mut lines = err.lines();
 281                            let mut indented_err = lines.next().unwrap().to_string();
 282                            for line in lines {
 283                                indented_err.push_str("  ");
 284                                indented_err.push_str(line);
 285                                indented_err.push_str("\n");
 286                            }
 287                            write!(
 288                                section_errors,
 289                                "\n\n- In binding {}, {indented_err}",
 290                                MarkdownInlineCode(&format!("\"{}\"", keystrokes))
 291                            )
 292                            .unwrap();
 293                        }
 294                    }
 295                }
 296            }
 297
 298            if !section_errors.is_empty() {
 299                errors.push((context, section_errors))
 300            }
 301        }
 302
 303        if errors.is_empty() {
 304            KeymapFileLoadResult::Success { key_bindings }
 305        } else {
 306            let mut error_message = "Errors in user keymap file.\n".to_owned();
 307            for (context, section_errors) in errors {
 308                if context.is_empty() {
 309                    let _ = write!(error_message, "\n\nIn section without context predicate:");
 310                } else {
 311                    let _ = write!(
 312                        error_message,
 313                        "\n\nIn section with {}:",
 314                        MarkdownInlineCode(&format!("context = \"{}\"", context))
 315                    );
 316                }
 317                let _ = write!(error_message, "{section_errors}");
 318            }
 319            KeymapFileLoadResult::SomeFailedToLoad {
 320                key_bindings,
 321                error_message: MarkdownString(error_message),
 322            }
 323        }
 324    }
 325
 326    fn load_keybinding(
 327        keystrokes: &str,
 328        action: &KeymapAction,
 329        context: Option<Rc<KeyBindingContextPredicate>>,
 330        use_key_equivalents: bool,
 331        cx: &App,
 332    ) -> std::result::Result<KeyBinding, String> {
 333        let (action, action_input_string) = Self::build_keymap_action(action, cx)?;
 334
 335        let key_binding = match KeyBinding::load(
 336            keystrokes,
 337            action,
 338            context,
 339            use_key_equivalents,
 340            action_input_string.map(SharedString::from),
 341            cx.keyboard_mapper().as_ref(),
 342        ) {
 343            Ok(key_binding) => key_binding,
 344            Err(InvalidKeystrokeError { keystroke }) => {
 345                return Err(format!(
 346                    "invalid keystroke {}. {}",
 347                    MarkdownInlineCode(&format!("\"{}\"", &keystroke)),
 348                    KEYSTROKE_PARSE_EXPECTED_MESSAGE
 349                ));
 350            }
 351        };
 352
 353        if let Some(validator) = KEY_BINDING_VALIDATORS.get(&key_binding.action().type_id()) {
 354            match validator.validate(&key_binding) {
 355                Ok(()) => Ok(key_binding),
 356                Err(error) => Err(error.0),
 357            }
 358        } else {
 359            Ok(key_binding)
 360        }
 361    }
 362
 363    pub fn parse_action(
 364        action: &KeymapAction,
 365    ) -> Result<Option<(&String, Option<&Value>)>, String> {
 366        let name_and_input = match &action.0 {
 367            Value::Array(items) => {
 368                if items.len() != 2 {
 369                    return Err(format!(
 370                        "expected two-element array of `[name, input]`. \
 371                        Instead found {}.",
 372                        MarkdownInlineCode(&action.0.to_string())
 373                    ));
 374                }
 375                let serde_json::Value::String(ref name) = items[0] else {
 376                    return Err(format!(
 377                        "expected two-element array of `[name, input]`, \
 378                        but the first element is not a string in {}.",
 379                        MarkdownInlineCode(&action.0.to_string())
 380                    ));
 381                };
 382                Some((name, Some(&items[1])))
 383            }
 384            Value::String(name) => Some((name, None)),
 385            Value::Null => None,
 386            _ => {
 387                return Err(format!(
 388                    "expected two-element array of `[name, input]`. \
 389                    Instead found {}.",
 390                    MarkdownInlineCode(&action.0.to_string())
 391                ));
 392            }
 393        };
 394        Ok(name_and_input)
 395    }
 396
 397    fn build_keymap_action(
 398        action: &KeymapAction,
 399        cx: &App,
 400    ) -> std::result::Result<(Box<dyn Action>, Option<String>), String> {
 401        let (build_result, action_input_string) = match Self::parse_action(action)? {
 402            Some((name, action_input)) if name.as_str() == ActionSequence::name_for_type() => {
 403                match action_input {
 404                    Some(action_input) => (
 405                        ActionSequence::build_sequence(action_input.clone(), cx),
 406                        None,
 407                    ),
 408                    None => (Err(ActionSequence::expected_array_error()), None),
 409                }
 410            }
 411            Some((name, Some(action_input))) => {
 412                let action_input_string = action_input.to_string();
 413                (
 414                    cx.build_action(name, Some(action_input.clone())),
 415                    Some(action_input_string),
 416                )
 417            }
 418            Some((name, None)) => (cx.build_action(name, None), None),
 419            None => (Ok(NoAction.boxed_clone()), None),
 420        };
 421
 422        let action = match build_result {
 423            Ok(action) => action,
 424            Err(ActionBuildError::NotFound { name }) => {
 425                return Err(format!(
 426                    "didn't find an action named {}.",
 427                    MarkdownInlineCode(&format!("\"{}\"", &name))
 428                ));
 429            }
 430            Err(ActionBuildError::BuildError { name, error }) => match action_input_string {
 431                Some(action_input_string) => {
 432                    return Err(format!(
 433                        "can't build {} action from input value {}: {}",
 434                        MarkdownInlineCode(&format!("\"{}\"", &name)),
 435                        MarkdownInlineCode(&action_input_string),
 436                        MarkdownEscaped(&error.to_string())
 437                    ));
 438                }
 439                None => {
 440                    return Err(format!(
 441                        "can't build {} action - it requires input data via [name, input]: {}",
 442                        MarkdownInlineCode(&format!("\"{}\"", &name)),
 443                        MarkdownEscaped(&error.to_string())
 444                    ));
 445                }
 446            },
 447        };
 448
 449        Ok((action, action_input_string))
 450    }
 451
 452    /// Creates a JSON schema generator, suitable for generating json schemas
 453    /// for actions
 454    pub fn action_schema_generator() -> schemars::SchemaGenerator {
 455        schemars::generate::SchemaSettings::draft2019_09().into_generator()
 456    }
 457
 458    pub fn generate_json_schema_for_registered_actions(cx: &mut App) -> Value {
 459        // instead of using DefaultDenyUnknownFields, actions typically use
 460        // `#[serde(deny_unknown_fields)]` so that these cases are reported as parse failures. This
 461        // is because the rest of the keymap will still load in these cases, whereas other settings
 462        // files would not.
 463        let mut generator = Self::action_schema_generator();
 464
 465        let action_schemas = cx.action_schemas(&mut generator);
 466        let action_documentation = cx.action_documentation();
 467        let deprecations = cx.deprecated_actions_to_preferred_actions();
 468        let deprecation_messages = cx.action_deprecation_messages();
 469        KeymapFile::generate_json_schema(
 470            generator,
 471            action_schemas,
 472            action_documentation,
 473            deprecations,
 474            deprecation_messages,
 475        )
 476    }
 477
 478    fn generate_json_schema(
 479        mut generator: schemars::SchemaGenerator,
 480        action_schemas: Vec<(&'static str, Option<schemars::Schema>)>,
 481        action_documentation: &HashMap<&'static str, &'static str>,
 482        deprecations: &HashMap<&'static str, &'static str>,
 483        deprecation_messages: &HashMap<&'static str, &'static str>,
 484    ) -> serde_json::Value {
 485        fn add_deprecation(schema: &mut schemars::Schema, message: String) {
 486            schema.insert(
 487                // deprecationMessage is not part of the JSON Schema spec, but
 488                // json-language-server recognizes it.
 489                "deprecationMessage".to_string(),
 490                Value::String(message),
 491            );
 492        }
 493
 494        fn add_deprecation_preferred_name(schema: &mut schemars::Schema, new_name: &str) {
 495            add_deprecation(schema, format!("Deprecated, use {new_name}"));
 496        }
 497
 498        fn add_description(schema: &mut schemars::Schema, description: &str) {
 499            schema.insert(
 500                "description".to_string(),
 501                Value::String(description.to_string()),
 502            );
 503        }
 504
 505        let empty_object = json_schema!({
 506            "type": "object"
 507        });
 508
 509        // This is a workaround for a json-language-server issue where it matches the first
 510        // alternative that matches the value's shape and uses that for documentation.
 511        //
 512        // In the case of the array validations, it would even provide an error saying that the name
 513        // must match the name of the first alternative.
 514        let mut empty_action_name = json_schema!({
 515            "type": "string",
 516            "const": ""
 517        });
 518        let no_action_message = "No action named this.";
 519        add_description(&mut empty_action_name, no_action_message);
 520        add_deprecation(&mut empty_action_name, no_action_message.to_string());
 521        let empty_action_name_with_input = json_schema!({
 522            "type": "array",
 523            "items": [
 524                empty_action_name,
 525                true
 526            ],
 527            "minItems": 2,
 528            "maxItems": 2
 529        });
 530        let mut keymap_action_alternatives = vec![empty_action_name, empty_action_name_with_input];
 531
 532        let mut empty_schema_action_names = vec![];
 533        for (name, action_schema) in action_schemas.into_iter() {
 534            let deprecation = if name == NoAction.name() {
 535                Some("null")
 536            } else {
 537                deprecations.get(name).copied()
 538            };
 539
 540            // Add an alternative for plain action names.
 541            let mut plain_action = json_schema!({
 542                "type": "string",
 543                "const": name
 544            });
 545            if let Some(message) = deprecation_messages.get(name) {
 546                add_deprecation(&mut plain_action, message.to_string());
 547            } else if let Some(new_name) = deprecation {
 548                add_deprecation_preferred_name(&mut plain_action, new_name);
 549            }
 550            let description = action_documentation.get(name);
 551            if let Some(description) = &description {
 552                add_description(&mut plain_action, description);
 553            }
 554            keymap_action_alternatives.push(plain_action);
 555
 556            // Add an alternative for actions with data specified as a [name, data] array.
 557            //
 558            // When a struct with no deserializable fields is added by deriving `Action`, an empty
 559            // object schema is produced. The action should be invoked without data in this case.
 560            if let Some(schema) = action_schema
 561                && schema != empty_object
 562            {
 563                let mut matches_action_name = json_schema!({
 564                    "const": name
 565                });
 566                if let Some(description) = &description {
 567                    add_description(&mut matches_action_name, description);
 568                }
 569                if let Some(message) = deprecation_messages.get(name) {
 570                    add_deprecation(&mut matches_action_name, message.to_string());
 571                } else if let Some(new_name) = deprecation {
 572                    add_deprecation_preferred_name(&mut matches_action_name, new_name);
 573                }
 574                let action_with_input = json_schema!({
 575                    "type": "array",
 576                    "items": [matches_action_name, schema],
 577                    "minItems": 2,
 578                    "maxItems": 2
 579                });
 580                keymap_action_alternatives.push(action_with_input);
 581            } else {
 582                empty_schema_action_names.push(name);
 583            }
 584        }
 585
 586        if !empty_schema_action_names.is_empty() {
 587            let action_names = json_schema!({ "enum": empty_schema_action_names });
 588            let no_properties_allowed = json_schema!({
 589                "type": "object",
 590                "additionalProperties": false
 591            });
 592            let mut actions_with_empty_input = json_schema!({
 593                "type": "array",
 594                "items": [action_names, no_properties_allowed],
 595                "minItems": 2,
 596                "maxItems": 2
 597            });
 598            add_deprecation(
 599                &mut actions_with_empty_input,
 600                "This action does not take input - just the action name string should be used."
 601                    .to_string(),
 602            );
 603            keymap_action_alternatives.push(actions_with_empty_input);
 604        }
 605
 606        // Placing null first causes json-language-server to default assuming actions should be
 607        // null, so place it last.
 608        keymap_action_alternatives.push(json_schema!({
 609            "type": "null"
 610        }));
 611
 612        // The `KeymapSection` schema will reference the `KeymapAction` schema by name, so setting
 613        // the definition of `KeymapAction` results in the full action schema being used.
 614        generator.definitions_mut().insert(
 615            KeymapAction::schema_name().to_string(),
 616            json!({
 617                "oneOf": keymap_action_alternatives
 618            }),
 619        );
 620
 621        generator.root_schema_for::<KeymapFile>().to_value()
 622    }
 623
 624    pub fn sections(&self) -> impl DoubleEndedIterator<Item = &KeymapSection> {
 625        self.0.iter()
 626    }
 627
 628    pub async fn load_keymap_file(fs: &Arc<dyn Fs>) -> Result<String> {
 629        match fs.load(paths::keymap_file()).await {
 630            result @ Ok(_) => result,
 631            Err(err) => {
 632                if let Some(e) = err.downcast_ref::<std::io::Error>()
 633                    && e.kind() == std::io::ErrorKind::NotFound
 634                {
 635                    return Ok(crate::initial_keymap_content().to_string());
 636                }
 637                Err(err)
 638            }
 639        }
 640    }
 641
 642    pub fn update_keybinding<'a>(
 643        mut operation: KeybindUpdateOperation<'a>,
 644        mut keymap_contents: String,
 645        tab_size: usize,
 646        keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
 647    ) -> Result<String> {
 648        match operation {
 649            // if trying to replace a keybinding that is not user-defined, treat it as an add operation
 650            KeybindUpdateOperation::Replace {
 651                target_keybind_source: target_source,
 652                source,
 653                target,
 654            } if target_source != KeybindSource::User => {
 655                operation = KeybindUpdateOperation::Add {
 656                    source,
 657                    from: Some(target),
 658                };
 659            }
 660            // if trying to remove a keybinding that is not user-defined, treat it as creating a binding
 661            // that binds it to `zed::NoAction`
 662            KeybindUpdateOperation::Remove {
 663                target,
 664                target_keybind_source,
 665            } if target_keybind_source != KeybindSource::User => {
 666                let mut source = target.clone();
 667                source.action_name = gpui::NoAction.name();
 668                source.action_arguments.take();
 669                operation = KeybindUpdateOperation::Add {
 670                    source,
 671                    from: Some(target),
 672                };
 673            }
 674            _ => {}
 675        }
 676
 677        // Sanity check that keymap contents are valid, even though we only use it for Replace.
 678        // We don't want to modify the file if it's invalid.
 679        let keymap = Self::parse(&keymap_contents).context("Failed to parse keymap")?;
 680
 681        if let KeybindUpdateOperation::Remove { target, .. } = operation {
 682            let target_action_value = target
 683                .action_value()
 684                .context("Failed to generate target action JSON value")?;
 685            let Some((index, keystrokes_str)) =
 686                find_binding(&keymap, &target, &target_action_value, keyboard_mapper)
 687            else {
 688                anyhow::bail!("Failed to find keybinding to remove");
 689            };
 690            let is_only_binding = keymap.0[index]
 691                .bindings
 692                .as_ref()
 693                .is_none_or(|bindings| bindings.len() == 1);
 694            let key_path: &[&str] = if is_only_binding {
 695                &[]
 696            } else {
 697                &["bindings", keystrokes_str]
 698            };
 699            let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
 700                &keymap_contents,
 701                key_path,
 702                None,
 703                None,
 704                index,
 705                tab_size,
 706            );
 707            keymap_contents.replace_range(replace_range, &replace_value);
 708            return Ok(keymap_contents);
 709        }
 710
 711        if let KeybindUpdateOperation::Replace { source, target, .. } = operation {
 712            let target_action_value = target
 713                .action_value()
 714                .context("Failed to generate target action JSON value")?;
 715            let source_action_value = source
 716                .action_value()
 717                .context("Failed to generate source action JSON value")?;
 718
 719            if let Some((index, keystrokes_str)) =
 720                find_binding(&keymap, &target, &target_action_value, keyboard_mapper)
 721            {
 722                if target.context == source.context {
 723                    // if we are only changing the keybinding (common case)
 724                    // not the context, etc. Then just update the binding in place
 725
 726                    let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
 727                        &keymap_contents,
 728                        &["bindings", keystrokes_str],
 729                        Some(&source_action_value),
 730                        Some(&source.keystrokes_unparsed()),
 731                        index,
 732                        tab_size,
 733                    );
 734                    keymap_contents.replace_range(replace_range, &replace_value);
 735
 736                    return Ok(keymap_contents);
 737                } else if keymap.0[index]
 738                    .bindings
 739                    .as_ref()
 740                    .is_none_or(|bindings| bindings.len() == 1)
 741                {
 742                    // if we are replacing the only binding in the section,
 743                    // just update the section in place, updating the context
 744                    // and the binding
 745
 746                    let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
 747                        &keymap_contents,
 748                        &["bindings", keystrokes_str],
 749                        Some(&source_action_value),
 750                        Some(&source.keystrokes_unparsed()),
 751                        index,
 752                        tab_size,
 753                    );
 754                    keymap_contents.replace_range(replace_range, &replace_value);
 755
 756                    let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
 757                        &keymap_contents,
 758                        &["context"],
 759                        source.context.map(Into::into).as_ref(),
 760                        None,
 761                        index,
 762                        tab_size,
 763                    );
 764                    keymap_contents.replace_range(replace_range, &replace_value);
 765                    return Ok(keymap_contents);
 766                } else {
 767                    // if we are replacing one of multiple bindings in a section
 768                    // with a context change, remove the existing binding from the
 769                    // section, then treat this operation as an add operation of the
 770                    // new binding with the updated context.
 771
 772                    let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
 773                        &keymap_contents,
 774                        &["bindings", keystrokes_str],
 775                        None,
 776                        None,
 777                        index,
 778                        tab_size,
 779                    );
 780                    keymap_contents.replace_range(replace_range, &replace_value);
 781                    operation = KeybindUpdateOperation::Add {
 782                        source,
 783                        from: Some(target),
 784                    };
 785                }
 786            } else {
 787                log::warn!(
 788                    "Failed to find keybinding to update `{:?} -> {}` creating new binding for `{:?} -> {}` instead",
 789                    target.keystrokes,
 790                    target_action_value,
 791                    source.keystrokes,
 792                    source_action_value,
 793                );
 794                operation = KeybindUpdateOperation::Add {
 795                    source,
 796                    from: Some(target),
 797                };
 798            }
 799        }
 800
 801        if let KeybindUpdateOperation::Add {
 802            source: keybinding,
 803            from,
 804        } = operation
 805        {
 806            let mut value = serde_json::Map::with_capacity(4);
 807            if let Some(context) = keybinding.context {
 808                value.insert("context".to_string(), context.into());
 809            }
 810            let use_key_equivalents = from.and_then(|from| {
 811                let action_value = from.action_value().context("Failed to serialize action value. `use_key_equivalents` on new keybinding may be incorrect.").log_err()?;
 812                let (index, _) = find_binding(&keymap, &from, &action_value, keyboard_mapper)?;
 813                Some(keymap.0[index].use_key_equivalents)
 814            }).unwrap_or(false);
 815            if use_key_equivalents {
 816                value.insert("use_key_equivalents".to_string(), true.into());
 817            }
 818
 819            value.insert("bindings".to_string(), {
 820                let mut bindings = serde_json::Map::new();
 821                let action = keybinding.action_value()?;
 822                bindings.insert(keybinding.keystrokes_unparsed(), action);
 823                bindings.into()
 824            });
 825
 826            let (replace_range, replace_value) = append_top_level_array_value_in_json_text(
 827                &keymap_contents,
 828                &value.into(),
 829                tab_size,
 830            );
 831            keymap_contents.replace_range(replace_range, &replace_value);
 832        }
 833        return Ok(keymap_contents);
 834
 835        fn find_binding<'a, 'b>(
 836            keymap: &'b KeymapFile,
 837            target: &KeybindUpdateTarget<'a>,
 838            target_action_value: &Value,
 839            keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
 840        ) -> Option<(usize, &'b str)> {
 841            let target_context_parsed =
 842                KeyBindingContextPredicate::parse(target.context.unwrap_or("")).ok();
 843            for (index, section) in keymap.sections().enumerate() {
 844                let section_context_parsed =
 845                    KeyBindingContextPredicate::parse(&section.context).ok();
 846                if section_context_parsed != target_context_parsed {
 847                    continue;
 848                }
 849                let Some(bindings) = &section.bindings else {
 850                    continue;
 851                };
 852                for (keystrokes_str, action) in bindings {
 853                    let Ok(keystrokes) = keystrokes_str
 854                        .split_whitespace()
 855                        .map(|source| {
 856                            let keystroke = Keystroke::parse(source)?;
 857                            Ok(KeybindingKeystroke::new_with_mapper(
 858                                keystroke,
 859                                false,
 860                                keyboard_mapper,
 861                            ))
 862                        })
 863                        .collect::<Result<Vec<_>, InvalidKeystrokeError>>()
 864                    else {
 865                        continue;
 866                    };
 867                    if keystrokes.len() != target.keystrokes.len()
 868                        || !keystrokes
 869                            .iter()
 870                            .zip(target.keystrokes)
 871                            .all(|(a, b)| a.inner().should_match(b))
 872                    {
 873                        continue;
 874                    }
 875                    if &action.0 != target_action_value {
 876                        continue;
 877                    }
 878                    return Some((index, keystrokes_str));
 879                }
 880            }
 881            None
 882        }
 883    }
 884}
 885
 886#[derive(Clone, Debug)]
 887pub enum KeybindUpdateOperation<'a> {
 888    Replace {
 889        /// Describes the keybind to create
 890        source: KeybindUpdateTarget<'a>,
 891        /// Describes the keybind to remove
 892        target: KeybindUpdateTarget<'a>,
 893        target_keybind_source: KeybindSource,
 894    },
 895    Add {
 896        source: KeybindUpdateTarget<'a>,
 897        from: Option<KeybindUpdateTarget<'a>>,
 898    },
 899    Remove {
 900        target: KeybindUpdateTarget<'a>,
 901        target_keybind_source: KeybindSource,
 902    },
 903}
 904
 905impl KeybindUpdateOperation<'_> {
 906    pub fn generate_telemetry(
 907        &self,
 908    ) -> (
 909        // The keybind that is created
 910        String,
 911        // The keybinding that was removed
 912        String,
 913        // The source of the keybinding
 914        String,
 915    ) {
 916        let (new_binding, removed_binding, source) = match &self {
 917            KeybindUpdateOperation::Replace {
 918                source,
 919                target,
 920                target_keybind_source,
 921            } => (Some(source), Some(target), Some(*target_keybind_source)),
 922            KeybindUpdateOperation::Add { source, .. } => (Some(source), None, None),
 923            KeybindUpdateOperation::Remove {
 924                target,
 925                target_keybind_source,
 926            } => (None, Some(target), Some(*target_keybind_source)),
 927        };
 928
 929        let new_binding = new_binding
 930            .map(KeybindUpdateTarget::telemetry_string)
 931            .unwrap_or("null".to_owned());
 932        let removed_binding = removed_binding
 933            .map(KeybindUpdateTarget::telemetry_string)
 934            .unwrap_or("null".to_owned());
 935
 936        let source = source
 937            .as_ref()
 938            .map(KeybindSource::name)
 939            .map(ToOwned::to_owned)
 940            .unwrap_or("null".to_owned());
 941
 942        (new_binding, removed_binding, source)
 943    }
 944}
 945
 946impl<'a> KeybindUpdateOperation<'a> {
 947    pub const fn add(source: KeybindUpdateTarget<'a>) -> Self {
 948        Self::Add { source, from: None }
 949    }
 950}
 951
 952#[derive(Debug, Clone)]
 953pub struct KeybindUpdateTarget<'a> {
 954    pub context: Option<&'a str>,
 955    pub keystrokes: &'a [KeybindingKeystroke],
 956    pub action_name: &'a str,
 957    pub action_arguments: Option<&'a str>,
 958}
 959
 960impl<'a> KeybindUpdateTarget<'a> {
 961    fn action_value(&self) -> Result<Value> {
 962        if self.action_name == gpui::NoAction.name() {
 963            return Ok(Value::Null);
 964        }
 965        let action_name: Value = self.action_name.into();
 966        let value = match self.action_arguments {
 967            Some(args) if !args.is_empty() => {
 968                let args = serde_json::from_str::<Value>(args)
 969                    .context("Failed to parse action arguments as JSON")?;
 970                serde_json::json!([action_name, args])
 971            }
 972            _ => action_name,
 973        };
 974        Ok(value)
 975    }
 976
 977    fn keystrokes_unparsed(&self) -> String {
 978        let mut keystrokes = String::with_capacity(self.keystrokes.len() * 8);
 979        for keystroke in self.keystrokes {
 980            // The reason use `keystroke.unparse()` instead of `keystroke.inner.unparse()`
 981            // here is that, we want the user to use `ctrl-shift-4` instead of `ctrl-$`
 982            // by default on Windows.
 983            keystrokes.push_str(&keystroke.unparse());
 984            keystrokes.push(' ');
 985        }
 986        keystrokes.pop();
 987        keystrokes
 988    }
 989
 990    fn telemetry_string(&self) -> String {
 991        format!(
 992            "action_name: {}, context: {}, action_arguments: {}, keystrokes: {}",
 993            self.action_name,
 994            self.context.unwrap_or("global"),
 995            self.action_arguments.unwrap_or("none"),
 996            self.keystrokes_unparsed()
 997        )
 998    }
 999}
1000
1001#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
1002pub enum KeybindSource {
1003    User,
1004    Vim,
1005    Base,
1006    #[default]
1007    Default,
1008    Unknown,
1009}
1010
1011impl KeybindSource {
1012    const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::Base as u32);
1013    const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::Default as u32);
1014    const VIM: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::Vim as u32);
1015    const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::User as u32);
1016
1017    pub const fn name(&self) -> &'static str {
1018        match self {
1019            KeybindSource::User => "User",
1020            KeybindSource::Default => "Default",
1021            KeybindSource::Base => "Base",
1022            KeybindSource::Vim => "Vim",
1023            KeybindSource::Unknown => "Unknown",
1024        }
1025    }
1026
1027    pub const fn meta(&self) -> KeyBindingMetaIndex {
1028        match self {
1029            KeybindSource::User => Self::USER,
1030            KeybindSource::Default => Self::DEFAULT,
1031            KeybindSource::Base => Self::BASE,
1032            KeybindSource::Vim => Self::VIM,
1033            KeybindSource::Unknown => KeyBindingMetaIndex(*self as u32),
1034        }
1035    }
1036
1037    pub const fn from_meta(index: KeyBindingMetaIndex) -> Self {
1038        match index {
1039            Self::USER => KeybindSource::User,
1040            Self::BASE => KeybindSource::Base,
1041            Self::DEFAULT => KeybindSource::Default,
1042            Self::VIM => KeybindSource::Vim,
1043            _ => KeybindSource::Unknown,
1044        }
1045    }
1046}
1047
1048impl From<KeyBindingMetaIndex> for KeybindSource {
1049    fn from(index: KeyBindingMetaIndex) -> Self {
1050        Self::from_meta(index)
1051    }
1052}
1053
1054impl From<KeybindSource> for KeyBindingMetaIndex {
1055    fn from(source: KeybindSource) -> Self {
1056        source.meta()
1057    }
1058}
1059
1060/// Runs a sequence of actions. Does not wait for asynchronous actions to complete before running
1061/// the next action. Currently only works in workspace windows.
1062///
1063/// This action is special-cased in keymap parsing to allow it to access `App` while parsing, so
1064/// that it can parse its input actions.
1065pub struct ActionSequence(pub Vec<Box<dyn Action>>);
1066
1067register_action!(ActionSequence);
1068
1069impl ActionSequence {
1070    fn build_sequence(
1071        value: Value,
1072        cx: &App,
1073    ) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
1074        match value {
1075            Value::Array(values) => {
1076                let actions = values
1077                    .into_iter()
1078                    .enumerate()
1079                    .map(|(index, action)| {
1080                        match KeymapFile::build_keymap_action(&KeymapAction(action), cx) {
1081                            Ok((action, _)) => Ok(action),
1082                            Err(err) => {
1083                                return Err(ActionBuildError::BuildError {
1084                                    name: Self::name_for_type().to_string(),
1085                                    error: anyhow::anyhow!(
1086                                        "error at sequence index {index}: {err}"
1087                                    ),
1088                                });
1089                            }
1090                        }
1091                    })
1092                    .collect::<Result<Vec<_>, _>>()?;
1093                Ok(Box::new(Self(actions)))
1094            }
1095            _ => Err(Self::expected_array_error()),
1096        }
1097    }
1098
1099    fn expected_array_error() -> ActionBuildError {
1100        ActionBuildError::BuildError {
1101            name: Self::name_for_type().to_string(),
1102            error: anyhow::anyhow!("expected array of actions"),
1103        }
1104    }
1105}
1106
1107impl Action for ActionSequence {
1108    fn name(&self) -> &'static str {
1109        Self::name_for_type()
1110    }
1111
1112    fn name_for_type() -> &'static str
1113    where
1114        Self: Sized,
1115    {
1116        "action::Sequence"
1117    }
1118
1119    fn partial_eq(&self, action: &dyn Action) -> bool {
1120        action
1121            .as_any()
1122            .downcast_ref::<Self>()
1123            .map_or(false, |other| {
1124                self.0.len() == other.0.len()
1125                    && self
1126                        .0
1127                        .iter()
1128                        .zip(other.0.iter())
1129                        .all(|(a, b)| a.partial_eq(b.as_ref()))
1130            })
1131    }
1132
1133    fn boxed_clone(&self) -> Box<dyn Action> {
1134        Box::new(ActionSequence(
1135            self.0
1136                .iter()
1137                .map(|action| action.boxed_clone())
1138                .collect::<Vec<_>>(),
1139        ))
1140    }
1141
1142    fn build(_value: Value) -> Result<Box<dyn Action>> {
1143        Err(anyhow::anyhow!(
1144            "{} cannot be built directly",
1145            Self::name_for_type()
1146        ))
1147    }
1148
1149    fn action_json_schema(generator: &mut schemars::SchemaGenerator) -> Option<schemars::Schema> {
1150        let keymap_action_schema = generator.subschema_for::<KeymapAction>();
1151        Some(json_schema!({
1152            "type": "array",
1153            "items": keymap_action_schema
1154        }))
1155    }
1156
1157    fn deprecated_aliases() -> &'static [&'static str] {
1158        &[]
1159    }
1160
1161    fn deprecation_message() -> Option<&'static str> {
1162        None
1163    }
1164
1165    fn documentation() -> Option<&'static str> {
1166        Some(
1167            "Runs a sequence of actions.\n\n\
1168            NOTE: This does **not** wait for asynchronous actions to complete before running the next action.",
1169        )
1170    }
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use gpui::{DummyKeyboardMapper, KeybindingKeystroke, Keystroke};
1176    use unindent::Unindent;
1177
1178    use crate::{
1179        KeybindSource, KeymapFile,
1180        keymap_file::{KeybindUpdateOperation, KeybindUpdateTarget},
1181    };
1182
1183    #[test]
1184    fn can_deserialize_keymap_with_trailing_comma() {
1185        let json = indoc::indoc! {"[
1186              // Standard macOS bindings
1187              {
1188                \"bindings\": {
1189                  \"up\": \"menu::SelectPrevious\",
1190                },
1191              },
1192            ]
1193                  "
1194        };
1195        KeymapFile::parse(json).unwrap();
1196    }
1197
1198    #[track_caller]
1199    fn check_keymap_update(
1200        input: impl ToString,
1201        operation: KeybindUpdateOperation,
1202        expected: impl ToString,
1203    ) {
1204        let result = KeymapFile::update_keybinding(
1205            operation,
1206            input.to_string(),
1207            4,
1208            &gpui::DummyKeyboardMapper,
1209        )
1210        .expect("Update succeeded");
1211        pretty_assertions::assert_eq!(expected.to_string(), result);
1212    }
1213
1214    #[track_caller]
1215    fn parse_keystrokes(keystrokes: &str) -> Vec<KeybindingKeystroke> {
1216        keystrokes
1217            .split(' ')
1218            .map(|s| {
1219                KeybindingKeystroke::new_with_mapper(
1220                    Keystroke::parse(s).expect("Keystrokes valid"),
1221                    false,
1222                    &DummyKeyboardMapper,
1223                )
1224            })
1225            .collect()
1226    }
1227
1228    #[test]
1229    fn keymap_update() {
1230        zlog::init_test();
1231
1232        check_keymap_update(
1233            "[]",
1234            KeybindUpdateOperation::add(KeybindUpdateTarget {
1235                keystrokes: &parse_keystrokes("ctrl-a"),
1236                action_name: "zed::SomeAction",
1237                context: None,
1238                action_arguments: None,
1239            }),
1240            r#"[
1241                {
1242                    "bindings": {
1243                        "ctrl-a": "zed::SomeAction"
1244                    }
1245                }
1246            ]"#
1247            .unindent(),
1248        );
1249
1250        check_keymap_update(
1251            "[]",
1252            KeybindUpdateOperation::add(KeybindUpdateTarget {
1253                keystrokes: &parse_keystrokes("\\ a"),
1254                action_name: "zed::SomeAction",
1255                context: None,
1256                action_arguments: None,
1257            }),
1258            r#"[
1259                {
1260                    "bindings": {
1261                        "\\ a": "zed::SomeAction"
1262                    }
1263                }
1264            ]"#
1265            .unindent(),
1266        );
1267
1268        check_keymap_update(
1269            "[]",
1270            KeybindUpdateOperation::add(KeybindUpdateTarget {
1271                keystrokes: &parse_keystrokes("ctrl-a"),
1272                action_name: "zed::SomeAction",
1273                context: None,
1274                action_arguments: Some(""),
1275            }),
1276            r#"[
1277                {
1278                    "bindings": {
1279                        "ctrl-a": "zed::SomeAction"
1280                    }
1281                }
1282            ]"#
1283            .unindent(),
1284        );
1285
1286        check_keymap_update(
1287            r#"[
1288                {
1289                    "bindings": {
1290                        "ctrl-a": "zed::SomeAction"
1291                    }
1292                }
1293            ]"#
1294            .unindent(),
1295            KeybindUpdateOperation::add(KeybindUpdateTarget {
1296                keystrokes: &parse_keystrokes("ctrl-b"),
1297                action_name: "zed::SomeOtherAction",
1298                context: None,
1299                action_arguments: None,
1300            }),
1301            r#"[
1302                {
1303                    "bindings": {
1304                        "ctrl-a": "zed::SomeAction"
1305                    }
1306                },
1307                {
1308                    "bindings": {
1309                        "ctrl-b": "zed::SomeOtherAction"
1310                    }
1311                }
1312            ]"#
1313            .unindent(),
1314        );
1315
1316        check_keymap_update(
1317            r#"[
1318                {
1319                    "bindings": {
1320                        "ctrl-a": "zed::SomeAction"
1321                    }
1322                }
1323            ]"#
1324            .unindent(),
1325            KeybindUpdateOperation::add(KeybindUpdateTarget {
1326                keystrokes: &parse_keystrokes("ctrl-b"),
1327                action_name: "zed::SomeOtherAction",
1328                context: None,
1329                action_arguments: Some(r#"{"foo": "bar"}"#),
1330            }),
1331            r#"[
1332                {
1333                    "bindings": {
1334                        "ctrl-a": "zed::SomeAction"
1335                    }
1336                },
1337                {
1338                    "bindings": {
1339                        "ctrl-b": [
1340                            "zed::SomeOtherAction",
1341                            {
1342                                "foo": "bar"
1343                            }
1344                        ]
1345                    }
1346                }
1347            ]"#
1348            .unindent(),
1349        );
1350
1351        check_keymap_update(
1352            r#"[
1353                {
1354                    "bindings": {
1355                        "ctrl-a": "zed::SomeAction"
1356                    }
1357                }
1358            ]"#
1359            .unindent(),
1360            KeybindUpdateOperation::add(KeybindUpdateTarget {
1361                keystrokes: &parse_keystrokes("ctrl-b"),
1362                action_name: "zed::SomeOtherAction",
1363                context: Some("Zed > Editor && some_condition = true"),
1364                action_arguments: Some(r#"{"foo": "bar"}"#),
1365            }),
1366            r#"[
1367                {
1368                    "bindings": {
1369                        "ctrl-a": "zed::SomeAction"
1370                    }
1371                },
1372                {
1373                    "context": "Zed > Editor && some_condition = true",
1374                    "bindings": {
1375                        "ctrl-b": [
1376                            "zed::SomeOtherAction",
1377                            {
1378                                "foo": "bar"
1379                            }
1380                        ]
1381                    }
1382                }
1383            ]"#
1384            .unindent(),
1385        );
1386
1387        check_keymap_update(
1388            r#"[
1389                {
1390                    "bindings": {
1391                        "ctrl-a": "zed::SomeAction"
1392                    }
1393                }
1394            ]"#
1395            .unindent(),
1396            KeybindUpdateOperation::Replace {
1397                target: KeybindUpdateTarget {
1398                    keystrokes: &parse_keystrokes("ctrl-a"),
1399                    action_name: "zed::SomeAction",
1400                    context: None,
1401                    action_arguments: None,
1402                },
1403                source: KeybindUpdateTarget {
1404                    keystrokes: &parse_keystrokes("ctrl-b"),
1405                    action_name: "zed::SomeOtherAction",
1406                    context: None,
1407                    action_arguments: Some(r#"{"foo": "bar"}"#),
1408                },
1409                target_keybind_source: KeybindSource::Base,
1410            },
1411            r#"[
1412                {
1413                    "bindings": {
1414                        "ctrl-a": "zed::SomeAction"
1415                    }
1416                },
1417                {
1418                    "bindings": {
1419                        "ctrl-b": [
1420                            "zed::SomeOtherAction",
1421                            {
1422                                "foo": "bar"
1423                            }
1424                        ]
1425                    }
1426                }
1427            ]"#
1428            .unindent(),
1429        );
1430
1431        check_keymap_update(
1432            r#"[
1433                {
1434                    "bindings": {
1435                        "a": "zed::SomeAction"
1436                    }
1437                }
1438            ]"#
1439            .unindent(),
1440            KeybindUpdateOperation::Replace {
1441                target: KeybindUpdateTarget {
1442                    keystrokes: &parse_keystrokes("a"),
1443                    action_name: "zed::SomeAction",
1444                    context: None,
1445                    action_arguments: None,
1446                },
1447                source: KeybindUpdateTarget {
1448                    keystrokes: &parse_keystrokes("ctrl-b"),
1449                    action_name: "zed::SomeOtherAction",
1450                    context: None,
1451                    action_arguments: Some(r#"{"foo": "bar"}"#),
1452                },
1453                target_keybind_source: KeybindSource::User,
1454            },
1455            r#"[
1456                {
1457                    "bindings": {
1458                        "ctrl-b": [
1459                            "zed::SomeOtherAction",
1460                            {
1461                                "foo": "bar"
1462                            }
1463                        ]
1464                    }
1465                }
1466            ]"#
1467            .unindent(),
1468        );
1469
1470        check_keymap_update(
1471            r#"[
1472                {
1473                    "bindings": {
1474                        "\\ a": "zed::SomeAction"
1475                    }
1476                }
1477            ]"#
1478            .unindent(),
1479            KeybindUpdateOperation::Replace {
1480                target: KeybindUpdateTarget {
1481                    keystrokes: &parse_keystrokes("\\ a"),
1482                    action_name: "zed::SomeAction",
1483                    context: None,
1484                    action_arguments: None,
1485                },
1486                source: KeybindUpdateTarget {
1487                    keystrokes: &parse_keystrokes("\\ b"),
1488                    action_name: "zed::SomeOtherAction",
1489                    context: None,
1490                    action_arguments: Some(r#"{"foo": "bar"}"#),
1491                },
1492                target_keybind_source: KeybindSource::User,
1493            },
1494            r#"[
1495                {
1496                    "bindings": {
1497                        "\\ b": [
1498                            "zed::SomeOtherAction",
1499                            {
1500                                "foo": "bar"
1501                            }
1502                        ]
1503                    }
1504                }
1505            ]"#
1506            .unindent(),
1507        );
1508
1509        check_keymap_update(
1510            r#"[
1511                {
1512                    "bindings": {
1513                        "\\ a": "zed::SomeAction"
1514                    }
1515                }
1516            ]"#
1517            .unindent(),
1518            KeybindUpdateOperation::Replace {
1519                target: KeybindUpdateTarget {
1520                    keystrokes: &parse_keystrokes("\\ a"),
1521                    action_name: "zed::SomeAction",
1522                    context: None,
1523                    action_arguments: None,
1524                },
1525                source: KeybindUpdateTarget {
1526                    keystrokes: &parse_keystrokes("\\ a"),
1527                    action_name: "zed::SomeAction",
1528                    context: None,
1529                    action_arguments: None,
1530                },
1531                target_keybind_source: KeybindSource::User,
1532            },
1533            r#"[
1534                {
1535                    "bindings": {
1536                        "\\ a": "zed::SomeAction"
1537                    }
1538                }
1539            ]"#
1540            .unindent(),
1541        );
1542
1543        check_keymap_update(
1544            r#"[
1545                {
1546                    "bindings": {
1547                        "ctrl-a": "zed::SomeAction"
1548                    }
1549                }
1550            ]"#
1551            .unindent(),
1552            KeybindUpdateOperation::Replace {
1553                target: KeybindUpdateTarget {
1554                    keystrokes: &parse_keystrokes("ctrl-a"),
1555                    action_name: "zed::SomeNonexistentAction",
1556                    context: None,
1557                    action_arguments: None,
1558                },
1559                source: KeybindUpdateTarget {
1560                    keystrokes: &parse_keystrokes("ctrl-b"),
1561                    action_name: "zed::SomeOtherAction",
1562                    context: None,
1563                    action_arguments: None,
1564                },
1565                target_keybind_source: KeybindSource::User,
1566            },
1567            r#"[
1568                {
1569                    "bindings": {
1570                        "ctrl-a": "zed::SomeAction"
1571                    }
1572                },
1573                {
1574                    "bindings": {
1575                        "ctrl-b": "zed::SomeOtherAction"
1576                    }
1577                }
1578            ]"#
1579            .unindent(),
1580        );
1581
1582        check_keymap_update(
1583            r#"[
1584                {
1585                    "bindings": {
1586                        // some comment
1587                        "ctrl-a": "zed::SomeAction"
1588                        // some other comment
1589                    }
1590                }
1591            ]"#
1592            .unindent(),
1593            KeybindUpdateOperation::Replace {
1594                target: KeybindUpdateTarget {
1595                    keystrokes: &parse_keystrokes("ctrl-a"),
1596                    action_name: "zed::SomeAction",
1597                    context: None,
1598                    action_arguments: None,
1599                },
1600                source: KeybindUpdateTarget {
1601                    keystrokes: &parse_keystrokes("ctrl-b"),
1602                    action_name: "zed::SomeOtherAction",
1603                    context: None,
1604                    action_arguments: Some(r#"{"foo": "bar"}"#),
1605                },
1606                target_keybind_source: KeybindSource::User,
1607            },
1608            r#"[
1609                {
1610                    "bindings": {
1611                        // some comment
1612                        "ctrl-b": [
1613                            "zed::SomeOtherAction",
1614                            {
1615                                "foo": "bar"
1616                            }
1617                        ]
1618                        // some other comment
1619                    }
1620                }
1621            ]"#
1622            .unindent(),
1623        );
1624
1625        check_keymap_update(
1626            r#"[
1627                {
1628                    "context": "SomeContext",
1629                    "bindings": {
1630                        "a": "foo::bar",
1631                        "b": "baz::qux",
1632                    }
1633                }
1634            ]"#
1635            .unindent(),
1636            KeybindUpdateOperation::Replace {
1637                target: KeybindUpdateTarget {
1638                    keystrokes: &parse_keystrokes("a"),
1639                    action_name: "foo::bar",
1640                    context: Some("SomeContext"),
1641                    action_arguments: None,
1642                },
1643                source: KeybindUpdateTarget {
1644                    keystrokes: &parse_keystrokes("c"),
1645                    action_name: "foo::baz",
1646                    context: Some("SomeOtherContext"),
1647                    action_arguments: None,
1648                },
1649                target_keybind_source: KeybindSource::User,
1650            },
1651            r#"[
1652                {
1653                    "context": "SomeContext",
1654                    "bindings": {
1655                        "b": "baz::qux",
1656                    }
1657                },
1658                {
1659                    "context": "SomeOtherContext",
1660                    "bindings": {
1661                        "c": "foo::baz"
1662                    }
1663                }
1664            ]"#
1665            .unindent(),
1666        );
1667
1668        check_keymap_update(
1669            r#"[
1670                {
1671                    "context": "SomeContext",
1672                    "bindings": {
1673                        "a": "foo::bar",
1674                    }
1675                }
1676            ]"#
1677            .unindent(),
1678            KeybindUpdateOperation::Replace {
1679                target: KeybindUpdateTarget {
1680                    keystrokes: &parse_keystrokes("a"),
1681                    action_name: "foo::bar",
1682                    context: Some("SomeContext"),
1683                    action_arguments: None,
1684                },
1685                source: KeybindUpdateTarget {
1686                    keystrokes: &parse_keystrokes("c"),
1687                    action_name: "foo::baz",
1688                    context: Some("SomeOtherContext"),
1689                    action_arguments: None,
1690                },
1691                target_keybind_source: KeybindSource::User,
1692            },
1693            r#"[
1694                {
1695                    "context": "SomeOtherContext",
1696                    "bindings": {
1697                        "c": "foo::baz",
1698                    }
1699                }
1700            ]"#
1701            .unindent(),
1702        );
1703
1704        check_keymap_update(
1705            r#"[
1706                {
1707                    "context": "SomeContext",
1708                    "bindings": {
1709                        "a": "foo::bar",
1710                        "c": "foo::baz",
1711                    }
1712                },
1713            ]"#
1714            .unindent(),
1715            KeybindUpdateOperation::Remove {
1716                target: KeybindUpdateTarget {
1717                    context: Some("SomeContext"),
1718                    keystrokes: &parse_keystrokes("a"),
1719                    action_name: "foo::bar",
1720                    action_arguments: None,
1721                },
1722                target_keybind_source: KeybindSource::User,
1723            },
1724            r#"[
1725                {
1726                    "context": "SomeContext",
1727                    "bindings": {
1728                        "c": "foo::baz",
1729                    }
1730                },
1731            ]"#
1732            .unindent(),
1733        );
1734
1735        check_keymap_update(
1736            r#"[
1737                {
1738                    "context": "SomeContext",
1739                    "bindings": {
1740                        "\\ a": "foo::bar",
1741                        "c": "foo::baz",
1742                    }
1743                },
1744            ]"#
1745            .unindent(),
1746            KeybindUpdateOperation::Remove {
1747                target: KeybindUpdateTarget {
1748                    context: Some("SomeContext"),
1749                    keystrokes: &parse_keystrokes("\\ a"),
1750                    action_name: "foo::bar",
1751                    action_arguments: None,
1752                },
1753                target_keybind_source: KeybindSource::User,
1754            },
1755            r#"[
1756                {
1757                    "context": "SomeContext",
1758                    "bindings": {
1759                        "c": "foo::baz",
1760                    }
1761                },
1762            ]"#
1763            .unindent(),
1764        );
1765
1766        check_keymap_update(
1767            r#"[
1768                {
1769                    "context": "SomeContext",
1770                    "bindings": {
1771                        "a": ["foo::bar", true],
1772                        "c": "foo::baz",
1773                    }
1774                },
1775            ]"#
1776            .unindent(),
1777            KeybindUpdateOperation::Remove {
1778                target: KeybindUpdateTarget {
1779                    context: Some("SomeContext"),
1780                    keystrokes: &parse_keystrokes("a"),
1781                    action_name: "foo::bar",
1782                    action_arguments: Some("true"),
1783                },
1784                target_keybind_source: KeybindSource::User,
1785            },
1786            r#"[
1787                {
1788                    "context": "SomeContext",
1789                    "bindings": {
1790                        "c": "foo::baz",
1791                    }
1792                },
1793            ]"#
1794            .unindent(),
1795        );
1796
1797        check_keymap_update(
1798            r#"[
1799                {
1800                    "context": "SomeContext",
1801                    "bindings": {
1802                        "b": "foo::baz",
1803                    }
1804                },
1805                {
1806                    "context": "SomeContext",
1807                    "bindings": {
1808                        "a": ["foo::bar", true],
1809                    }
1810                },
1811                {
1812                    "context": "SomeContext",
1813                    "bindings": {
1814                        "c": "foo::baz",
1815                    }
1816                },
1817            ]"#
1818            .unindent(),
1819            KeybindUpdateOperation::Remove {
1820                target: KeybindUpdateTarget {
1821                    context: Some("SomeContext"),
1822                    keystrokes: &parse_keystrokes("a"),
1823                    action_name: "foo::bar",
1824                    action_arguments: Some("true"),
1825                },
1826                target_keybind_source: KeybindSource::User,
1827            },
1828            r#"[
1829                {
1830                    "context": "SomeContext",
1831                    "bindings": {
1832                        "b": "foo::baz",
1833                    }
1834                },
1835                {
1836                    "context": "SomeContext",
1837                    "bindings": {
1838                        "c": "foo::baz",
1839                    }
1840                },
1841            ]"#
1842            .unindent(),
1843        );
1844        check_keymap_update(
1845            r#"[
1846                {
1847                    "context": "SomeOtherContext",
1848                    "use_key_equivalents": true,
1849                    "bindings": {
1850                        "b": "foo::bar",
1851                    }
1852                },
1853            ]"#
1854            .unindent(),
1855            KeybindUpdateOperation::Add {
1856                source: KeybindUpdateTarget {
1857                    context: Some("SomeContext"),
1858                    keystrokes: &parse_keystrokes("a"),
1859                    action_name: "foo::baz",
1860                    action_arguments: Some("true"),
1861                },
1862                from: Some(KeybindUpdateTarget {
1863                    context: Some("SomeOtherContext"),
1864                    keystrokes: &parse_keystrokes("b"),
1865                    action_name: "foo::bar",
1866                    action_arguments: None,
1867                }),
1868            },
1869            r#"[
1870                {
1871                    "context": "SomeOtherContext",
1872                    "use_key_equivalents": true,
1873                    "bindings": {
1874                        "b": "foo::bar",
1875                    }
1876                },
1877                {
1878                    "context": "SomeContext",
1879                    "use_key_equivalents": true,
1880                    "bindings": {
1881                        "a": [
1882                            "foo::baz",
1883                            true
1884                        ]
1885                    }
1886                }
1887            ]"#
1888            .unindent(),
1889        );
1890
1891        check_keymap_update(
1892            r#"[
1893                {
1894                    "context": "SomeOtherContext",
1895                    "use_key_equivalents": true,
1896                    "bindings": {
1897                        "b": "foo::bar",
1898                    }
1899                },
1900            ]"#
1901            .unindent(),
1902            KeybindUpdateOperation::Remove {
1903                target: KeybindUpdateTarget {
1904                    context: Some("SomeContext"),
1905                    keystrokes: &parse_keystrokes("a"),
1906                    action_name: "foo::baz",
1907                    action_arguments: Some("true"),
1908                },
1909                target_keybind_source: KeybindSource::Default,
1910            },
1911            r#"[
1912                {
1913                    "context": "SomeOtherContext",
1914                    "use_key_equivalents": true,
1915                    "bindings": {
1916                        "b": "foo::bar",
1917                    }
1918                },
1919                {
1920                    "context": "SomeContext",
1921                    "bindings": {
1922                        "a": null
1923                    }
1924                }
1925            ]"#
1926            .unindent(),
1927        );
1928    }
1929
1930    #[test]
1931    fn test_keymap_remove() {
1932        zlog::init_test();
1933
1934        check_keymap_update(
1935            r#"
1936            [
1937              {
1938                "context": "Editor",
1939                "bindings": {
1940                  "cmd-k cmd-u": "editor::ConvertToUpperCase",
1941                  "cmd-k cmd-l": "editor::ConvertToLowerCase",
1942                  "cmd-[": "pane::GoBack",
1943                }
1944              },
1945            ]
1946            "#,
1947            KeybindUpdateOperation::Remove {
1948                target: KeybindUpdateTarget {
1949                    context: Some("Editor"),
1950                    keystrokes: &parse_keystrokes("cmd-k cmd-l"),
1951                    action_name: "editor::ConvertToLowerCase",
1952                    action_arguments: None,
1953                },
1954                target_keybind_source: KeybindSource::User,
1955            },
1956            r#"
1957            [
1958              {
1959                "context": "Editor",
1960                "bindings": {
1961                  "cmd-k cmd-u": "editor::ConvertToUpperCase",
1962                  "cmd-[": "pane::GoBack",
1963                }
1964              },
1965            ]
1966            "#,
1967        );
1968    }
1969}