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,
   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    #[cfg(feature = "test-support")]
 181    pub fn load_asset_allow_partial_failure(
 182        asset_path: &str,
 183        cx: &App,
 184    ) -> anyhow::Result<Vec<KeyBinding>> {
 185        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
 186            KeymapFileLoadResult::SomeFailedToLoad {
 187                key_bindings,
 188                error_message,
 189                ..
 190            } if key_bindings.is_empty() => {
 191                anyhow::bail!("Error loading built-in keymap \"{asset_path}\": {error_message}",)
 192            }
 193            KeymapFileLoadResult::Success { key_bindings, .. }
 194            | KeymapFileLoadResult::SomeFailedToLoad { key_bindings, .. } => Ok(key_bindings),
 195            KeymapFileLoadResult::JsonParseFailure { error } => {
 196                anyhow::bail!("JSON parse error in built-in keymap \"{asset_path}\": {error}")
 197            }
 198        }
 199    }
 200
 201    #[cfg(feature = "test-support")]
 202    pub fn load_panic_on_failure(content: &str, cx: &App) -> Vec<KeyBinding> {
 203        match Self::load(content, cx) {
 204            KeymapFileLoadResult::Success { key_bindings, .. } => key_bindings,
 205            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => {
 206                panic!("{error_message}");
 207            }
 208            KeymapFileLoadResult::JsonParseFailure { error } => {
 209                panic!("JSON parse error: {error}");
 210            }
 211        }
 212    }
 213
 214    pub fn load(content: &str, cx: &App) -> KeymapFileLoadResult {
 215        if content.is_empty() {
 216            return KeymapFileLoadResult::Success {
 217                key_bindings: Vec::new(),
 218            };
 219        }
 220        let keymap_file = match Self::parse(content) {
 221            Ok(keymap_file) => keymap_file,
 222            Err(error) => {
 223                return KeymapFileLoadResult::JsonParseFailure { error };
 224            }
 225        };
 226
 227        // Accumulate errors in order to support partial load of user keymap in the presence of
 228        // errors in context and binding parsing.
 229        let mut errors = Vec::new();
 230        let mut key_bindings = Vec::new();
 231
 232        for KeymapSection {
 233            context,
 234            use_key_equivalents,
 235            bindings,
 236            unrecognized_fields,
 237        } in keymap_file.0.iter()
 238        {
 239            let context_predicate: Option<Rc<KeyBindingContextPredicate>> = if context.is_empty() {
 240                None
 241            } else {
 242                match KeyBindingContextPredicate::parse(context) {
 243                    Ok(context_predicate) => Some(context_predicate.into()),
 244                    Err(err) => {
 245                        // Leading space is to separate from the message indicating which section
 246                        // the error occurred in.
 247                        errors.push((
 248                            context,
 249                            format!(" Parse error in section `context` field: {}", err),
 250                        ));
 251                        continue;
 252                    }
 253                }
 254            };
 255
 256            let mut section_errors = String::new();
 257
 258            if !unrecognized_fields.is_empty() {
 259                write!(
 260                    section_errors,
 261                    "\n\n - Unrecognized fields: {}",
 262                    MarkdownInlineCode(&format!("{:?}", unrecognized_fields.keys()))
 263                )
 264                .unwrap();
 265            }
 266
 267            if let Some(bindings) = bindings {
 268                for (keystrokes, action) in bindings {
 269                    let result = Self::load_keybinding(
 270                        keystrokes,
 271                        action,
 272                        context_predicate.clone(),
 273                        *use_key_equivalents,
 274                        cx,
 275                    );
 276                    match result {
 277                        Ok(key_binding) => {
 278                            key_bindings.push(key_binding);
 279                        }
 280                        Err(err) => {
 281                            let mut lines = err.lines();
 282                            let mut indented_err = lines.next().unwrap().to_string();
 283                            for line in lines {
 284                                indented_err.push_str("  ");
 285                                indented_err.push_str(line);
 286                                indented_err.push_str("\n");
 287                            }
 288                            write!(
 289                                section_errors,
 290                                "\n\n- In binding {}, {indented_err}",
 291                                MarkdownInlineCode(&format!("\"{}\"", keystrokes))
 292                            )
 293                            .unwrap();
 294                        }
 295                    }
 296                }
 297            }
 298
 299            if !section_errors.is_empty() {
 300                errors.push((context, section_errors))
 301            }
 302        }
 303
 304        if errors.is_empty() {
 305            KeymapFileLoadResult::Success { key_bindings }
 306        } else {
 307            let mut error_message = "Errors in user keymap file.\n".to_owned();
 308            for (context, section_errors) in errors {
 309                if context.is_empty() {
 310                    let _ = write!(error_message, "\n\nIn section without context predicate:");
 311                } else {
 312                    let _ = write!(
 313                        error_message,
 314                        "\n\nIn section with {}:",
 315                        MarkdownInlineCode(&format!("context = \"{}\"", context))
 316                    );
 317                }
 318                let _ = write!(error_message, "{section_errors}");
 319            }
 320            KeymapFileLoadResult::SomeFailedToLoad {
 321                key_bindings,
 322                error_message: MarkdownString(error_message),
 323            }
 324        }
 325    }
 326
 327    fn load_keybinding(
 328        keystrokes: &str,
 329        action: &KeymapAction,
 330        context: Option<Rc<KeyBindingContextPredicate>>,
 331        use_key_equivalents: bool,
 332        cx: &App,
 333    ) -> std::result::Result<KeyBinding, String> {
 334        let (build_result, action_input_string) = match &action.0 {
 335            Value::Array(items) => {
 336                if items.len() != 2 {
 337                    return Err(format!(
 338                        "expected two-element array of `[name, input]`. \
 339                        Instead found {}.",
 340                        MarkdownInlineCode(&action.0.to_string())
 341                    ));
 342                }
 343                let serde_json::Value::String(ref name) = items[0] else {
 344                    return Err(format!(
 345                        "expected two-element array of `[name, input]`, \
 346                        but the first element is not a string in {}.",
 347                        MarkdownInlineCode(&action.0.to_string())
 348                    ));
 349                };
 350                let action_input = items[1].clone();
 351                let action_input_string = action_input.to_string();
 352                (
 353                    cx.build_action(name, Some(action_input)),
 354                    Some(action_input_string),
 355                )
 356            }
 357            Value::String(name) => (cx.build_action(name, None), None),
 358            Value::Null => (Ok(NoAction.boxed_clone()), None),
 359            _ => {
 360                return Err(format!(
 361                    "expected two-element array of `[name, input]`. \
 362                    Instead found {}.",
 363                    MarkdownInlineCode(&action.0.to_string())
 364                ));
 365            }
 366        };
 367
 368        let action = match build_result {
 369            Ok(action) => action,
 370            Err(ActionBuildError::NotFound { name }) => {
 371                return Err(format!(
 372                    "didn't find an action named {}.",
 373                    MarkdownInlineCode(&format!("\"{}\"", &name))
 374                ));
 375            }
 376            Err(ActionBuildError::BuildError { name, error }) => match action_input_string {
 377                Some(action_input_string) => {
 378                    return Err(format!(
 379                        "can't build {} action from input value {}: {}",
 380                        MarkdownInlineCode(&format!("\"{}\"", &name)),
 381                        MarkdownInlineCode(&action_input_string),
 382                        MarkdownEscaped(&error.to_string())
 383                    ));
 384                }
 385                None => {
 386                    return Err(format!(
 387                        "can't build {} action - it requires input data via [name, input]: {}",
 388                        MarkdownInlineCode(&format!("\"{}\"", &name)),
 389                        MarkdownEscaped(&error.to_string())
 390                    ));
 391                }
 392            },
 393        };
 394
 395        let key_binding = match KeyBinding::load(
 396            keystrokes,
 397            action,
 398            context,
 399            use_key_equivalents,
 400            action_input_string.map(SharedString::from),
 401            cx.keyboard_mapper().as_ref(),
 402        ) {
 403            Ok(key_binding) => key_binding,
 404            Err(InvalidKeystrokeError { keystroke }) => {
 405                return Err(format!(
 406                    "invalid keystroke {}. {}",
 407                    MarkdownInlineCode(&format!("\"{}\"", &keystroke)),
 408                    KEYSTROKE_PARSE_EXPECTED_MESSAGE
 409                ));
 410            }
 411        };
 412
 413        if let Some(validator) = KEY_BINDING_VALIDATORS.get(&key_binding.action().type_id()) {
 414            match validator.validate(&key_binding) {
 415                Ok(()) => Ok(key_binding),
 416                Err(error) => Err(error.0),
 417            }
 418        } else {
 419            Ok(key_binding)
 420        }
 421    }
 422
 423    /// Creates a JSON schema generator, suitable for generating json schemas
 424    /// for actions
 425    pub fn action_schema_generator() -> schemars::SchemaGenerator {
 426        schemars::generate::SchemaSettings::draft2019_09().into_generator()
 427    }
 428
 429    pub fn generate_json_schema_for_registered_actions(cx: &mut App) -> Value {
 430        // instead of using DefaultDenyUnknownFields, actions typically use
 431        // `#[serde(deny_unknown_fields)]` so that these cases are reported as parse failures. This
 432        // is because the rest of the keymap will still load in these cases, whereas other settings
 433        // files would not.
 434        let mut generator = Self::action_schema_generator();
 435
 436        let action_schemas = cx.action_schemas(&mut generator);
 437        let deprecations = cx.deprecated_actions_to_preferred_actions();
 438        let deprecation_messages = cx.action_deprecation_messages();
 439        KeymapFile::generate_json_schema(
 440            generator,
 441            action_schemas,
 442            deprecations,
 443            deprecation_messages,
 444        )
 445    }
 446
 447    fn generate_json_schema(
 448        mut generator: schemars::SchemaGenerator,
 449        action_schemas: Vec<(&'static str, Option<schemars::Schema>)>,
 450        deprecations: &HashMap<&'static str, &'static str>,
 451        deprecation_messages: &HashMap<&'static str, &'static str>,
 452    ) -> serde_json::Value {
 453        fn add_deprecation(schema: &mut schemars::Schema, message: String) {
 454            schema.insert(
 455                // deprecationMessage is not part of the JSON Schema spec, but
 456                // json-language-server recognizes it.
 457                "deprecationMessage".to_string(),
 458                Value::String(message),
 459            );
 460        }
 461
 462        fn add_deprecation_preferred_name(schema: &mut schemars::Schema, new_name: &str) {
 463            add_deprecation(schema, format!("Deprecated, use {new_name}"));
 464        }
 465
 466        fn add_description(schema: &mut schemars::Schema, description: String) {
 467            schema.insert("description".to_string(), Value::String(description));
 468        }
 469
 470        let empty_object = json_schema!({
 471            "type": "object"
 472        });
 473
 474        // This is a workaround for a json-language-server issue where it matches the first
 475        // alternative that matches the value's shape and uses that for documentation.
 476        //
 477        // In the case of the array validations, it would even provide an error saying that the name
 478        // must match the name of the first alternative.
 479        let mut plain_action = json_schema!({
 480            "type": "string",
 481            "const": ""
 482        });
 483        let no_action_message = "No action named this.";
 484        add_description(&mut plain_action, no_action_message.to_owned());
 485        add_deprecation(&mut plain_action, no_action_message.to_owned());
 486
 487        let mut matches_action_name = json_schema!({
 488            "const": ""
 489        });
 490        let no_action_message_input = "No action named this that takes input.";
 491        add_description(&mut matches_action_name, no_action_message_input.to_owned());
 492        add_deprecation(&mut matches_action_name, no_action_message_input.to_owned());
 493
 494        let action_with_input = json_schema!({
 495            "type": "array",
 496            "items": [
 497                matches_action_name,
 498                true
 499            ],
 500            "minItems": 2,
 501            "maxItems": 2
 502        });
 503        let mut keymap_action_alternatives = vec![plain_action, action_with_input];
 504
 505        for (name, action_schema) in action_schemas.into_iter() {
 506            let description = action_schema.as_ref().and_then(|schema| {
 507                schema
 508                    .as_object()
 509                    .and_then(|obj| obj.get("description"))
 510                    .and_then(|v| v.as_str())
 511                    .map(|s| s.to_string())
 512            });
 513
 514            let deprecation = if name == NoAction.name() {
 515                Some("null")
 516            } else {
 517                deprecations.get(name).copied()
 518            };
 519
 520            // Add an alternative for plain action names.
 521            let mut plain_action = json_schema!({
 522                "type": "string",
 523                "const": name
 524            });
 525            if let Some(message) = deprecation_messages.get(name) {
 526                add_deprecation(&mut plain_action, message.to_string());
 527            } else if let Some(new_name) = deprecation {
 528                add_deprecation_preferred_name(&mut plain_action, new_name);
 529            }
 530            if let Some(desc) = description.clone() {
 531                add_description(&mut plain_action, desc);
 532            }
 533            keymap_action_alternatives.push(plain_action);
 534
 535            // Add an alternative for actions with data specified as a [name, data] array.
 536            //
 537            // When a struct with no deserializable fields is added by deriving `Action`, an empty
 538            // object schema is produced. The action should be invoked without data in this case.
 539            if let Some(schema) = action_schema
 540                && schema != empty_object
 541            {
 542                let mut matches_action_name = json_schema!({
 543                    "const": name
 544                });
 545                if let Some(desc) = description.clone() {
 546                    add_description(&mut matches_action_name, desc);
 547                }
 548                if let Some(message) = deprecation_messages.get(name) {
 549                    add_deprecation(&mut matches_action_name, message.to_string());
 550                } else if let Some(new_name) = deprecation {
 551                    add_deprecation_preferred_name(&mut matches_action_name, new_name);
 552                }
 553                let action_with_input = json_schema!({
 554                    "type": "array",
 555                    "items": [matches_action_name, schema],
 556                    "minItems": 2,
 557                    "maxItems": 2
 558                });
 559                keymap_action_alternatives.push(action_with_input);
 560            }
 561        }
 562
 563        // Placing null first causes json-language-server to default assuming actions should be
 564        // null, so place it last.
 565        keymap_action_alternatives.push(json_schema!({
 566            "type": "null"
 567        }));
 568
 569        // The `KeymapSection` schema will reference the `KeymapAction` schema by name, so setting
 570        // the definition of `KeymapAction` results in the full action schema being used.
 571        generator.definitions_mut().insert(
 572            KeymapAction::schema_name().to_string(),
 573            json!({
 574                "oneOf": keymap_action_alternatives
 575            }),
 576        );
 577
 578        generator.root_schema_for::<KeymapFile>().to_value()
 579    }
 580
 581    pub fn sections(&self) -> impl DoubleEndedIterator<Item = &KeymapSection> {
 582        self.0.iter()
 583    }
 584
 585    pub async fn load_keymap_file(fs: &Arc<dyn Fs>) -> Result<String> {
 586        match fs.load(paths::keymap_file()).await {
 587            result @ Ok(_) => result,
 588            Err(err) => {
 589                if let Some(e) = err.downcast_ref::<std::io::Error>()
 590                    && e.kind() == std::io::ErrorKind::NotFound
 591                {
 592                    return Ok(crate::initial_keymap_content().to_string());
 593                }
 594                Err(err)
 595            }
 596        }
 597    }
 598
 599    pub fn update_keybinding<'a>(
 600        mut operation: KeybindUpdateOperation<'a>,
 601        mut keymap_contents: String,
 602        tab_size: usize,
 603        keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
 604    ) -> Result<String> {
 605        match operation {
 606            // if trying to replace a keybinding that is not user-defined, treat it as an add operation
 607            KeybindUpdateOperation::Replace {
 608                target_keybind_source: target_source,
 609                source,
 610                target,
 611            } if target_source != KeybindSource::User => {
 612                operation = KeybindUpdateOperation::Add {
 613                    source,
 614                    from: Some(target),
 615                };
 616            }
 617            // if trying to remove a keybinding that is not user-defined, treat it as creating a binding
 618            // that binds it to `zed::NoAction`
 619            KeybindUpdateOperation::Remove {
 620                target,
 621                target_keybind_source,
 622            } if target_keybind_source != KeybindSource::User => {
 623                let mut source = target.clone();
 624                source.action_name = gpui::NoAction.name();
 625                source.action_arguments.take();
 626                operation = KeybindUpdateOperation::Add {
 627                    source,
 628                    from: Some(target),
 629                };
 630            }
 631            _ => {}
 632        }
 633
 634        // Sanity check that keymap contents are valid, even though we only use it for Replace.
 635        // We don't want to modify the file if it's invalid.
 636        let keymap = Self::parse(&keymap_contents).context("Failed to parse keymap")?;
 637
 638        if let KeybindUpdateOperation::Remove { target, .. } = operation {
 639            let target_action_value = target
 640                .action_value()
 641                .context("Failed to generate target action JSON value")?;
 642            let Some((index, keystrokes_str)) =
 643                find_binding(&keymap, &target, &target_action_value, keyboard_mapper)
 644            else {
 645                anyhow::bail!("Failed to find keybinding to remove");
 646            };
 647            let is_only_binding = keymap.0[index]
 648                .bindings
 649                .as_ref()
 650                .is_none_or(|bindings| bindings.len() == 1);
 651            let key_path: &[&str] = if is_only_binding {
 652                &[]
 653            } else {
 654                &["bindings", keystrokes_str]
 655            };
 656            let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
 657                &keymap_contents,
 658                key_path,
 659                None,
 660                None,
 661                index,
 662                tab_size,
 663            )
 664            .context("Failed to remove keybinding")?;
 665            keymap_contents.replace_range(replace_range, &replace_value);
 666            return Ok(keymap_contents);
 667        }
 668
 669        if let KeybindUpdateOperation::Replace { source, target, .. } = operation {
 670            let target_action_value = target
 671                .action_value()
 672                .context("Failed to generate target action JSON value")?;
 673            let source_action_value = source
 674                .action_value()
 675                .context("Failed to generate source action JSON value")?;
 676
 677            if let Some((index, keystrokes_str)) =
 678                find_binding(&keymap, &target, &target_action_value, keyboard_mapper)
 679            {
 680                if target.context == source.context {
 681                    // if we are only changing the keybinding (common case)
 682                    // not the context, etc. Then just update the binding in place
 683
 684                    let (replace_range, replace_value) =
 685                        replace_top_level_array_value_in_json_text(
 686                            &keymap_contents,
 687                            &["bindings", keystrokes_str],
 688                            Some(&source_action_value),
 689                            Some(&source.keystrokes_unparsed()),
 690                            index,
 691                            tab_size,
 692                        )
 693                        .context("Failed to replace keybinding")?;
 694                    keymap_contents.replace_range(replace_range, &replace_value);
 695
 696                    return Ok(keymap_contents);
 697                } else if keymap.0[index]
 698                    .bindings
 699                    .as_ref()
 700                    .is_none_or(|bindings| bindings.len() == 1)
 701                {
 702                    // if we are replacing the only binding in the section,
 703                    // just update the section in place, updating the context
 704                    // and the binding
 705
 706                    let (replace_range, replace_value) =
 707                        replace_top_level_array_value_in_json_text(
 708                            &keymap_contents,
 709                            &["bindings", keystrokes_str],
 710                            Some(&source_action_value),
 711                            Some(&source.keystrokes_unparsed()),
 712                            index,
 713                            tab_size,
 714                        )
 715                        .context("Failed to replace keybinding")?;
 716                    keymap_contents.replace_range(replace_range, &replace_value);
 717
 718                    let (replace_range, replace_value) =
 719                        replace_top_level_array_value_in_json_text(
 720                            &keymap_contents,
 721                            &["context"],
 722                            source.context.map(Into::into).as_ref(),
 723                            None,
 724                            index,
 725                            tab_size,
 726                        )
 727                        .context("Failed to replace keybinding")?;
 728                    keymap_contents.replace_range(replace_range, &replace_value);
 729                    return Ok(keymap_contents);
 730                } else {
 731                    // if we are replacing one of multiple bindings in a section
 732                    // with a context change, remove the existing binding from the
 733                    // section, then treat this operation as an add operation of the
 734                    // new binding with the updated context.
 735
 736                    let (replace_range, replace_value) =
 737                        replace_top_level_array_value_in_json_text(
 738                            &keymap_contents,
 739                            &["bindings", keystrokes_str],
 740                            None,
 741                            None,
 742                            index,
 743                            tab_size,
 744                        )
 745                        .context("Failed to replace keybinding")?;
 746                    keymap_contents.replace_range(replace_range, &replace_value);
 747                    operation = KeybindUpdateOperation::Add {
 748                        source,
 749                        from: Some(target),
 750                    };
 751                }
 752            } else {
 753                log::warn!(
 754                    "Failed to find keybinding to update `{:?} -> {}` creating new binding for `{:?} -> {}` instead",
 755                    target.keystrokes,
 756                    target_action_value,
 757                    source.keystrokes,
 758                    source_action_value,
 759                );
 760                operation = KeybindUpdateOperation::Add {
 761                    source,
 762                    from: Some(target),
 763                };
 764            }
 765        }
 766
 767        if let KeybindUpdateOperation::Add {
 768            source: keybinding,
 769            from,
 770        } = operation
 771        {
 772            let mut value = serde_json::Map::with_capacity(4);
 773            if let Some(context) = keybinding.context {
 774                value.insert("context".to_string(), context.into());
 775            }
 776            let use_key_equivalents = from.and_then(|from| {
 777                let action_value = from.action_value().context("Failed to serialize action value. `use_key_equivalents` on new keybinding may be incorrect.").log_err()?;
 778                let (index, _) = find_binding(&keymap, &from, &action_value, keyboard_mapper)?;
 779                Some(keymap.0[index].use_key_equivalents)
 780            }).unwrap_or(false);
 781            if use_key_equivalents {
 782                value.insert("use_key_equivalents".to_string(), true.into());
 783            }
 784
 785            value.insert("bindings".to_string(), {
 786                let mut bindings = serde_json::Map::new();
 787                let action = keybinding.action_value()?;
 788                bindings.insert(keybinding.keystrokes_unparsed(), action);
 789                bindings.into()
 790            });
 791
 792            let (replace_range, replace_value) = append_top_level_array_value_in_json_text(
 793                &keymap_contents,
 794                &value.into(),
 795                tab_size,
 796            )?;
 797            keymap_contents.replace_range(replace_range, &replace_value);
 798        }
 799        return Ok(keymap_contents);
 800
 801        fn find_binding<'a, 'b>(
 802            keymap: &'b KeymapFile,
 803            target: &KeybindUpdateTarget<'a>,
 804            target_action_value: &Value,
 805            keyboard_mapper: &dyn gpui::PlatformKeyboardMapper,
 806        ) -> Option<(usize, &'b str)> {
 807            let target_context_parsed =
 808                KeyBindingContextPredicate::parse(target.context.unwrap_or("")).ok();
 809            for (index, section) in keymap.sections().enumerate() {
 810                let section_context_parsed =
 811                    KeyBindingContextPredicate::parse(&section.context).ok();
 812                if section_context_parsed != target_context_parsed {
 813                    continue;
 814                }
 815                let Some(bindings) = &section.bindings else {
 816                    continue;
 817                };
 818                for (keystrokes_str, action) in bindings {
 819                    let Ok(keystrokes) = keystrokes_str
 820                        .split_whitespace()
 821                        .map(|source| {
 822                            let keystroke = Keystroke::parse(source)?;
 823                            Ok(KeybindingKeystroke::new(keystroke, false, keyboard_mapper))
 824                        })
 825                        .collect::<Result<Vec<_>, InvalidKeystrokeError>>()
 826                    else {
 827                        continue;
 828                    };
 829                    if keystrokes.len() != target.keystrokes.len()
 830                        || !keystrokes
 831                            .iter()
 832                            .zip(target.keystrokes)
 833                            .all(|(a, b)| a.inner.should_match(b))
 834                    {
 835                        continue;
 836                    }
 837                    if &action.0 != target_action_value {
 838                        continue;
 839                    }
 840                    return Some((index, keystrokes_str));
 841                }
 842            }
 843            None
 844        }
 845    }
 846}
 847
 848#[derive(Clone, Debug)]
 849pub enum KeybindUpdateOperation<'a> {
 850    Replace {
 851        /// Describes the keybind to create
 852        source: KeybindUpdateTarget<'a>,
 853        /// Describes the keybind to remove
 854        target: KeybindUpdateTarget<'a>,
 855        target_keybind_source: KeybindSource,
 856    },
 857    Add {
 858        source: KeybindUpdateTarget<'a>,
 859        from: Option<KeybindUpdateTarget<'a>>,
 860    },
 861    Remove {
 862        target: KeybindUpdateTarget<'a>,
 863        target_keybind_source: KeybindSource,
 864    },
 865}
 866
 867impl KeybindUpdateOperation<'_> {
 868    pub fn generate_telemetry(
 869        &self,
 870    ) -> (
 871        // The keybind that is created
 872        String,
 873        // The keybinding that was removed
 874        String,
 875        // The source of the keybinding
 876        String,
 877    ) {
 878        let (new_binding, removed_binding, source) = match &self {
 879            KeybindUpdateOperation::Replace {
 880                source,
 881                target,
 882                target_keybind_source,
 883            } => (Some(source), Some(target), Some(*target_keybind_source)),
 884            KeybindUpdateOperation::Add { source, .. } => (Some(source), None, None),
 885            KeybindUpdateOperation::Remove {
 886                target,
 887                target_keybind_source,
 888            } => (None, Some(target), Some(*target_keybind_source)),
 889        };
 890
 891        let new_binding = new_binding
 892            .map(KeybindUpdateTarget::telemetry_string)
 893            .unwrap_or("null".to_owned());
 894        let removed_binding = removed_binding
 895            .map(KeybindUpdateTarget::telemetry_string)
 896            .unwrap_or("null".to_owned());
 897
 898        let source = source
 899            .as_ref()
 900            .map(KeybindSource::name)
 901            .map(ToOwned::to_owned)
 902            .unwrap_or("null".to_owned());
 903
 904        (new_binding, removed_binding, source)
 905    }
 906}
 907
 908impl<'a> KeybindUpdateOperation<'a> {
 909    pub fn add(source: KeybindUpdateTarget<'a>) -> Self {
 910        Self::Add { source, from: None }
 911    }
 912}
 913
 914#[derive(Debug, Clone)]
 915pub struct KeybindUpdateTarget<'a> {
 916    pub context: Option<&'a str>,
 917    pub keystrokes: &'a [KeybindingKeystroke],
 918    pub action_name: &'a str,
 919    pub action_arguments: Option<&'a str>,
 920}
 921
 922impl<'a> KeybindUpdateTarget<'a> {
 923    fn action_value(&self) -> Result<Value> {
 924        if self.action_name == gpui::NoAction.name() {
 925            return Ok(Value::Null);
 926        }
 927        let action_name: Value = self.action_name.into();
 928        let value = match self.action_arguments {
 929            Some(args) if !args.is_empty() => {
 930                let args = serde_json::from_str::<Value>(args)
 931                    .context("Failed to parse action arguments as JSON")?;
 932                serde_json::json!([action_name, args])
 933            }
 934            _ => action_name,
 935        };
 936        Ok(value)
 937    }
 938
 939    fn keystrokes_unparsed(&self) -> String {
 940        let mut keystrokes = String::with_capacity(self.keystrokes.len() * 8);
 941        for keystroke in self.keystrokes {
 942            // The reason use `keystroke.unparse()` instead of `keystroke.inner.unparse()`
 943            // here is that, we want the user to use `ctrl-shift-4` instead of `ctrl-$`
 944            // by default on Windows.
 945            keystrokes.push_str(&keystroke.unparse());
 946            keystrokes.push(' ');
 947        }
 948        keystrokes.pop();
 949        keystrokes
 950    }
 951
 952    fn telemetry_string(&self) -> String {
 953        format!(
 954            "action_name: {}, context: {}, action_arguments: {}, keystrokes: {}",
 955            self.action_name,
 956            self.context.unwrap_or("global"),
 957            self.action_arguments.unwrap_or("none"),
 958            self.keystrokes_unparsed()
 959        )
 960    }
 961}
 962
 963#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
 964pub enum KeybindSource {
 965    User,
 966    Vim,
 967    Base,
 968    #[default]
 969    Default,
 970    Unknown,
 971}
 972
 973impl KeybindSource {
 974    const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::Base as u32);
 975    const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::Default as u32);
 976    const VIM: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::Vim as u32);
 977    const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(KeybindSource::User as u32);
 978
 979    pub fn name(&self) -> &'static str {
 980        match self {
 981            KeybindSource::User => "User",
 982            KeybindSource::Default => "Default",
 983            KeybindSource::Base => "Base",
 984            KeybindSource::Vim => "Vim",
 985            KeybindSource::Unknown => "Unknown",
 986        }
 987    }
 988
 989    pub fn meta(&self) -> KeyBindingMetaIndex {
 990        match self {
 991            KeybindSource::User => Self::USER,
 992            KeybindSource::Default => Self::DEFAULT,
 993            KeybindSource::Base => Self::BASE,
 994            KeybindSource::Vim => Self::VIM,
 995            KeybindSource::Unknown => KeyBindingMetaIndex(*self as u32),
 996        }
 997    }
 998
 999    pub fn from_meta(index: KeyBindingMetaIndex) -> Self {
1000        match index {
1001            Self::USER => KeybindSource::User,
1002            Self::BASE => KeybindSource::Base,
1003            Self::DEFAULT => KeybindSource::Default,
1004            Self::VIM => KeybindSource::Vim,
1005            _ => KeybindSource::Unknown,
1006        }
1007    }
1008}
1009
1010impl From<KeyBindingMetaIndex> for KeybindSource {
1011    fn from(index: KeyBindingMetaIndex) -> Self {
1012        Self::from_meta(index)
1013    }
1014}
1015
1016impl From<KeybindSource> for KeyBindingMetaIndex {
1017    fn from(source: KeybindSource) -> Self {
1018        source.meta()
1019    }
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024    use gpui::{DummyKeyboardMapper, KeybindingKeystroke, Keystroke};
1025    use unindent::Unindent;
1026
1027    use crate::{
1028        KeybindSource, KeymapFile,
1029        keymap_file::{KeybindUpdateOperation, KeybindUpdateTarget},
1030    };
1031
1032    #[test]
1033    fn can_deserialize_keymap_with_trailing_comma() {
1034        let json = indoc::indoc! {"[
1035              // Standard macOS bindings
1036              {
1037                \"bindings\": {
1038                  \"up\": \"menu::SelectPrevious\",
1039                },
1040              },
1041            ]
1042                  "
1043        };
1044        KeymapFile::parse(json).unwrap();
1045    }
1046
1047    #[track_caller]
1048    fn check_keymap_update(
1049        input: impl ToString,
1050        operation: KeybindUpdateOperation,
1051        expected: impl ToString,
1052    ) {
1053        let result = KeymapFile::update_keybinding(
1054            operation,
1055            input.to_string(),
1056            4,
1057            &gpui::DummyKeyboardMapper,
1058        )
1059        .expect("Update succeeded");
1060        pretty_assertions::assert_eq!(expected.to_string(), result);
1061    }
1062
1063    #[track_caller]
1064    fn parse_keystrokes(keystrokes: &str) -> Vec<KeybindingKeystroke> {
1065        keystrokes
1066            .split(' ')
1067            .map(|s| {
1068                KeybindingKeystroke::new(
1069                    Keystroke::parse(s).expect("Keystrokes valid"),
1070                    false,
1071                    &DummyKeyboardMapper,
1072                )
1073            })
1074            .collect()
1075    }
1076
1077    #[test]
1078    fn keymap_update() {
1079        zlog::init_test();
1080
1081        check_keymap_update(
1082            "[]",
1083            KeybindUpdateOperation::add(KeybindUpdateTarget {
1084                keystrokes: &parse_keystrokes("ctrl-a"),
1085                action_name: "zed::SomeAction",
1086                context: None,
1087                action_arguments: None,
1088            }),
1089            r#"[
1090                {
1091                    "bindings": {
1092                        "ctrl-a": "zed::SomeAction"
1093                    }
1094                }
1095            ]"#
1096            .unindent(),
1097        );
1098
1099        check_keymap_update(
1100            "[]",
1101            KeybindUpdateOperation::add(KeybindUpdateTarget {
1102                keystrokes: &parse_keystrokes("ctrl-a"),
1103                action_name: "zed::SomeAction",
1104                context: None,
1105                action_arguments: Some(""),
1106            }),
1107            r#"[
1108                {
1109                    "bindings": {
1110                        "ctrl-a": "zed::SomeAction"
1111                    }
1112                }
1113            ]"#
1114            .unindent(),
1115        );
1116
1117        check_keymap_update(
1118            r#"[
1119                {
1120                    "bindings": {
1121                        "ctrl-a": "zed::SomeAction"
1122                    }
1123                }
1124            ]"#
1125            .unindent(),
1126            KeybindUpdateOperation::add(KeybindUpdateTarget {
1127                keystrokes: &parse_keystrokes("ctrl-b"),
1128                action_name: "zed::SomeOtherAction",
1129                context: None,
1130                action_arguments: None,
1131            }),
1132            r#"[
1133                {
1134                    "bindings": {
1135                        "ctrl-a": "zed::SomeAction"
1136                    }
1137                },
1138                {
1139                    "bindings": {
1140                        "ctrl-b": "zed::SomeOtherAction"
1141                    }
1142                }
1143            ]"#
1144            .unindent(),
1145        );
1146
1147        check_keymap_update(
1148            r#"[
1149                {
1150                    "bindings": {
1151                        "ctrl-a": "zed::SomeAction"
1152                    }
1153                }
1154            ]"#
1155            .unindent(),
1156            KeybindUpdateOperation::add(KeybindUpdateTarget {
1157                keystrokes: &parse_keystrokes("ctrl-b"),
1158                action_name: "zed::SomeOtherAction",
1159                context: None,
1160                action_arguments: Some(r#"{"foo": "bar"}"#),
1161            }),
1162            r#"[
1163                {
1164                    "bindings": {
1165                        "ctrl-a": "zed::SomeAction"
1166                    }
1167                },
1168                {
1169                    "bindings": {
1170                        "ctrl-b": [
1171                            "zed::SomeOtherAction",
1172                            {
1173                                "foo": "bar"
1174                            }
1175                        ]
1176                    }
1177                }
1178            ]"#
1179            .unindent(),
1180        );
1181
1182        check_keymap_update(
1183            r#"[
1184                {
1185                    "bindings": {
1186                        "ctrl-a": "zed::SomeAction"
1187                    }
1188                }
1189            ]"#
1190            .unindent(),
1191            KeybindUpdateOperation::add(KeybindUpdateTarget {
1192                keystrokes: &parse_keystrokes("ctrl-b"),
1193                action_name: "zed::SomeOtherAction",
1194                context: Some("Zed > Editor && some_condition = true"),
1195                action_arguments: Some(r#"{"foo": "bar"}"#),
1196            }),
1197            r#"[
1198                {
1199                    "bindings": {
1200                        "ctrl-a": "zed::SomeAction"
1201                    }
1202                },
1203                {
1204                    "context": "Zed > Editor && some_condition = true",
1205                    "bindings": {
1206                        "ctrl-b": [
1207                            "zed::SomeOtherAction",
1208                            {
1209                                "foo": "bar"
1210                            }
1211                        ]
1212                    }
1213                }
1214            ]"#
1215            .unindent(),
1216        );
1217
1218        check_keymap_update(
1219            r#"[
1220                {
1221                    "bindings": {
1222                        "ctrl-a": "zed::SomeAction"
1223                    }
1224                }
1225            ]"#
1226            .unindent(),
1227            KeybindUpdateOperation::Replace {
1228                target: KeybindUpdateTarget {
1229                    keystrokes: &parse_keystrokes("ctrl-a"),
1230                    action_name: "zed::SomeAction",
1231                    context: None,
1232                    action_arguments: None,
1233                },
1234                source: KeybindUpdateTarget {
1235                    keystrokes: &parse_keystrokes("ctrl-b"),
1236                    action_name: "zed::SomeOtherAction",
1237                    context: None,
1238                    action_arguments: Some(r#"{"foo": "bar"}"#),
1239                },
1240                target_keybind_source: KeybindSource::Base,
1241            },
1242            r#"[
1243                {
1244                    "bindings": {
1245                        "ctrl-a": "zed::SomeAction"
1246                    }
1247                },
1248                {
1249                    "bindings": {
1250                        "ctrl-b": [
1251                            "zed::SomeOtherAction",
1252                            {
1253                                "foo": "bar"
1254                            }
1255                        ]
1256                    }
1257                }
1258            ]"#
1259            .unindent(),
1260        );
1261
1262        check_keymap_update(
1263            r#"[
1264                {
1265                    "bindings": {
1266                        "a": "zed::SomeAction"
1267                    }
1268                }
1269            ]"#
1270            .unindent(),
1271            KeybindUpdateOperation::Replace {
1272                target: KeybindUpdateTarget {
1273                    keystrokes: &parse_keystrokes("a"),
1274                    action_name: "zed::SomeAction",
1275                    context: None,
1276                    action_arguments: None,
1277                },
1278                source: KeybindUpdateTarget {
1279                    keystrokes: &parse_keystrokes("ctrl-b"),
1280                    action_name: "zed::SomeOtherAction",
1281                    context: None,
1282                    action_arguments: Some(r#"{"foo": "bar"}"#),
1283                },
1284                target_keybind_source: KeybindSource::User,
1285            },
1286            r#"[
1287                {
1288                    "bindings": {
1289                        "ctrl-b": [
1290                            "zed::SomeOtherAction",
1291                            {
1292                                "foo": "bar"
1293                            }
1294                        ]
1295                    }
1296                }
1297            ]"#
1298            .unindent(),
1299        );
1300
1301        check_keymap_update(
1302            r#"[
1303                {
1304                    "bindings": {
1305                        "ctrl-a": "zed::SomeAction"
1306                    }
1307                }
1308            ]"#
1309            .unindent(),
1310            KeybindUpdateOperation::Replace {
1311                target: KeybindUpdateTarget {
1312                    keystrokes: &parse_keystrokes("ctrl-a"),
1313                    action_name: "zed::SomeNonexistentAction",
1314                    context: None,
1315                    action_arguments: None,
1316                },
1317                source: KeybindUpdateTarget {
1318                    keystrokes: &parse_keystrokes("ctrl-b"),
1319                    action_name: "zed::SomeOtherAction",
1320                    context: None,
1321                    action_arguments: None,
1322                },
1323                target_keybind_source: KeybindSource::User,
1324            },
1325            r#"[
1326                {
1327                    "bindings": {
1328                        "ctrl-a": "zed::SomeAction"
1329                    }
1330                },
1331                {
1332                    "bindings": {
1333                        "ctrl-b": "zed::SomeOtherAction"
1334                    }
1335                }
1336            ]"#
1337            .unindent(),
1338        );
1339
1340        check_keymap_update(
1341            r#"[
1342                {
1343                    "bindings": {
1344                        // some comment
1345                        "ctrl-a": "zed::SomeAction"
1346                        // some other comment
1347                    }
1348                }
1349            ]"#
1350            .unindent(),
1351            KeybindUpdateOperation::Replace {
1352                target: KeybindUpdateTarget {
1353                    keystrokes: &parse_keystrokes("ctrl-a"),
1354                    action_name: "zed::SomeAction",
1355                    context: None,
1356                    action_arguments: None,
1357                },
1358                source: KeybindUpdateTarget {
1359                    keystrokes: &parse_keystrokes("ctrl-b"),
1360                    action_name: "zed::SomeOtherAction",
1361                    context: None,
1362                    action_arguments: Some(r#"{"foo": "bar"}"#),
1363                },
1364                target_keybind_source: KeybindSource::User,
1365            },
1366            r#"[
1367                {
1368                    "bindings": {
1369                        // some comment
1370                        "ctrl-b": [
1371                            "zed::SomeOtherAction",
1372                            {
1373                                "foo": "bar"
1374                            }
1375                        ]
1376                        // some other comment
1377                    }
1378                }
1379            ]"#
1380            .unindent(),
1381        );
1382
1383        check_keymap_update(
1384            r#"[
1385                {
1386                    "context": "SomeContext",
1387                    "bindings": {
1388                        "a": "foo::bar",
1389                        "b": "baz::qux",
1390                    }
1391                }
1392            ]"#
1393            .unindent(),
1394            KeybindUpdateOperation::Replace {
1395                target: KeybindUpdateTarget {
1396                    keystrokes: &parse_keystrokes("a"),
1397                    action_name: "foo::bar",
1398                    context: Some("SomeContext"),
1399                    action_arguments: None,
1400                },
1401                source: KeybindUpdateTarget {
1402                    keystrokes: &parse_keystrokes("c"),
1403                    action_name: "foo::baz",
1404                    context: Some("SomeOtherContext"),
1405                    action_arguments: None,
1406                },
1407                target_keybind_source: KeybindSource::User,
1408            },
1409            r#"[
1410                {
1411                    "context": "SomeContext",
1412                    "bindings": {
1413                        "b": "baz::qux",
1414                    }
1415                },
1416                {
1417                    "context": "SomeOtherContext",
1418                    "bindings": {
1419                        "c": "foo::baz"
1420                    }
1421                }
1422            ]"#
1423            .unindent(),
1424        );
1425
1426        check_keymap_update(
1427            r#"[
1428                {
1429                    "context": "SomeContext",
1430                    "bindings": {
1431                        "a": "foo::bar",
1432                    }
1433                }
1434            ]"#
1435            .unindent(),
1436            KeybindUpdateOperation::Replace {
1437                target: KeybindUpdateTarget {
1438                    keystrokes: &parse_keystrokes("a"),
1439                    action_name: "foo::bar",
1440                    context: Some("SomeContext"),
1441                    action_arguments: None,
1442                },
1443                source: KeybindUpdateTarget {
1444                    keystrokes: &parse_keystrokes("c"),
1445                    action_name: "foo::baz",
1446                    context: Some("SomeOtherContext"),
1447                    action_arguments: None,
1448                },
1449                target_keybind_source: KeybindSource::User,
1450            },
1451            r#"[
1452                {
1453                    "context": "SomeOtherContext",
1454                    "bindings": {
1455                        "c": "foo::baz",
1456                    }
1457                }
1458            ]"#
1459            .unindent(),
1460        );
1461
1462        check_keymap_update(
1463            r#"[
1464                {
1465                    "context": "SomeContext",
1466                    "bindings": {
1467                        "a": "foo::bar",
1468                        "c": "foo::baz",
1469                    }
1470                },
1471            ]"#
1472            .unindent(),
1473            KeybindUpdateOperation::Remove {
1474                target: KeybindUpdateTarget {
1475                    context: Some("SomeContext"),
1476                    keystrokes: &parse_keystrokes("a"),
1477                    action_name: "foo::bar",
1478                    action_arguments: None,
1479                },
1480                target_keybind_source: KeybindSource::User,
1481            },
1482            r#"[
1483                {
1484                    "context": "SomeContext",
1485                    "bindings": {
1486                        "c": "foo::baz",
1487                    }
1488                },
1489            ]"#
1490            .unindent(),
1491        );
1492
1493        check_keymap_update(
1494            r#"[
1495                {
1496                    "context": "SomeContext",
1497                    "bindings": {
1498                        "a": ["foo::bar", true],
1499                        "c": "foo::baz",
1500                    }
1501                },
1502            ]"#
1503            .unindent(),
1504            KeybindUpdateOperation::Remove {
1505                target: KeybindUpdateTarget {
1506                    context: Some("SomeContext"),
1507                    keystrokes: &parse_keystrokes("a"),
1508                    action_name: "foo::bar",
1509                    action_arguments: Some("true"),
1510                },
1511                target_keybind_source: KeybindSource::User,
1512            },
1513            r#"[
1514                {
1515                    "context": "SomeContext",
1516                    "bindings": {
1517                        "c": "foo::baz",
1518                    }
1519                },
1520            ]"#
1521            .unindent(),
1522        );
1523
1524        check_keymap_update(
1525            r#"[
1526                {
1527                    "context": "SomeContext",
1528                    "bindings": {
1529                        "b": "foo::baz",
1530                    }
1531                },
1532                {
1533                    "context": "SomeContext",
1534                    "bindings": {
1535                        "a": ["foo::bar", true],
1536                    }
1537                },
1538                {
1539                    "context": "SomeContext",
1540                    "bindings": {
1541                        "c": "foo::baz",
1542                    }
1543                },
1544            ]"#
1545            .unindent(),
1546            KeybindUpdateOperation::Remove {
1547                target: KeybindUpdateTarget {
1548                    context: Some("SomeContext"),
1549                    keystrokes: &parse_keystrokes("a"),
1550                    action_name: "foo::bar",
1551                    action_arguments: Some("true"),
1552                },
1553                target_keybind_source: KeybindSource::User,
1554            },
1555            r#"[
1556                {
1557                    "context": "SomeContext",
1558                    "bindings": {
1559                        "b": "foo::baz",
1560                    }
1561                },
1562                {
1563                    "context": "SomeContext",
1564                    "bindings": {
1565                        "c": "foo::baz",
1566                    }
1567                },
1568            ]"#
1569            .unindent(),
1570        );
1571        check_keymap_update(
1572            r#"[
1573                {
1574                    "context": "SomeOtherContext",
1575                    "use_key_equivalents": true,
1576                    "bindings": {
1577                        "b": "foo::bar",
1578                    }
1579                },
1580            ]"#
1581            .unindent(),
1582            KeybindUpdateOperation::Add {
1583                source: KeybindUpdateTarget {
1584                    context: Some("SomeContext"),
1585                    keystrokes: &parse_keystrokes("a"),
1586                    action_name: "foo::baz",
1587                    action_arguments: Some("true"),
1588                },
1589                from: Some(KeybindUpdateTarget {
1590                    context: Some("SomeOtherContext"),
1591                    keystrokes: &parse_keystrokes("b"),
1592                    action_name: "foo::bar",
1593                    action_arguments: None,
1594                }),
1595            },
1596            r#"[
1597                {
1598                    "context": "SomeOtherContext",
1599                    "use_key_equivalents": true,
1600                    "bindings": {
1601                        "b": "foo::bar",
1602                    }
1603                },
1604                {
1605                    "context": "SomeContext",
1606                    "use_key_equivalents": true,
1607                    "bindings": {
1608                        "a": [
1609                            "foo::baz",
1610                            true
1611                        ]
1612                    }
1613                }
1614            ]"#
1615            .unindent(),
1616        );
1617
1618        check_keymap_update(
1619            r#"[
1620                {
1621                    "context": "SomeOtherContext",
1622                    "use_key_equivalents": true,
1623                    "bindings": {
1624                        "b": "foo::bar",
1625                    }
1626                },
1627            ]"#
1628            .unindent(),
1629            KeybindUpdateOperation::Remove {
1630                target: KeybindUpdateTarget {
1631                    context: Some("SomeContext"),
1632                    keystrokes: &parse_keystrokes("a"),
1633                    action_name: "foo::baz",
1634                    action_arguments: Some("true"),
1635                },
1636                target_keybind_source: KeybindSource::Default,
1637            },
1638            r#"[
1639                {
1640                    "context": "SomeOtherContext",
1641                    "use_key_equivalents": true,
1642                    "bindings": {
1643                        "b": "foo::bar",
1644                    }
1645                },
1646                {
1647                    "context": "SomeContext",
1648                    "bindings": {
1649                        "a": null
1650                    }
1651                }
1652            ]"#
1653            .unindent(),
1654        );
1655    }
1656
1657    #[test]
1658    fn test_keymap_remove() {
1659        zlog::init_test();
1660
1661        check_keymap_update(
1662            r#"
1663            [
1664              {
1665                "context": "Editor",
1666                "bindings": {
1667                  "cmd-k cmd-u": "editor::ConvertToUpperCase",
1668                  "cmd-k cmd-l": "editor::ConvertToLowerCase",
1669                  "cmd-[": "pane::GoBack",
1670                }
1671              },
1672            ]
1673            "#,
1674            KeybindUpdateOperation::Remove {
1675                target: KeybindUpdateTarget {
1676                    context: Some("Editor"),
1677                    keystrokes: &parse_keystrokes("cmd-k cmd-l"),
1678                    action_name: "editor::ConvertToLowerCase",
1679                    action_arguments: None,
1680                },
1681                target_keybind_source: KeybindSource::User,
1682            },
1683            r#"
1684            [
1685              {
1686                "context": "Editor",
1687                "bindings": {
1688                  "cmd-k cmd-u": "editor::ConvertToUpperCase",
1689                  "cmd-[": "pane::GoBack",
1690                }
1691              },
1692            ]
1693            "#,
1694        );
1695    }
1696}