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