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