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::Remove {
627 target,
628 target_keybind_source,
629 } = operation
630 {
631 if target_keybind_source != KeybindSource::User {
632 anyhow::bail!("Cannot remove non-user created keybinding. Not implemented yet");
633 }
634 let target_action_value = target
635 .action_value()
636 .context("Failed to generate target action JSON value")?;
637 let Some((index, keystrokes_str)) =
638 find_binding(&keymap, &target, &target_action_value)
639 else {
640 anyhow::bail!("Failed to find keybinding to remove");
641 };
642 let is_only_binding = keymap.0[index]
643 .bindings
644 .as_ref()
645 .map_or(true, |bindings| bindings.len() == 1);
646 let key_path: &[&str] = if is_only_binding {
647 &[]
648 } else {
649 &["bindings", keystrokes_str]
650 };
651 let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
652 &keymap_contents,
653 key_path,
654 None,
655 None,
656 index,
657 tab_size,
658 )
659 .context("Failed to remove keybinding")?;
660 keymap_contents.replace_range(replace_range, &replace_value);
661 return Ok(keymap_contents);
662 }
663
664 if let KeybindUpdateOperation::Replace { source, target, .. } = operation {
665 let target_action_value = target
666 .action_value()
667 .context("Failed to generate target action JSON value")?;
668 let source_action_value = source
669 .action_value()
670 .context("Failed to generate source action JSON value")?;
671
672 if let Some((index, keystrokes_str)) =
673 find_binding(&keymap, &target, &target_action_value)
674 {
675 if target.context == source.context {
676 // if we are only changing the keybinding (common case)
677 // not the context, etc. Then just update the binding in place
678
679 let (replace_range, replace_value) =
680 replace_top_level_array_value_in_json_text(
681 &keymap_contents,
682 &["bindings", keystrokes_str],
683 Some(&source_action_value),
684 Some(&source.keystrokes_unparsed()),
685 index,
686 tab_size,
687 )
688 .context("Failed to replace keybinding")?;
689 keymap_contents.replace_range(replace_range, &replace_value);
690
691 return Ok(keymap_contents);
692 } else if keymap.0[index]
693 .bindings
694 .as_ref()
695 .map_or(true, |bindings| bindings.len() == 1)
696 {
697 // if we are replacing the only binding in the section,
698 // just update the section in place, updating the context
699 // and the binding
700
701 let (replace_range, replace_value) =
702 replace_top_level_array_value_in_json_text(
703 &keymap_contents,
704 &["bindings", keystrokes_str],
705 Some(&source_action_value),
706 Some(&source.keystrokes_unparsed()),
707 index,
708 tab_size,
709 )
710 .context("Failed to replace keybinding")?;
711 keymap_contents.replace_range(replace_range, &replace_value);
712
713 let (replace_range, replace_value) =
714 replace_top_level_array_value_in_json_text(
715 &keymap_contents,
716 &["context"],
717 source.context.map(Into::into).as_ref(),
718 None,
719 index,
720 tab_size,
721 )
722 .context("Failed to replace keybinding")?;
723 keymap_contents.replace_range(replace_range, &replace_value);
724 return Ok(keymap_contents);
725 } else {
726 // if we are replacing one of multiple bindings in a section
727 // with a context change, remove the existing binding from the
728 // section, then treat this operation as an add operation of the
729 // new binding with the updated context.
730
731 let (replace_range, replace_value) =
732 replace_top_level_array_value_in_json_text(
733 &keymap_contents,
734 &["bindings", keystrokes_str],
735 None,
736 None,
737 index,
738 tab_size,
739 )
740 .context("Failed to replace keybinding")?;
741 keymap_contents.replace_range(replace_range, &replace_value);
742 operation = KeybindUpdateOperation::Add(source);
743 }
744 } else {
745 log::warn!(
746 "Failed to find keybinding to update `{:?} -> {}` creating new binding for `{:?} -> {}` instead",
747 target.keystrokes,
748 target_action_value,
749 source.keystrokes,
750 source_action_value,
751 );
752 operation = KeybindUpdateOperation::Add(source);
753 }
754 }
755
756 if let KeybindUpdateOperation::Add(keybinding) = operation {
757 let mut value = serde_json::Map::with_capacity(4);
758 if let Some(context) = keybinding.context {
759 value.insert("context".to_string(), context.into());
760 }
761 if keybinding.use_key_equivalents {
762 value.insert("use_key_equivalents".to_string(), true.into());
763 }
764
765 value.insert("bindings".to_string(), {
766 let mut bindings = serde_json::Map::new();
767 let action = keybinding.action_value()?;
768 bindings.insert(keybinding.keystrokes_unparsed(), action);
769 bindings.into()
770 });
771
772 let (replace_range, replace_value) = append_top_level_array_value_in_json_text(
773 &keymap_contents,
774 &value.into(),
775 tab_size,
776 )?;
777 keymap_contents.replace_range(replace_range, &replace_value);
778 }
779 return Ok(keymap_contents);
780
781 fn find_binding<'a, 'b>(
782 keymap: &'b KeymapFile,
783 target: &KeybindUpdateTarget<'a>,
784 target_action_value: &Value,
785 ) -> Option<(usize, &'b str)> {
786 let target_context_parsed =
787 KeyBindingContextPredicate::parse(target.context.unwrap_or("")).ok();
788 for (index, section) in keymap.sections().enumerate() {
789 let section_context_parsed =
790 KeyBindingContextPredicate::parse(§ion.context).ok();
791 if section_context_parsed != target_context_parsed {
792 continue;
793 }
794 if section.use_key_equivalents != target.use_key_equivalents {
795 continue;
796 }
797 let Some(bindings) = §ion.bindings else {
798 continue;
799 };
800 for (keystrokes_str, action) in bindings {
801 let Ok(keystrokes) = keystrokes_str
802 .split_whitespace()
803 .map(Keystroke::parse)
804 .collect::<Result<Vec<_>, _>>()
805 else {
806 continue;
807 };
808 if keystrokes.len() != target.keystrokes.len()
809 || !keystrokes
810 .iter()
811 .zip(target.keystrokes)
812 .all(|(a, b)| a.should_match(b))
813 {
814 continue;
815 }
816 if &action.0 != target_action_value {
817 continue;
818 }
819 return Some((index, &keystrokes_str));
820 }
821 }
822 None
823 }
824 }
825}
826
827pub enum KeybindUpdateOperation<'a> {
828 Replace {
829 /// Describes the keybind to create
830 source: KeybindUpdateTarget<'a>,
831 /// Describes the keybind to remove
832 target: KeybindUpdateTarget<'a>,
833 target_keybind_source: KeybindSource,
834 },
835 Add(KeybindUpdateTarget<'a>),
836 Remove {
837 target: KeybindUpdateTarget<'a>,
838 target_keybind_source: KeybindSource,
839 },
840}
841
842#[derive(Debug)]
843pub struct KeybindUpdateTarget<'a> {
844 pub context: Option<&'a str>,
845 pub keystrokes: &'a [Keystroke],
846 pub action_name: &'a str,
847 pub use_key_equivalents: bool,
848 pub input: Option<&'a str>,
849}
850
851impl<'a> KeybindUpdateTarget<'a> {
852 fn action_value(&self) -> Result<Value> {
853 let action_name: Value = self.action_name.into();
854 let value = match self.input {
855 Some(input) => {
856 let input = serde_json::from_str::<Value>(input)
857 .context("Failed to parse action input as JSON")?;
858 serde_json::json!([action_name, input])
859 }
860 None => action_name,
861 };
862 return Ok(value);
863 }
864
865 fn keystrokes_unparsed(&self) -> String {
866 let mut keystrokes = String::with_capacity(self.keystrokes.len() * 8);
867 for keystroke in self.keystrokes {
868 keystrokes.push_str(&keystroke.unparse());
869 keystrokes.push(' ');
870 }
871 keystrokes.pop();
872 keystrokes
873 }
874}
875
876#[derive(Clone, Copy, PartialEq, Eq)]
877pub enum KeybindSource {
878 User,
879 Default,
880 Base,
881 Vim,
882}
883
884impl KeybindSource {
885 const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(0);
886 const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(1);
887 const VIM: KeyBindingMetaIndex = KeyBindingMetaIndex(2);
888 const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(3);
889
890 pub fn name(&self) -> &'static str {
891 match self {
892 KeybindSource::User => "User",
893 KeybindSource::Default => "Default",
894 KeybindSource::Base => "Base",
895 KeybindSource::Vim => "Vim",
896 }
897 }
898
899 pub fn meta(&self) -> KeyBindingMetaIndex {
900 match self {
901 KeybindSource::User => Self::USER,
902 KeybindSource::Default => Self::DEFAULT,
903 KeybindSource::Base => Self::BASE,
904 KeybindSource::Vim => Self::VIM,
905 }
906 }
907
908 pub fn from_meta(index: KeyBindingMetaIndex) -> Self {
909 match index {
910 Self::USER => KeybindSource::User,
911 Self::BASE => KeybindSource::Base,
912 Self::DEFAULT => KeybindSource::Default,
913 Self::VIM => KeybindSource::Vim,
914 _ => unreachable!(),
915 }
916 }
917}
918
919impl From<KeyBindingMetaIndex> for KeybindSource {
920 fn from(index: KeyBindingMetaIndex) -> Self {
921 Self::from_meta(index)
922 }
923}
924
925impl From<KeybindSource> for KeyBindingMetaIndex {
926 fn from(source: KeybindSource) -> Self {
927 return source.meta();
928 }
929}
930
931#[cfg(test)]
932mod tests {
933 use unindent::Unindent;
934
935 use crate::{
936 KeybindSource, KeymapFile,
937 keymap_file::{KeybindUpdateOperation, KeybindUpdateTarget},
938 };
939
940 #[test]
941 fn can_deserialize_keymap_with_trailing_comma() {
942 let json = indoc::indoc! {"[
943 // Standard macOS bindings
944 {
945 \"bindings\": {
946 \"up\": \"menu::SelectPrevious\",
947 },
948 },
949 ]
950 "
951 };
952 KeymapFile::parse(json).unwrap();
953 }
954
955 #[test]
956 fn keymap_update() {
957 use gpui::Keystroke;
958
959 zlog::init_test();
960 #[track_caller]
961 fn check_keymap_update(
962 input: impl ToString,
963 operation: KeybindUpdateOperation,
964 expected: impl ToString,
965 ) {
966 let result = KeymapFile::update_keybinding(operation, input.to_string(), 4)
967 .expect("Update succeeded");
968 pretty_assertions::assert_eq!(expected.to_string(), result);
969 }
970
971 #[track_caller]
972 fn parse_keystrokes(keystrokes: &str) -> Vec<Keystroke> {
973 return keystrokes
974 .split(' ')
975 .map(|s| Keystroke::parse(s).expect("Keystrokes valid"))
976 .collect();
977 }
978
979 check_keymap_update(
980 "[]",
981 KeybindUpdateOperation::Add(KeybindUpdateTarget {
982 keystrokes: &parse_keystrokes("ctrl-a"),
983 action_name: "zed::SomeAction",
984 context: None,
985 use_key_equivalents: false,
986 input: None,
987 }),
988 r#"[
989 {
990 "bindings": {
991 "ctrl-a": "zed::SomeAction"
992 }
993 }
994 ]"#
995 .unindent(),
996 );
997
998 check_keymap_update(
999 r#"[
1000 {
1001 "bindings": {
1002 "ctrl-a": "zed::SomeAction"
1003 }
1004 }
1005 ]"#
1006 .unindent(),
1007 KeybindUpdateOperation::Add(KeybindUpdateTarget {
1008 keystrokes: &parse_keystrokes("ctrl-b"),
1009 action_name: "zed::SomeOtherAction",
1010 context: None,
1011 use_key_equivalents: false,
1012 input: None,
1013 }),
1014 r#"[
1015 {
1016 "bindings": {
1017 "ctrl-a": "zed::SomeAction"
1018 }
1019 },
1020 {
1021 "bindings": {
1022 "ctrl-b": "zed::SomeOtherAction"
1023 }
1024 }
1025 ]"#
1026 .unindent(),
1027 );
1028
1029 check_keymap_update(
1030 r#"[
1031 {
1032 "bindings": {
1033 "ctrl-a": "zed::SomeAction"
1034 }
1035 }
1036 ]"#
1037 .unindent(),
1038 KeybindUpdateOperation::Add(KeybindUpdateTarget {
1039 keystrokes: &parse_keystrokes("ctrl-b"),
1040 action_name: "zed::SomeOtherAction",
1041 context: None,
1042 use_key_equivalents: false,
1043 input: Some(r#"{"foo": "bar"}"#),
1044 }),
1045 r#"[
1046 {
1047 "bindings": {
1048 "ctrl-a": "zed::SomeAction"
1049 }
1050 },
1051 {
1052 "bindings": {
1053 "ctrl-b": [
1054 "zed::SomeOtherAction",
1055 {
1056 "foo": "bar"
1057 }
1058 ]
1059 }
1060 }
1061 ]"#
1062 .unindent(),
1063 );
1064
1065 check_keymap_update(
1066 r#"[
1067 {
1068 "bindings": {
1069 "ctrl-a": "zed::SomeAction"
1070 }
1071 }
1072 ]"#
1073 .unindent(),
1074 KeybindUpdateOperation::Add(KeybindUpdateTarget {
1075 keystrokes: &parse_keystrokes("ctrl-b"),
1076 action_name: "zed::SomeOtherAction",
1077 context: Some("Zed > Editor && some_condition = true"),
1078 use_key_equivalents: true,
1079 input: Some(r#"{"foo": "bar"}"#),
1080 }),
1081 r#"[
1082 {
1083 "bindings": {
1084 "ctrl-a": "zed::SomeAction"
1085 }
1086 },
1087 {
1088 "context": "Zed > Editor && some_condition = true",
1089 "use_key_equivalents": true,
1090 "bindings": {
1091 "ctrl-b": [
1092 "zed::SomeOtherAction",
1093 {
1094 "foo": "bar"
1095 }
1096 ]
1097 }
1098 }
1099 ]"#
1100 .unindent(),
1101 );
1102
1103 check_keymap_update(
1104 r#"[
1105 {
1106 "bindings": {
1107 "ctrl-a": "zed::SomeAction"
1108 }
1109 }
1110 ]"#
1111 .unindent(),
1112 KeybindUpdateOperation::Replace {
1113 target: KeybindUpdateTarget {
1114 keystrokes: &parse_keystrokes("ctrl-a"),
1115 action_name: "zed::SomeAction",
1116 context: None,
1117 use_key_equivalents: false,
1118 input: None,
1119 },
1120 source: KeybindUpdateTarget {
1121 keystrokes: &parse_keystrokes("ctrl-b"),
1122 action_name: "zed::SomeOtherAction",
1123 context: None,
1124 use_key_equivalents: false,
1125 input: Some(r#"{"foo": "bar"}"#),
1126 },
1127 target_keybind_source: KeybindSource::Base,
1128 },
1129 r#"[
1130 {
1131 "bindings": {
1132 "ctrl-a": "zed::SomeAction"
1133 }
1134 },
1135 {
1136 "bindings": {
1137 "ctrl-b": [
1138 "zed::SomeOtherAction",
1139 {
1140 "foo": "bar"
1141 }
1142 ]
1143 }
1144 }
1145 ]"#
1146 .unindent(),
1147 );
1148
1149 check_keymap_update(
1150 r#"[
1151 {
1152 "bindings": {
1153 "a": "zed::SomeAction"
1154 }
1155 }
1156 ]"#
1157 .unindent(),
1158 KeybindUpdateOperation::Replace {
1159 target: KeybindUpdateTarget {
1160 keystrokes: &parse_keystrokes("a"),
1161 action_name: "zed::SomeAction",
1162 context: None,
1163 use_key_equivalents: false,
1164 input: None,
1165 },
1166 source: KeybindUpdateTarget {
1167 keystrokes: &parse_keystrokes("ctrl-b"),
1168 action_name: "zed::SomeOtherAction",
1169 context: None,
1170 use_key_equivalents: false,
1171 input: Some(r#"{"foo": "bar"}"#),
1172 },
1173 target_keybind_source: KeybindSource::User,
1174 },
1175 r#"[
1176 {
1177 "bindings": {
1178 "ctrl-b": [
1179 "zed::SomeOtherAction",
1180 {
1181 "foo": "bar"
1182 }
1183 ]
1184 }
1185 }
1186 ]"#
1187 .unindent(),
1188 );
1189
1190 check_keymap_update(
1191 r#"[
1192 {
1193 "bindings": {
1194 "ctrl-a": "zed::SomeAction"
1195 }
1196 }
1197 ]"#
1198 .unindent(),
1199 KeybindUpdateOperation::Replace {
1200 target: KeybindUpdateTarget {
1201 keystrokes: &parse_keystrokes("ctrl-a"),
1202 action_name: "zed::SomeNonexistentAction",
1203 context: None,
1204 use_key_equivalents: false,
1205 input: None,
1206 },
1207 source: KeybindUpdateTarget {
1208 keystrokes: &parse_keystrokes("ctrl-b"),
1209 action_name: "zed::SomeOtherAction",
1210 context: None,
1211 use_key_equivalents: false,
1212 input: None,
1213 },
1214 target_keybind_source: KeybindSource::User,
1215 },
1216 r#"[
1217 {
1218 "bindings": {
1219 "ctrl-a": "zed::SomeAction"
1220 }
1221 },
1222 {
1223 "bindings": {
1224 "ctrl-b": "zed::SomeOtherAction"
1225 }
1226 }
1227 ]"#
1228 .unindent(),
1229 );
1230
1231 check_keymap_update(
1232 r#"[
1233 {
1234 "bindings": {
1235 // some comment
1236 "ctrl-a": "zed::SomeAction"
1237 // some other comment
1238 }
1239 }
1240 ]"#
1241 .unindent(),
1242 KeybindUpdateOperation::Replace {
1243 target: KeybindUpdateTarget {
1244 keystrokes: &parse_keystrokes("ctrl-a"),
1245 action_name: "zed::SomeAction",
1246 context: None,
1247 use_key_equivalents: false,
1248 input: None,
1249 },
1250 source: KeybindUpdateTarget {
1251 keystrokes: &parse_keystrokes("ctrl-b"),
1252 action_name: "zed::SomeOtherAction",
1253 context: None,
1254 use_key_equivalents: false,
1255 input: Some(r#"{"foo": "bar"}"#),
1256 },
1257 target_keybind_source: KeybindSource::User,
1258 },
1259 r#"[
1260 {
1261 "bindings": {
1262 // some comment
1263 "ctrl-b": [
1264 "zed::SomeOtherAction",
1265 {
1266 "foo": "bar"
1267 }
1268 ]
1269 // some other comment
1270 }
1271 }
1272 ]"#
1273 .unindent(),
1274 );
1275
1276 check_keymap_update(
1277 r#"[
1278 {
1279 "context": "SomeContext",
1280 "bindings": {
1281 "a": "foo::bar",
1282 "b": "baz::qux",
1283 }
1284 }
1285 ]"#
1286 .unindent(),
1287 KeybindUpdateOperation::Replace {
1288 target: KeybindUpdateTarget {
1289 keystrokes: &parse_keystrokes("a"),
1290 action_name: "foo::bar",
1291 context: Some("SomeContext"),
1292 use_key_equivalents: false,
1293 input: None,
1294 },
1295 source: KeybindUpdateTarget {
1296 keystrokes: &parse_keystrokes("c"),
1297 action_name: "foo::baz",
1298 context: Some("SomeOtherContext"),
1299 use_key_equivalents: false,
1300 input: None,
1301 },
1302 target_keybind_source: KeybindSource::User,
1303 },
1304 r#"[
1305 {
1306 "context": "SomeContext",
1307 "bindings": {
1308 "b": "baz::qux",
1309 }
1310 },
1311 {
1312 "context": "SomeOtherContext",
1313 "bindings": {
1314 "c": "foo::baz"
1315 }
1316 }
1317 ]"#
1318 .unindent(),
1319 );
1320
1321 check_keymap_update(
1322 r#"[
1323 {
1324 "context": "SomeContext",
1325 "bindings": {
1326 "a": "foo::bar",
1327 }
1328 }
1329 ]"#
1330 .unindent(),
1331 KeybindUpdateOperation::Replace {
1332 target: KeybindUpdateTarget {
1333 keystrokes: &parse_keystrokes("a"),
1334 action_name: "foo::bar",
1335 context: Some("SomeContext"),
1336 use_key_equivalents: false,
1337 input: None,
1338 },
1339 source: KeybindUpdateTarget {
1340 keystrokes: &parse_keystrokes("c"),
1341 action_name: "foo::baz",
1342 context: Some("SomeOtherContext"),
1343 use_key_equivalents: false,
1344 input: None,
1345 },
1346 target_keybind_source: KeybindSource::User,
1347 },
1348 r#"[
1349 {
1350 "context": "SomeOtherContext",
1351 "bindings": {
1352 "c": "foo::baz",
1353 }
1354 }
1355 ]"#
1356 .unindent(),
1357 );
1358
1359 check_keymap_update(
1360 r#"[
1361 {
1362 "context": "SomeContext",
1363 "bindings": {
1364 "a": "foo::bar",
1365 "c": "foo::baz",
1366 }
1367 },
1368 ]"#
1369 .unindent(),
1370 KeybindUpdateOperation::Remove {
1371 target: KeybindUpdateTarget {
1372 context: Some("SomeContext"),
1373 keystrokes: &parse_keystrokes("a"),
1374 action_name: "foo::bar",
1375 use_key_equivalents: false,
1376 input: None,
1377 },
1378 target_keybind_source: KeybindSource::User,
1379 },
1380 r#"[
1381 {
1382 "context": "SomeContext",
1383 "bindings": {
1384 "c": "foo::baz",
1385 }
1386 },
1387 ]"#
1388 .unindent(),
1389 );
1390
1391 check_keymap_update(
1392 r#"[
1393 {
1394 "context": "SomeContext",
1395 "bindings": {
1396 "a": ["foo::bar", true],
1397 "c": "foo::baz",
1398 }
1399 },
1400 ]"#
1401 .unindent(),
1402 KeybindUpdateOperation::Remove {
1403 target: KeybindUpdateTarget {
1404 context: Some("SomeContext"),
1405 keystrokes: &parse_keystrokes("a"),
1406 action_name: "foo::bar",
1407 use_key_equivalents: false,
1408 input: Some("true"),
1409 },
1410 target_keybind_source: KeybindSource::User,
1411 },
1412 r#"[
1413 {
1414 "context": "SomeContext",
1415 "bindings": {
1416 "c": "foo::baz",
1417 }
1418 },
1419 ]"#
1420 .unindent(),
1421 );
1422
1423 check_keymap_update(
1424 r#"[
1425 {
1426 "context": "SomeContext",
1427 "bindings": {
1428 "b": "foo::baz",
1429 }
1430 },
1431 {
1432 "context": "SomeContext",
1433 "bindings": {
1434 "a": ["foo::bar", true],
1435 }
1436 },
1437 {
1438 "context": "SomeContext",
1439 "bindings": {
1440 "c": "foo::baz",
1441 }
1442 },
1443 ]"#
1444 .unindent(),
1445 KeybindUpdateOperation::Remove {
1446 target: KeybindUpdateTarget {
1447 context: Some("SomeContext"),
1448 keystrokes: &parse_keystrokes("a"),
1449 action_name: "foo::bar",
1450 use_key_equivalents: false,
1451 input: Some("true"),
1452 },
1453 target_keybind_source: KeybindSource::User,
1454 },
1455 r#"[
1456 {
1457 "context": "SomeContext",
1458 "bindings": {
1459 "b": "foo::baz",
1460 }
1461 },
1462 {
1463 "context": "SomeContext",
1464 "bindings": {
1465 "c": "foo::baz",
1466 }
1467 },
1468 ]"#
1469 .unindent(),
1470 );
1471 }
1472}