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::{
  14    asset_str,
  15    markdown::{MarkdownEscaped, MarkdownInlineCode, MarkdownString},
  16};
  17
  18use crate::{
  19    SettingsAssets, append_top_level_array_value_in_json_text, parse_json_with_comments,
  20    replace_top_level_array_value_in_json_text,
  21};
  22
  23pub trait KeyBindingValidator: Send + Sync {
  24    fn action_type_id(&self) -> TypeId;
  25    fn validate(&self, binding: &KeyBinding) -> Result<(), MarkdownString>;
  26}
  27
  28pub struct KeyBindingValidatorRegistration(pub fn() -> Box<dyn KeyBindingValidator>);
  29
  30inventory::collect!(KeyBindingValidatorRegistration);
  31
  32pub(crate) static KEY_BINDING_VALIDATORS: LazyLock<BTreeMap<TypeId, Box<dyn KeyBindingValidator>>> =
  33    LazyLock::new(|| {
  34        let mut validators = BTreeMap::new();
  35        for validator_registration in inventory::iter::<KeyBindingValidatorRegistration> {
  36            let validator = validator_registration.0();
  37            validators.insert(validator.action_type_id(), validator);
  38        }
  39        validators
  40    });
  41
  42// Note that the doc comments on these are shown by json-language-server when editing the keymap, so
  43// they should be considered user-facing documentation. Documentation is not handled well with
  44// schemars-0.8 - when there are newlines, it is rendered as plaintext (see
  45// https://github.com/GREsau/schemars/issues/38#issuecomment-2282883519). So for now these docs
  46// avoid newlines.
  47//
  48// TODO: Update to schemars-1.0 once it's released, and add more docs as newlines would be
  49// supported. Tracking issue is https://github.com/GREsau/schemars/issues/112.
  50
  51/// Keymap configuration consisting of sections. Each section may have a context predicate which
  52/// determines whether its bindings are used.
  53#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
  54#[serde(transparent)]
  55pub struct KeymapFile(Vec<KeymapSection>);
  56
  57/// Keymap section which binds keystrokes to actions.
  58#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
  59pub struct KeymapSection {
  60    /// Determines when these bindings are active. When just a name is provided, like `Editor` or
  61    /// `Workspace`, the bindings will be active in that context. Boolean expressions like `X && Y`,
  62    /// `X || Y`, `!X` are also supported. Some more complex logic including checking OS and the
  63    /// current file extension are also supported - see [the
  64    /// documentation](https://zed.dev/docs/key-bindings#contexts) for more details.
  65    #[serde(default)]
  66    pub context: String,
  67    /// This option enables specifying keys based on their position on a QWERTY keyboard, by using
  68    /// position-equivalent mappings for some non-QWERTY keyboards. This is currently only supported
  69    /// on macOS. See the documentation for more details.
  70    #[serde(default)]
  71    use_key_equivalents: bool,
  72    /// This keymap section's bindings, as a JSON object mapping keystrokes to actions. The
  73    /// keystrokes key is a string representing a sequence of keystrokes to type, where the
  74    /// keystrokes are separated by whitespace. Each keystroke is a sequence of modifiers (`ctrl`,
  75    /// `alt`, `shift`, `fn`, `cmd`, `super`, or `win`) followed by a key, separated by `-`. The
  76    /// order of bindings does matter. When the same keystrokes are bound at the same context depth,
  77    /// the binding that occurs later in the file is preferred. For displaying keystrokes in the UI,
  78    /// the later binding for the same action is preferred.
  79    #[serde(default)]
  80    bindings: Option<IndexMap<String, KeymapAction>>,
  81    #[serde(flatten)]
  82    unrecognized_fields: IndexMap<String, Value>,
  83    // This struct intentionally uses permissive types for its fields, rather than validating during
  84    // deserialization. The purpose of this is to allow loading the portion of the keymap that doesn't
  85    // have errors. The downside of this is that the errors are not reported with line+column info.
  86    // Unfortunately the implementations of the `Spanned` types for preserving this information are
  87    // highly inconvenient (`serde_spanned`) and in some cases don't work at all here
  88    // (`json_spanned_>value`). Serde should really have builtin support for this.
  89}
  90
  91impl KeymapSection {
  92    pub fn bindings(&self) -> impl DoubleEndedIterator<Item = (&String, &KeymapAction)> {
  93        self.bindings.iter().flatten()
  94    }
  95}
  96
  97/// Keymap action as a JSON value, since it can either be null for no action, or the name of the
  98/// action, or an array of the name of the action and the action input.
  99///
 100/// Unlike the other json types involved in keymaps (including actions), this doc-comment will not
 101/// be included in the generated JSON schema, as it manually defines its `JsonSchema` impl. The
 102/// actual schema used for it is automatically generated in `KeymapFile::generate_json_schema`.
 103#[derive(Debug, Deserialize, Default, Clone)]
 104#[serde(transparent)]
 105pub struct KeymapAction(Value);
 106
 107impl std::fmt::Display for KeymapAction {
 108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 109        match &self.0 {
 110            Value::String(s) => write!(f, "{}", s),
 111            Value::Array(arr) => {
 112                let strings: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
 113                write!(f, "{}", strings.join(", "))
 114            }
 115            _ => write!(f, "{}", self.0),
 116        }
 117    }
 118}
 119
 120impl JsonSchema for KeymapAction {
 121    /// This is used when generating the JSON schema for the `KeymapAction` type, so that it can
 122    /// reference the keymap action schema.
 123    fn schema_name() -> Cow<'static, str> {
 124        "KeymapAction".into()
 125    }
 126
 127    /// This schema will be replaced with the full action schema in
 128    /// `KeymapFile::generate_json_schema`.
 129    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
 130        json_schema!(true)
 131    }
 132}
 133
 134#[derive(Debug)]
 135#[must_use]
 136pub enum KeymapFileLoadResult {
 137    Success {
 138        key_bindings: Vec<KeyBinding>,
 139    },
 140    SomeFailedToLoad {
 141        key_bindings: Vec<KeyBinding>,
 142        error_message: MarkdownString,
 143    },
 144    JsonParseFailure {
 145        error: anyhow::Error,
 146    },
 147}
 148
 149impl KeymapFile {
 150    pub fn parse(content: &str) -> anyhow::Result<Self> {
 151        parse_json_with_comments::<Self>(content)
 152    }
 153
 154    pub fn load_asset(
 155        asset_path: &str,
 156        source: Option<KeybindSource>,
 157        cx: &App,
 158    ) -> anyhow::Result<Vec<KeyBinding>> {
 159        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
 160            KeymapFileLoadResult::Success { mut key_bindings } => match source {
 161                Some(source) => Ok({
 162                    for key_binding in &mut key_bindings {
 163                        key_binding.set_meta(source.meta());
 164                    }
 165                    key_bindings
 166                }),
 167                None => Ok(key_bindings),
 168            },
 169            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => {
 170                anyhow::bail!("Error loading built-in keymap \"{asset_path}\": {error_message}",)
 171            }
 172            KeymapFileLoadResult::JsonParseFailure { error } => {
 173                anyhow::bail!("JSON parse error in built-in keymap \"{asset_path}\": {error}")
 174            }
 175        }
 176    }
 177
 178    #[cfg(feature = "test-support")]
 179    pub fn load_asset_allow_partial_failure(
 180        asset_path: &str,
 181        cx: &App,
 182    ) -> anyhow::Result<Vec<KeyBinding>> {
 183        match Self::load(asset_str::<SettingsAssets>(asset_path).as_ref(), cx) {
 184            KeymapFileLoadResult::SomeFailedToLoad {
 185                key_bindings,
 186                error_message,
 187                ..
 188            } if key_bindings.is_empty() => {
 189                anyhow::bail!("Error loading built-in keymap \"{asset_path}\": {error_message}",)
 190            }
 191            KeymapFileLoadResult::Success { key_bindings, .. }
 192            | KeymapFileLoadResult::SomeFailedToLoad { key_bindings, .. } => Ok(key_bindings),
 193            KeymapFileLoadResult::JsonParseFailure { error } => {
 194                anyhow::bail!("JSON parse error in built-in keymap \"{asset_path}\": {error}")
 195            }
 196        }
 197    }
 198
 199    #[cfg(feature = "test-support")]
 200    pub fn load_panic_on_failure(content: &str, cx: &App) -> Vec<KeyBinding> {
 201        match Self::load(content, cx) {
 202            KeymapFileLoadResult::Success { key_bindings, .. } => key_bindings,
 203            KeymapFileLoadResult::SomeFailedToLoad { error_message, .. } => {
 204                panic!("{error_message}");
 205            }
 206            KeymapFileLoadResult::JsonParseFailure { error } => {
 207                panic!("JSON parse error: {error}");
 208            }
 209        }
 210    }
 211
 212    pub fn load(content: &str, cx: &App) -> KeymapFileLoadResult {
 213        let key_equivalents =
 214            crate::key_equivalents::get_key_equivalents(cx.keyboard_layout().id());
 215
 216        if content.is_empty() {
 217            return KeymapFileLoadResult::Success {
 218                key_bindings: Vec::new(),
 219            };
 220        }
 221        let keymap_file = match Self::parse(content) {
 222            Ok(keymap_file) => keymap_file,
 223            Err(error) => {
 224                return KeymapFileLoadResult::JsonParseFailure { error };
 225            }
 226        };
 227
 228        // Accumulate errors in order to support partial load of user keymap in the presence of
 229        // errors in context and binding parsing.
 230        let mut errors = Vec::new();
 231        let mut key_bindings = Vec::new();
 232
 233        for KeymapSection {
 234            context,
 235            use_key_equivalents,
 236            bindings,
 237            unrecognized_fields,
 238        } in keymap_file.0.iter()
 239        {
 240            let context_predicate: Option<Rc<KeyBindingContextPredicate>> = if context.is_empty() {
 241                None
 242            } else {
 243                match KeyBindingContextPredicate::parse(context) {
 244                    Ok(context_predicate) => Some(context_predicate.into()),
 245                    Err(err) => {
 246                        // Leading space is to separate from the message indicating which section
 247                        // the error occurred in.
 248                        errors.push((
 249                            context,
 250                            format!(" Parse error in section `context` field: {}", err),
 251                        ));
 252                        continue;
 253                    }
 254                }
 255            };
 256
 257            let key_equivalents = if *use_key_equivalents {
 258                key_equivalents.as_ref()
 259            } else {
 260                None
 261            };
 262
 263            let mut section_errors = String::new();
 264
 265            if !unrecognized_fields.is_empty() {
 266                write!(
 267                    section_errors,
 268                    "\n\n - Unrecognized fields: {}",
 269                    MarkdownInlineCode(&format!("{:?}", unrecognized_fields.keys()))
 270                )
 271                .unwrap();
 272            }
 273
 274            if let Some(bindings) = bindings {
 275                for (keystrokes, action) in bindings {
 276                    let result = Self::load_keybinding(
 277                        keystrokes,
 278                        action,
 279                        context_predicate.clone(),
 280                        key_equivalents,
 281                        cx,
 282                    );
 283                    match result {
 284                        Ok(key_binding) => {
 285                            key_bindings.push(key_binding);
 286                        }
 287                        Err(err) => {
 288                            let mut lines = err.lines();
 289                            let mut indented_err = lines.next().unwrap().to_string();
 290                            for line in lines {
 291                                indented_err.push_str("  ");
 292                                indented_err.push_str(line);
 293                                indented_err.push_str("\n");
 294                            }
 295                            write!(
 296                                section_errors,
 297                                "\n\n- In binding {}, {indented_err}",
 298                                MarkdownInlineCode(&format!("\"{}\"", keystrokes))
 299                            )
 300                            .unwrap();
 301                        }
 302                    }
 303                }
 304            }
 305
 306            if !section_errors.is_empty() {
 307                errors.push((context, section_errors))
 308            }
 309        }
 310
 311        if errors.is_empty() {
 312            KeymapFileLoadResult::Success { key_bindings }
 313        } else {
 314            let mut error_message = "Errors in user keymap file.\n".to_owned();
 315            for (context, section_errors) in errors {
 316                if context.is_empty() {
 317                    let _ = write!(error_message, "\n\nIn section without context predicate:");
 318                } else {
 319                    let _ = write!(
 320                        error_message,
 321                        "\n\nIn section with {}:",
 322                        MarkdownInlineCode(&format!("context = \"{}\"", context))
 323                    );
 324                }
 325                let _ = write!(error_message, "{section_errors}");
 326            }
 327            KeymapFileLoadResult::SomeFailedToLoad {
 328                key_bindings,
 329                error_message: MarkdownString(error_message),
 330            }
 331        }
 332    }
 333
 334    fn load_keybinding(
 335        keystrokes: &str,
 336        action: &KeymapAction,
 337        context: Option<Rc<KeyBindingContextPredicate>>,
 338        key_equivalents: Option<&HashMap<char, char>>,
 339        cx: &App,
 340    ) -> std::result::Result<KeyBinding, String> {
 341        let (build_result, action_input_string) = match &action.0 {
 342            Value::Array(items) => {
 343                if items.len() != 2 {
 344                    return Err(format!(
 345                        "expected two-element array of `[name, input]`. \
 346                        Instead found {}.",
 347                        MarkdownInlineCode(&action.0.to_string())
 348                    ));
 349                }
 350                let serde_json::Value::String(ref name) = items[0] else {
 351                    return Err(format!(
 352                        "expected two-element array of `[name, input]`, \
 353                        but the first element is not a string in {}.",
 354                        MarkdownInlineCode(&action.0.to_string())
 355                    ));
 356                };
 357                let action_input = items[1].clone();
 358                let action_input_string = action_input.to_string();
 359                (
 360                    cx.build_action(&name, Some(action_input)),
 361                    Some(action_input_string),
 362                )
 363            }
 364            Value::String(name) => (cx.build_action(&name, None), None),
 365            Value::Null => (Ok(NoAction.boxed_clone()), None),
 366            _ => {
 367                return Err(format!(
 368                    "expected two-element array of `[name, input]`. \
 369                    Instead found {}.",
 370                    MarkdownInlineCode(&action.0.to_string())
 371                ));
 372            }
 373        };
 374
 375        let action = match build_result {
 376            Ok(action) => action,
 377            Err(ActionBuildError::NotFound { name }) => {
 378                return Err(format!(
 379                    "didn't find an action named {}.",
 380                    MarkdownInlineCode(&format!("\"{}\"", &name))
 381                ));
 382            }
 383            Err(ActionBuildError::BuildError { name, error }) => match action_input_string {
 384                Some(action_input_string) => {
 385                    return Err(format!(
 386                        "can't build {} action from input value {}: {}",
 387                        MarkdownInlineCode(&format!("\"{}\"", &name)),
 388                        MarkdownInlineCode(&action_input_string),
 389                        MarkdownEscaped(&error.to_string())
 390                    ));
 391                }
 392                None => {
 393                    return Err(format!(
 394                        "can't build {} action - it requires input data via [name, input]: {}",
 395                        MarkdownInlineCode(&format!("\"{}\"", &name)),
 396                        MarkdownEscaped(&error.to_string())
 397                    ));
 398                }
 399            },
 400        };
 401
 402        let key_binding = match KeyBinding::load(
 403            keystrokes,
 404            action,
 405            context,
 406            key_equivalents,
 407            action_input_string.map(SharedString::from),
 408        ) {
 409            Ok(key_binding) => key_binding,
 410            Err(InvalidKeystrokeError { keystroke }) => {
 411                return Err(format!(
 412                    "invalid keystroke {}. {}",
 413                    MarkdownInlineCode(&format!("\"{}\"", &keystroke)),
 414                    KEYSTROKE_PARSE_EXPECTED_MESSAGE
 415                ));
 416            }
 417        };
 418
 419        if let Some(validator) = KEY_BINDING_VALIDATORS.get(&key_binding.action().type_id()) {
 420            match validator.validate(&key_binding) {
 421                Ok(()) => Ok(key_binding),
 422                Err(error) => Err(error.0),
 423            }
 424        } else {
 425            Ok(key_binding)
 426        }
 427    }
 428
 429    /// Creates a JSON schema generator, suitable for generating json schemas
 430    /// for actions
 431    pub fn action_schema_generator() -> schemars::SchemaGenerator {
 432        schemars::generate::SchemaSettings::draft2019_09().into_generator()
 433    }
 434
 435    pub fn generate_json_schema_for_registered_actions(cx: &mut App) -> Value {
 436        // instead of using DefaultDenyUnknownFields, actions typically use
 437        // `#[serde(deny_unknown_fields)]` so that these cases are reported as parse failures. This
 438        // is because the rest of the keymap will still load in these cases, whereas other settings
 439        // files would not.
 440        let mut generator = Self::action_schema_generator();
 441
 442        let action_schemas = cx.action_schemas(&mut generator);
 443        let deprecations = cx.deprecated_actions_to_preferred_actions();
 444        let deprecation_messages = cx.action_deprecation_messages();
 445        KeymapFile::generate_json_schema(
 446            generator,
 447            action_schemas,
 448            deprecations,
 449            deprecation_messages,
 450        )
 451    }
 452
 453    fn generate_json_schema(
 454        mut generator: schemars::SchemaGenerator,
 455        action_schemas: Vec<(&'static str, Option<schemars::Schema>)>,
 456        deprecations: &HashMap<&'static str, &'static str>,
 457        deprecation_messages: &HashMap<&'static str, &'static str>,
 458    ) -> serde_json::Value {
 459        fn add_deprecation(schema: &mut schemars::Schema, message: String) {
 460            schema.insert(
 461                // deprecationMessage is not part of the JSON Schema spec, but
 462                // json-language-server recognizes it.
 463                "deprecationMessage".to_string(),
 464                Value::String(message),
 465            );
 466        }
 467
 468        fn add_deprecation_preferred_name(schema: &mut schemars::Schema, new_name: &str) {
 469            add_deprecation(schema, format!("Deprecated, use {new_name}"));
 470        }
 471
 472        fn add_description(schema: &mut schemars::Schema, description: String) {
 473            schema.insert("description".to_string(), Value::String(description));
 474        }
 475
 476        let empty_object = json_schema!({
 477            "type": "object"
 478        });
 479
 480        // This is a workaround for a json-language-server issue where it matches the first
 481        // alternative that matches the value's shape and uses that for documentation.
 482        //
 483        // In the case of the array validations, it would even provide an error saying that the name
 484        // must match the name of the first alternative.
 485        let mut plain_action = json_schema!({
 486            "type": "string",
 487            "const": ""
 488        });
 489        let no_action_message = "No action named this.";
 490        add_description(&mut plain_action, no_action_message.to_owned());
 491        add_deprecation(&mut plain_action, no_action_message.to_owned());
 492
 493        let mut matches_action_name = json_schema!({
 494            "const": ""
 495        });
 496        let no_action_message_input = "No action named this that takes input.";
 497        add_description(&mut matches_action_name, no_action_message_input.to_owned());
 498        add_deprecation(&mut matches_action_name, no_action_message_input.to_owned());
 499
 500        let action_with_input = json_schema!({
 501            "type": "array",
 502            "items": [
 503                matches_action_name,
 504                true
 505            ],
 506            "minItems": 2,
 507            "maxItems": 2
 508        });
 509        let mut keymap_action_alternatives = vec![plain_action, action_with_input];
 510
 511        for (name, action_schema) in action_schemas.into_iter() {
 512            let description = action_schema.as_ref().and_then(|schema| {
 513                schema
 514                    .as_object()
 515                    .and_then(|obj| obj.get("description"))
 516                    .and_then(|v| v.as_str())
 517                    .map(|s| s.to_string())
 518            });
 519
 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            if let Some(desc) = description.clone() {
 537                add_description(&mut plain_action, desc);
 538            }
 539            keymap_action_alternatives.push(plain_action);
 540
 541            // Add an alternative for actions with data specified as a [name, data] array.
 542            //
 543            // When a struct with no deserializable fields is added by deriving `Action`, an empty
 544            // object schema is produced. The action should be invoked without data in this case.
 545            if let Some(schema) = action_schema {
 546                if schema != empty_object {
 547                    let mut matches_action_name = json_schema!({
 548                        "const": name
 549                    });
 550                    if let Some(desc) = description.clone() {
 551                        add_description(&mut matches_action_name, desc);
 552                    }
 553                    if let Some(message) = deprecation_messages.get(name) {
 554                        add_deprecation(&mut matches_action_name, message.to_string());
 555                    } else if let Some(new_name) = deprecation {
 556                        add_deprecation_preferred_name(&mut matches_action_name, new_name);
 557                    }
 558                    let action_with_input = json_schema!({
 559                        "type": "array",
 560                        "items": [matches_action_name, schema],
 561                        "minItems": 2,
 562                        "maxItems": 2
 563                    });
 564                    keymap_action_alternatives.push(action_with_input);
 565                }
 566            }
 567        }
 568
 569        // Placing null first causes json-language-server to default assuming actions should be
 570        // null, so place it last.
 571        keymap_action_alternatives.push(json_schema!({
 572            "type": "null"
 573        }));
 574
 575        // The `KeymapSection` schema will reference the `KeymapAction` schema by name, so setting
 576        // the definition of `KeymapAction` results in the full action schema being used.
 577        generator.definitions_mut().insert(
 578            KeymapAction::schema_name().to_string(),
 579            json!({
 580                "oneOf": keymap_action_alternatives
 581            }),
 582        );
 583
 584        generator.root_schema_for::<KeymapFile>().to_value()
 585    }
 586
 587    pub fn sections(&self) -> impl DoubleEndedIterator<Item = &KeymapSection> {
 588        self.0.iter()
 589    }
 590
 591    pub async fn load_keymap_file(fs: &Arc<dyn Fs>) -> Result<String> {
 592        match fs.load(paths::keymap_file()).await {
 593            result @ Ok(_) => result,
 594            Err(err) => {
 595                if let Some(e) = err.downcast_ref::<std::io::Error>() {
 596                    if e.kind() == std::io::ErrorKind::NotFound {
 597                        return Ok(crate::initial_keymap_content().to_string());
 598                    }
 599                }
 600                Err(err)
 601            }
 602        }
 603    }
 604
 605    pub fn update_keybinding<'a>(
 606        mut operation: KeybindUpdateOperation<'a>,
 607        mut keymap_contents: String,
 608        tab_size: usize,
 609    ) -> Result<String> {
 610        // if trying to replace a keybinding that is not user-defined, treat it as an add operation
 611        match operation {
 612            KeybindUpdateOperation::Replace {
 613                target_keybind_source: target_source,
 614                source,
 615                ..
 616            } if target_source != KeybindSource::User => {
 617                operation = KeybindUpdateOperation::Add(source);
 618            }
 619            _ => {}
 620        }
 621
 622        // Sanity check that keymap contents are valid, even though we only use it for Replace.
 623        // We don't want to modify the file if it's invalid.
 624        let keymap = Self::parse(&keymap_contents).context("Failed to parse keymap")?;
 625
 626        if let KeybindUpdateOperation::Replace { source, target, .. } = operation {
 627            let mut found_index = None;
 628            let target_action_value = target
 629                .action_value()
 630                .context("Failed to generate target action JSON value")?;
 631            let source_action_value = source
 632                .action_value()
 633                .context("Failed to generate source action JSON value")?;
 634            'sections: for (index, section) in keymap.sections().enumerate() {
 635                if section.context != target.context.unwrap_or("") {
 636                    continue;
 637                }
 638                if section.use_key_equivalents != target.use_key_equivalents {
 639                    continue;
 640                }
 641                let Some(bindings) = &section.bindings else {
 642                    continue;
 643                };
 644                for (keystrokes, action) in bindings {
 645                    let Ok(keystrokes) = keystrokes
 646                        .split_whitespace()
 647                        .map(Keystroke::parse)
 648                        .collect::<Result<Vec<_>, _>>()
 649                    else {
 650                        continue;
 651                    };
 652                    if keystrokes.len() != target.keystrokes.len()
 653                        || !keystrokes
 654                            .iter()
 655                            .zip(target.keystrokes)
 656                            .all(|(a, b)| a.should_match(b))
 657                    {
 658                        continue;
 659                    }
 660                    if action.0 != target_action_value {
 661                        continue;
 662                    }
 663                    found_index = Some(index);
 664                    break 'sections;
 665                }
 666            }
 667
 668            if let Some(index) = found_index {
 669                if target.context == source.context {
 670                    // if we are only changing the keybinding (common case)
 671                    // not the context, etc. Then just update the binding in place
 672
 673                    let (replace_range, replace_value) =
 674                        replace_top_level_array_value_in_json_text(
 675                            &keymap_contents,
 676                            &["bindings", &target.keystrokes_unparsed()],
 677                            Some(&source_action_value),
 678                            Some(&source.keystrokes_unparsed()),
 679                            index,
 680                            tab_size,
 681                        )
 682                        .context("Failed to replace keybinding")?;
 683                    keymap_contents.replace_range(replace_range, &replace_value);
 684
 685                    return Ok(keymap_contents);
 686                } else if keymap.0[index]
 687                    .bindings
 688                    .as_ref()
 689                    .map_or(true, |bindings| bindings.len() == 1)
 690                {
 691                    // if we are replacing the only binding in the section,
 692                    // just update the section in place, updating the context
 693                    // and the binding
 694
 695                    let (replace_range, replace_value) =
 696                        replace_top_level_array_value_in_json_text(
 697                            &keymap_contents,
 698                            &["bindings", &target.keystrokes_unparsed()],
 699                            Some(&source_action_value),
 700                            Some(&source.keystrokes_unparsed()),
 701                            index,
 702                            tab_size,
 703                        )
 704                        .context("Failed to replace keybinding")?;
 705                    keymap_contents.replace_range(replace_range, &replace_value);
 706
 707                    let (replace_range, replace_value) =
 708                        replace_top_level_array_value_in_json_text(
 709                            &keymap_contents,
 710                            &["context"],
 711                            source.context.map(Into::into).as_ref(),
 712                            None,
 713                            index,
 714                            tab_size,
 715                        )
 716                        .context("Failed to replace keybinding")?;
 717                    keymap_contents.replace_range(replace_range, &replace_value);
 718                    return Ok(keymap_contents);
 719                } else {
 720                    // if we are replacing one of multiple bindings in a section
 721                    // with a context change, remove the existing binding from the
 722                    // section, then treat this operation as an add operation of the
 723                    // new binding with the updated context.
 724
 725                    let (replace_range, replace_value) =
 726                        replace_top_level_array_value_in_json_text(
 727                            &keymap_contents,
 728                            &["bindings", &target.keystrokes_unparsed()],
 729                            None,
 730                            None,
 731                            index,
 732                            tab_size,
 733                        )
 734                        .context("Failed to replace keybinding")?;
 735                    keymap_contents.replace_range(replace_range, &replace_value);
 736                    operation = KeybindUpdateOperation::Add(source);
 737                }
 738            } else {
 739                log::warn!(
 740                    "Failed to find keybinding to update `{:?} -> {}` creating new binding for `{:?} -> {}` instead",
 741                    target.keystrokes,
 742                    target_action_value,
 743                    source.keystrokes,
 744                    source_action_value,
 745                );
 746                operation = KeybindUpdateOperation::Add(source);
 747            }
 748        }
 749
 750        if let KeybindUpdateOperation::Add(keybinding) = operation {
 751            let mut value = serde_json::Map::with_capacity(4);
 752            if let Some(context) = keybinding.context {
 753                value.insert("context".to_string(), context.into());
 754            }
 755            if keybinding.use_key_equivalents {
 756                value.insert("use_key_equivalents".to_string(), true.into());
 757            }
 758
 759            value.insert("bindings".to_string(), {
 760                let mut bindings = serde_json::Map::new();
 761                let action = keybinding.action_value()?;
 762                bindings.insert(keybinding.keystrokes_unparsed(), action);
 763                bindings.into()
 764            });
 765
 766            let (replace_range, replace_value) = append_top_level_array_value_in_json_text(
 767                &keymap_contents,
 768                &value.into(),
 769                tab_size,
 770            )?;
 771            keymap_contents.replace_range(replace_range, &replace_value);
 772        }
 773        return Ok(keymap_contents);
 774    }
 775}
 776
 777pub enum KeybindUpdateOperation<'a> {
 778    Replace {
 779        /// Describes the keybind to create
 780        source: KeybindUpdateTarget<'a>,
 781        /// Describes the keybind to remove
 782        target: KeybindUpdateTarget<'a>,
 783        target_keybind_source: KeybindSource,
 784    },
 785    Add(KeybindUpdateTarget<'a>),
 786}
 787
 788pub struct KeybindUpdateTarget<'a> {
 789    pub context: Option<&'a str>,
 790    pub keystrokes: &'a [Keystroke],
 791    pub action_name: &'a str,
 792    pub use_key_equivalents: bool,
 793    pub input: Option<&'a str>,
 794}
 795
 796impl<'a> KeybindUpdateTarget<'a> {
 797    fn action_value(&self) -> Result<Value> {
 798        let action_name: Value = self.action_name.into();
 799        let value = match self.input {
 800            Some(input) => {
 801                let input = serde_json::from_str::<Value>(input)
 802                    .context("Failed to parse action input as JSON")?;
 803                serde_json::json!([action_name, input])
 804            }
 805            None => action_name,
 806        };
 807        return Ok(value);
 808    }
 809
 810    fn keystrokes_unparsed(&self) -> String {
 811        let mut keystrokes = String::with_capacity(self.keystrokes.len() * 8);
 812        for keystroke in self.keystrokes {
 813            keystrokes.push_str(&keystroke.unparse());
 814            keystrokes.push(' ');
 815        }
 816        keystrokes.pop();
 817        keystrokes
 818    }
 819}
 820
 821#[derive(Clone, Copy, PartialEq, Eq)]
 822pub enum KeybindSource {
 823    User,
 824    Default,
 825    Base,
 826    Vim,
 827}
 828
 829impl KeybindSource {
 830    const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(0);
 831    const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(1);
 832    const VIM: KeyBindingMetaIndex = KeyBindingMetaIndex(2);
 833    const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(3);
 834
 835    pub fn name(&self) -> &'static str {
 836        match self {
 837            KeybindSource::User => "User",
 838            KeybindSource::Default => "Default",
 839            KeybindSource::Base => "Base",
 840            KeybindSource::Vim => "Vim",
 841        }
 842    }
 843
 844    pub fn meta(&self) -> KeyBindingMetaIndex {
 845        match self {
 846            KeybindSource::User => Self::USER,
 847            KeybindSource::Default => Self::DEFAULT,
 848            KeybindSource::Base => Self::BASE,
 849            KeybindSource::Vim => Self::VIM,
 850        }
 851    }
 852
 853    pub fn from_meta(index: KeyBindingMetaIndex) -> Self {
 854        match index {
 855            Self::USER => KeybindSource::User,
 856            Self::BASE => KeybindSource::Base,
 857            Self::DEFAULT => KeybindSource::Default,
 858            Self::VIM => KeybindSource::Vim,
 859            _ => unreachable!(),
 860        }
 861    }
 862}
 863
 864impl From<KeyBindingMetaIndex> for KeybindSource {
 865    fn from(index: KeyBindingMetaIndex) -> Self {
 866        Self::from_meta(index)
 867    }
 868}
 869
 870impl From<KeybindSource> for KeyBindingMetaIndex {
 871    fn from(source: KeybindSource) -> Self {
 872        return source.meta();
 873    }
 874}
 875
 876#[cfg(test)]
 877mod tests {
 878    use unindent::Unindent;
 879
 880    use crate::{
 881        KeybindSource, KeymapFile,
 882        keymap_file::{KeybindUpdateOperation, KeybindUpdateTarget},
 883    };
 884
 885    #[test]
 886    fn can_deserialize_keymap_with_trailing_comma() {
 887        let json = indoc::indoc! {"[
 888              // Standard macOS bindings
 889              {
 890                \"bindings\": {
 891                  \"up\": \"menu::SelectPrevious\",
 892                },
 893              },
 894            ]
 895                  "
 896        };
 897        KeymapFile::parse(json).unwrap();
 898    }
 899
 900    #[test]
 901    fn keymap_update() {
 902        use gpui::Keystroke;
 903
 904        zlog::init_test();
 905        #[track_caller]
 906        fn check_keymap_update(
 907            input: impl ToString,
 908            operation: KeybindUpdateOperation,
 909            expected: impl ToString,
 910        ) {
 911            let result = KeymapFile::update_keybinding(operation, input.to_string(), 4)
 912                .expect("Update succeeded");
 913            pretty_assertions::assert_eq!(expected.to_string(), result);
 914        }
 915
 916        #[track_caller]
 917        fn parse_keystrokes(keystrokes: &str) -> Vec<Keystroke> {
 918            return keystrokes
 919                .split(' ')
 920                .map(|s| Keystroke::parse(s).expect("Keystrokes valid"))
 921                .collect();
 922        }
 923
 924        check_keymap_update(
 925            "[]",
 926            KeybindUpdateOperation::Add(KeybindUpdateTarget {
 927                keystrokes: &parse_keystrokes("ctrl-a"),
 928                action_name: "zed::SomeAction",
 929                context: None,
 930                use_key_equivalents: false,
 931                input: None,
 932            }),
 933            r#"[
 934                {
 935                    "bindings": {
 936                        "ctrl-a": "zed::SomeAction"
 937                    }
 938                }
 939            ]"#
 940            .unindent(),
 941        );
 942
 943        check_keymap_update(
 944            r#"[
 945                {
 946                    "bindings": {
 947                        "ctrl-a": "zed::SomeAction"
 948                    }
 949                }
 950            ]"#
 951            .unindent(),
 952            KeybindUpdateOperation::Add(KeybindUpdateTarget {
 953                keystrokes: &parse_keystrokes("ctrl-b"),
 954                action_name: "zed::SomeOtherAction",
 955                context: None,
 956                use_key_equivalents: false,
 957                input: None,
 958            }),
 959            r#"[
 960                {
 961                    "bindings": {
 962                        "ctrl-a": "zed::SomeAction"
 963                    }
 964                },
 965                {
 966                    "bindings": {
 967                        "ctrl-b": "zed::SomeOtherAction"
 968                    }
 969                }
 970            ]"#
 971            .unindent(),
 972        );
 973
 974        check_keymap_update(
 975            r#"[
 976                {
 977                    "bindings": {
 978                        "ctrl-a": "zed::SomeAction"
 979                    }
 980                }
 981            ]"#
 982            .unindent(),
 983            KeybindUpdateOperation::Add(KeybindUpdateTarget {
 984                keystrokes: &parse_keystrokes("ctrl-b"),
 985                action_name: "zed::SomeOtherAction",
 986                context: None,
 987                use_key_equivalents: false,
 988                input: Some(r#"{"foo": "bar"}"#),
 989            }),
 990            r#"[
 991                {
 992                    "bindings": {
 993                        "ctrl-a": "zed::SomeAction"
 994                    }
 995                },
 996                {
 997                    "bindings": {
 998                        "ctrl-b": [
 999                            "zed::SomeOtherAction",
1000                            {
1001                                "foo": "bar"
1002                            }
1003                        ]
1004                    }
1005                }
1006            ]"#
1007            .unindent(),
1008        );
1009
1010        check_keymap_update(
1011            r#"[
1012                {
1013                    "bindings": {
1014                        "ctrl-a": "zed::SomeAction"
1015                    }
1016                }
1017            ]"#
1018            .unindent(),
1019            KeybindUpdateOperation::Add(KeybindUpdateTarget {
1020                keystrokes: &parse_keystrokes("ctrl-b"),
1021                action_name: "zed::SomeOtherAction",
1022                context: Some("Zed > Editor && some_condition = true"),
1023                use_key_equivalents: true,
1024                input: Some(r#"{"foo": "bar"}"#),
1025            }),
1026            r#"[
1027                {
1028                    "bindings": {
1029                        "ctrl-a": "zed::SomeAction"
1030                    }
1031                },
1032                {
1033                    "context": "Zed > Editor && some_condition = true",
1034                    "use_key_equivalents": true,
1035                    "bindings": {
1036                        "ctrl-b": [
1037                            "zed::SomeOtherAction",
1038                            {
1039                                "foo": "bar"
1040                            }
1041                        ]
1042                    }
1043                }
1044            ]"#
1045            .unindent(),
1046        );
1047
1048        check_keymap_update(
1049            r#"[
1050                {
1051                    "bindings": {
1052                        "ctrl-a": "zed::SomeAction"
1053                    }
1054                }
1055            ]"#
1056            .unindent(),
1057            KeybindUpdateOperation::Replace {
1058                target: KeybindUpdateTarget {
1059                    keystrokes: &parse_keystrokes("ctrl-a"),
1060                    action_name: "zed::SomeAction",
1061                    context: None,
1062                    use_key_equivalents: false,
1063                    input: None,
1064                },
1065                source: KeybindUpdateTarget {
1066                    keystrokes: &parse_keystrokes("ctrl-b"),
1067                    action_name: "zed::SomeOtherAction",
1068                    context: None,
1069                    use_key_equivalents: false,
1070                    input: Some(r#"{"foo": "bar"}"#),
1071                },
1072                target_keybind_source: KeybindSource::Base,
1073            },
1074            r#"[
1075                {
1076                    "bindings": {
1077                        "ctrl-a": "zed::SomeAction"
1078                    }
1079                },
1080                {
1081                    "bindings": {
1082                        "ctrl-b": [
1083                            "zed::SomeOtherAction",
1084                            {
1085                                "foo": "bar"
1086                            }
1087                        ]
1088                    }
1089                }
1090            ]"#
1091            .unindent(),
1092        );
1093
1094        check_keymap_update(
1095            r#"[
1096                {
1097                    "bindings": {
1098                        "a": "zed::SomeAction"
1099                    }
1100                }
1101            ]"#
1102            .unindent(),
1103            KeybindUpdateOperation::Replace {
1104                target: KeybindUpdateTarget {
1105                    keystrokes: &parse_keystrokes("a"),
1106                    action_name: "zed::SomeAction",
1107                    context: None,
1108                    use_key_equivalents: false,
1109                    input: None,
1110                },
1111                source: KeybindUpdateTarget {
1112                    keystrokes: &parse_keystrokes("ctrl-b"),
1113                    action_name: "zed::SomeOtherAction",
1114                    context: None,
1115                    use_key_equivalents: false,
1116                    input: Some(r#"{"foo": "bar"}"#),
1117                },
1118                target_keybind_source: KeybindSource::User,
1119            },
1120            r#"[
1121                {
1122                    "bindings": {
1123                        "ctrl-b": [
1124                            "zed::SomeOtherAction",
1125                            {
1126                                "foo": "bar"
1127                            }
1128                        ]
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::Replace {
1145                target: KeybindUpdateTarget {
1146                    keystrokes: &parse_keystrokes("ctrl-a"),
1147                    action_name: "zed::SomeNonexistentAction",
1148                    context: None,
1149                    use_key_equivalents: false,
1150                    input: None,
1151                },
1152                source: KeybindUpdateTarget {
1153                    keystrokes: &parse_keystrokes("ctrl-b"),
1154                    action_name: "zed::SomeOtherAction",
1155                    context: None,
1156                    use_key_equivalents: false,
1157                    input: None,
1158                },
1159                target_keybind_source: KeybindSource::User,
1160            },
1161            r#"[
1162                {
1163                    "bindings": {
1164                        "ctrl-a": "zed::SomeAction"
1165                    }
1166                },
1167                {
1168                    "bindings": {
1169                        "ctrl-b": "zed::SomeOtherAction"
1170                    }
1171                }
1172            ]"#
1173            .unindent(),
1174        );
1175
1176        check_keymap_update(
1177            r#"[
1178                {
1179                    "bindings": {
1180                        // some comment
1181                        "ctrl-a": "zed::SomeAction"
1182                        // some other comment
1183                    }
1184                }
1185            ]"#
1186            .unindent(),
1187            KeybindUpdateOperation::Replace {
1188                target: KeybindUpdateTarget {
1189                    keystrokes: &parse_keystrokes("ctrl-a"),
1190                    action_name: "zed::SomeAction",
1191                    context: None,
1192                    use_key_equivalents: false,
1193                    input: None,
1194                },
1195                source: KeybindUpdateTarget {
1196                    keystrokes: &parse_keystrokes("ctrl-b"),
1197                    action_name: "zed::SomeOtherAction",
1198                    context: None,
1199                    use_key_equivalents: false,
1200                    input: Some(r#"{"foo": "bar"}"#),
1201                },
1202                target_keybind_source: KeybindSource::User,
1203            },
1204            r#"[
1205                {
1206                    "bindings": {
1207                        // some comment
1208                        "ctrl-b": [
1209                            "zed::SomeOtherAction",
1210                            {
1211                                "foo": "bar"
1212                            }
1213                        ]
1214                        // some other comment
1215                    }
1216                }
1217            ]"#
1218            .unindent(),
1219        );
1220
1221        check_keymap_update(
1222            r#"[
1223                {
1224                    "context": "SomeContext",
1225                    "bindings": {
1226                        "a": "foo::bar",
1227                        "b": "baz::qux",
1228                    }
1229                }
1230            ]"#
1231            .unindent(),
1232            KeybindUpdateOperation::Replace {
1233                target: KeybindUpdateTarget {
1234                    keystrokes: &parse_keystrokes("a"),
1235                    action_name: "foo::bar",
1236                    context: Some("SomeContext"),
1237                    use_key_equivalents: false,
1238                    input: None,
1239                },
1240                source: KeybindUpdateTarget {
1241                    keystrokes: &parse_keystrokes("c"),
1242                    action_name: "foo::baz",
1243                    context: Some("SomeOtherContext"),
1244                    use_key_equivalents: false,
1245                    input: None,
1246                },
1247                target_keybind_source: KeybindSource::User,
1248            },
1249            r#"[
1250                {
1251                    "context": "SomeContext",
1252                    "bindings": {
1253                        "b": "baz::qux",
1254                    }
1255                },
1256                {
1257                    "context": "SomeOtherContext",
1258                    "bindings": {
1259                        "c": "foo::baz"
1260                    }
1261                }
1262            ]"#
1263            .unindent(),
1264        );
1265
1266        check_keymap_update(
1267            r#"[
1268                {
1269                    "context": "SomeContext",
1270                    "bindings": {
1271                        "a": "foo::bar",
1272                    }
1273                }
1274            ]"#
1275            .unindent(),
1276            KeybindUpdateOperation::Replace {
1277                target: KeybindUpdateTarget {
1278                    keystrokes: &parse_keystrokes("a"),
1279                    action_name: "foo::bar",
1280                    context: Some("SomeContext"),
1281                    use_key_equivalents: false,
1282                    input: None,
1283                },
1284                source: KeybindUpdateTarget {
1285                    keystrokes: &parse_keystrokes("c"),
1286                    action_name: "foo::baz",
1287                    context: Some("SomeOtherContext"),
1288                    use_key_equivalents: false,
1289                    input: None,
1290                },
1291                target_keybind_source: KeybindSource::User,
1292            },
1293            r#"[
1294                {
1295                    "context": "SomeOtherContext",
1296                    "bindings": {
1297                        "c": "foo::baz",
1298                    }
1299                }
1300            ]"#
1301            .unindent(),
1302        );
1303    }
1304}