keymap_file.rs

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