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 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 pub fn generate_json_schema_for_registered_actions(cx: &mut App) -> Value {
430 // instead of using DefaultDenyUnknownFields, actions typically use
431 // `#[serde(deny_unknown_fields)]` so that these cases are reported as parse failures. This
432 // is because the rest of the keymap will still load in these cases, whereas other settings
433 // files would not.
434 let mut generator = schemars::generate::SchemaSettings::draft2019_09().into_generator();
435
436 let action_schemas = cx.action_schemas(&mut generator);
437 let deprecations = cx.deprecated_actions_to_preferred_actions();
438 let deprecation_messages = cx.action_deprecation_messages();
439 KeymapFile::generate_json_schema(
440 generator,
441 action_schemas,
442 deprecations,
443 deprecation_messages,
444 )
445 }
446
447 fn generate_json_schema(
448 mut generator: schemars::SchemaGenerator,
449 action_schemas: Vec<(&'static str, Option<schemars::Schema>)>,
450 deprecations: &HashMap<&'static str, &'static str>,
451 deprecation_messages: &HashMap<&'static str, &'static str>,
452 ) -> serde_json::Value {
453 fn add_deprecation(schema: &mut schemars::Schema, message: String) {
454 schema.insert(
455 // deprecationMessage is not part of the JSON Schema spec, but
456 // json-language-server recognizes it.
457 "deprecationMessage".to_string(),
458 Value::String(message),
459 );
460 }
461
462 fn add_deprecation_preferred_name(schema: &mut schemars::Schema, new_name: &str) {
463 add_deprecation(schema, format!("Deprecated, use {new_name}"));
464 }
465
466 fn add_description(schema: &mut schemars::Schema, description: String) {
467 schema.insert("description".to_string(), Value::String(description));
468 }
469
470 let empty_object = json_schema!({
471 "type": "object"
472 });
473
474 // This is a workaround for a json-language-server issue where it matches the first
475 // alternative that matches the value's shape and uses that for documentation.
476 //
477 // In the case of the array validations, it would even provide an error saying that the name
478 // must match the name of the first alternative.
479 let mut plain_action = json_schema!({
480 "type": "string",
481 "const": ""
482 });
483 let no_action_message = "No action named this.";
484 add_description(&mut plain_action, no_action_message.to_owned());
485 add_deprecation(&mut plain_action, no_action_message.to_owned());
486
487 let mut matches_action_name = json_schema!({
488 "const": ""
489 });
490 let no_action_message_input = "No action named this that takes input.";
491 add_description(&mut matches_action_name, no_action_message_input.to_owned());
492 add_deprecation(&mut matches_action_name, no_action_message_input.to_owned());
493
494 let action_with_input = json_schema!({
495 "type": "array",
496 "items": [
497 matches_action_name,
498 true
499 ],
500 "minItems": 2,
501 "maxItems": 2
502 });
503 let mut keymap_action_alternatives = vec![plain_action, action_with_input];
504
505 for (name, action_schema) in action_schemas.into_iter() {
506 let description = action_schema.as_ref().and_then(|schema| {
507 schema
508 .as_object()
509 .and_then(|obj| obj.get("description"))
510 .and_then(|v| v.as_str())
511 .map(|s| s.to_string())
512 });
513
514 let deprecation = if name == NoAction.name() {
515 Some("null")
516 } else {
517 deprecations.get(name).copied()
518 };
519
520 // Add an alternative for plain action names.
521 let mut plain_action = json_schema!({
522 "type": "string",
523 "const": name
524 });
525 if let Some(message) = deprecation_messages.get(name) {
526 add_deprecation(&mut plain_action, message.to_string());
527 } else if let Some(new_name) = deprecation {
528 add_deprecation_preferred_name(&mut plain_action, new_name);
529 }
530 if let Some(desc) = description.clone() {
531 add_description(&mut plain_action, desc);
532 }
533 keymap_action_alternatives.push(plain_action);
534
535 // Add an alternative for actions with data specified as a [name, data] array.
536 //
537 // When a struct with no deserializable fields is added by deriving `Action`, an empty
538 // object schema is produced. The action should be invoked without data in this case.
539 if let Some(schema) = action_schema {
540 if schema != empty_object {
541 let mut matches_action_name = json_schema!({
542 "const": name
543 });
544 if let Some(desc) = description.clone() {
545 add_description(&mut matches_action_name, desc);
546 }
547 if let Some(message) = deprecation_messages.get(name) {
548 add_deprecation(&mut matches_action_name, message.to_string());
549 } else if let Some(new_name) = deprecation {
550 add_deprecation_preferred_name(&mut matches_action_name, new_name);
551 }
552 let action_with_input = json_schema!({
553 "type": "array",
554 "items": [matches_action_name, schema],
555 "minItems": 2,
556 "maxItems": 2
557 });
558 keymap_action_alternatives.push(action_with_input);
559 }
560 }
561 }
562
563 // Placing null first causes json-language-server to default assuming actions should be
564 // null, so place it last.
565 keymap_action_alternatives.push(json_schema!({
566 "type": "null"
567 }));
568
569 // The `KeymapSection` schema will reference the `KeymapAction` schema by name, so setting
570 // the definition of `KeymapAction` results in the full action schema being used.
571 generator.definitions_mut().insert(
572 KeymapAction::schema_name().to_string(),
573 json!({
574 "oneOf": keymap_action_alternatives
575 }),
576 );
577
578 generator.root_schema_for::<KeymapFile>().to_value()
579 }
580
581 pub fn sections(&self) -> impl DoubleEndedIterator<Item = &KeymapSection> {
582 self.0.iter()
583 }
584
585 pub async fn load_keymap_file(fs: &Arc<dyn Fs>) -> Result<String> {
586 match fs.load(paths::keymap_file()).await {
587 result @ Ok(_) => result,
588 Err(err) => {
589 if let Some(e) = err.downcast_ref::<std::io::Error>() {
590 if e.kind() == std::io::ErrorKind::NotFound {
591 return Ok(crate::initial_keymap_content().to_string());
592 }
593 }
594 Err(err)
595 }
596 }
597 }
598
599 pub fn update_keybinding<'a>(
600 mut operation: KeybindUpdateOperation<'a>,
601 mut keymap_contents: String,
602 tab_size: usize,
603 ) -> Result<String> {
604 // if trying to replace a keybinding that is not user-defined, treat it as an add operation
605 match operation {
606 KeybindUpdateOperation::Replace {
607 target_source,
608 source,
609 ..
610 } if target_source != KeybindSource::User => {
611 operation = KeybindUpdateOperation::Add(source);
612 }
613 _ => {}
614 }
615
616 // Sanity check that keymap contents are valid, even though we only use it for Replace.
617 // We don't want to modify the file if it's invalid.
618 let keymap = Self::parse(&keymap_contents).context("Failed to parse keymap")?;
619
620 if let KeybindUpdateOperation::Replace { source, target, .. } = operation {
621 let mut found_index = None;
622 let target_action_value = target
623 .action_value()
624 .context("Failed to generate target action JSON value")?;
625 let source_action_value = source
626 .action_value()
627 .context("Failed to generate source action JSON value")?;
628 'sections: for (index, section) in keymap.sections().enumerate() {
629 if section.context != target.context.unwrap_or("") {
630 continue;
631 }
632 if section.use_key_equivalents != target.use_key_equivalents {
633 continue;
634 }
635 let Some(bindings) = §ion.bindings else {
636 continue;
637 };
638 for (keystrokes, action) in bindings {
639 let Ok(keystrokes) = keystrokes
640 .split_whitespace()
641 .map(Keystroke::parse)
642 .collect::<Result<Vec<_>, _>>()
643 else {
644 continue;
645 };
646 if keystrokes != target.keystrokes {
647 continue;
648 }
649 if action.0 != target_action_value {
650 continue;
651 }
652 found_index = Some(index);
653 break 'sections;
654 }
655 }
656
657 if let Some(index) = found_index {
658 let (replace_range, replace_value) = replace_top_level_array_value_in_json_text(
659 &keymap_contents,
660 &["bindings", &target.keystrokes_unparsed()],
661 Some(&source_action_value),
662 Some(&source.keystrokes_unparsed()),
663 index,
664 tab_size,
665 )
666 .context("Failed to replace keybinding")?;
667 keymap_contents.replace_range(replace_range, &replace_value);
668
669 return Ok(keymap_contents);
670 } else {
671 log::warn!(
672 "Failed to find keybinding to update `{:?} -> {}` creating new binding for `{:?} -> {}` instead",
673 target.keystrokes,
674 target_action_value,
675 source.keystrokes,
676 source_action_value,
677 );
678 operation = KeybindUpdateOperation::Add(source);
679 }
680 }
681
682 if let KeybindUpdateOperation::Add(keybinding) = operation {
683 let mut value = serde_json::Map::with_capacity(4);
684 if let Some(context) = keybinding.context {
685 value.insert("context".to_string(), context.into());
686 }
687 if keybinding.use_key_equivalents {
688 value.insert("use_key_equivalents".to_string(), true.into());
689 }
690
691 value.insert("bindings".to_string(), {
692 let mut bindings = serde_json::Map::new();
693 let action = keybinding.action_value()?;
694 bindings.insert(keybinding.keystrokes_unparsed(), action);
695 bindings.into()
696 });
697
698 let (replace_range, replace_value) = append_top_level_array_value_in_json_text(
699 &keymap_contents,
700 &value.into(),
701 tab_size,
702 )?;
703 keymap_contents.replace_range(replace_range, &replace_value);
704 }
705 return Ok(keymap_contents);
706 }
707}
708
709pub enum KeybindUpdateOperation<'a> {
710 Replace {
711 /// Describes the keybind to create
712 source: KeybindUpdateTarget<'a>,
713 /// Describes the keybind to remove
714 target: KeybindUpdateTarget<'a>,
715 target_source: KeybindSource,
716 },
717 Add(KeybindUpdateTarget<'a>),
718}
719
720pub struct KeybindUpdateTarget<'a> {
721 pub context: Option<&'a str>,
722 pub keystrokes: &'a [Keystroke],
723 pub action_name: &'a str,
724 pub use_key_equivalents: bool,
725 pub input: Option<&'a str>,
726}
727
728impl<'a> KeybindUpdateTarget<'a> {
729 fn action_value(&self) -> Result<Value> {
730 let action_name: Value = self.action_name.into();
731 let value = match self.input {
732 Some(input) => {
733 let input = serde_json::from_str::<Value>(input)
734 .context("Failed to parse action input as JSON")?;
735 serde_json::json!([action_name, input])
736 }
737 None => action_name,
738 };
739 return Ok(value);
740 }
741
742 fn keystrokes_unparsed(&self) -> String {
743 let mut keystrokes = String::with_capacity(self.keystrokes.len() * 8);
744 for keystroke in self.keystrokes {
745 keystrokes.push_str(&keystroke.unparse());
746 keystrokes.push(' ');
747 }
748 keystrokes.pop();
749 keystrokes
750 }
751}
752
753#[derive(Clone, Copy, PartialEq, Eq)]
754pub enum KeybindSource {
755 User,
756 Default,
757 Base,
758 Vim,
759}
760
761impl KeybindSource {
762 const BASE: KeyBindingMetaIndex = KeyBindingMetaIndex(0);
763 const DEFAULT: KeyBindingMetaIndex = KeyBindingMetaIndex(1);
764 const VIM: KeyBindingMetaIndex = KeyBindingMetaIndex(2);
765 const USER: KeyBindingMetaIndex = KeyBindingMetaIndex(3);
766
767 pub fn name(&self) -> &'static str {
768 match self {
769 KeybindSource::User => "User",
770 KeybindSource::Default => "Default",
771 KeybindSource::Base => "Base",
772 KeybindSource::Vim => "Vim",
773 }
774 }
775
776 pub fn meta(&self) -> KeyBindingMetaIndex {
777 match self {
778 KeybindSource::User => Self::USER,
779 KeybindSource::Default => Self::DEFAULT,
780 KeybindSource::Base => Self::BASE,
781 KeybindSource::Vim => Self::VIM,
782 }
783 }
784
785 pub fn from_meta(index: KeyBindingMetaIndex) -> Self {
786 match index {
787 Self::USER => KeybindSource::User,
788 Self::BASE => KeybindSource::Base,
789 Self::DEFAULT => KeybindSource::Default,
790 Self::VIM => KeybindSource::Vim,
791 _ => unreachable!(),
792 }
793 }
794}
795
796impl From<KeyBindingMetaIndex> for KeybindSource {
797 fn from(index: KeyBindingMetaIndex) -> Self {
798 Self::from_meta(index)
799 }
800}
801
802impl From<KeybindSource> for KeyBindingMetaIndex {
803 fn from(source: KeybindSource) -> Self {
804 return source.meta();
805 }
806}
807
808#[cfg(test)]
809mod tests {
810 use unindent::Unindent;
811
812 use crate::{
813 KeybindSource, KeymapFile,
814 keymap_file::{KeybindUpdateOperation, KeybindUpdateTarget},
815 };
816
817 #[test]
818 fn can_deserialize_keymap_with_trailing_comma() {
819 let json = indoc::indoc! {"[
820 // Standard macOS bindings
821 {
822 \"bindings\": {
823 \"up\": \"menu::SelectPrevious\",
824 },
825 },
826 ]
827 "
828 };
829 KeymapFile::parse(json).unwrap();
830 }
831
832 #[test]
833 fn keymap_update() {
834 use gpui::Keystroke;
835
836 zlog::init_test();
837 #[track_caller]
838 fn check_keymap_update(
839 input: impl ToString,
840 operation: KeybindUpdateOperation,
841 expected: impl ToString,
842 ) {
843 let result = KeymapFile::update_keybinding(operation, input.to_string(), 4)
844 .expect("Update succeeded");
845 pretty_assertions::assert_eq!(expected.to_string(), result);
846 }
847
848 #[track_caller]
849 fn parse_keystrokes(keystrokes: &str) -> Vec<Keystroke> {
850 return keystrokes
851 .split(' ')
852 .map(|s| Keystroke::parse(s).expect("Keystrokes valid"))
853 .collect();
854 }
855
856 check_keymap_update(
857 "[]",
858 KeybindUpdateOperation::Add(KeybindUpdateTarget {
859 keystrokes: &parse_keystrokes("ctrl-a"),
860 action_name: "zed::SomeAction",
861 context: None,
862 use_key_equivalents: false,
863 input: None,
864 }),
865 r#"[
866 {
867 "bindings": {
868 "ctrl-a": "zed::SomeAction"
869 }
870 }
871 ]"#
872 .unindent(),
873 );
874
875 check_keymap_update(
876 r#"[
877 {
878 "bindings": {
879 "ctrl-a": "zed::SomeAction"
880 }
881 }
882 ]"#
883 .unindent(),
884 KeybindUpdateOperation::Add(KeybindUpdateTarget {
885 keystrokes: &parse_keystrokes("ctrl-b"),
886 action_name: "zed::SomeOtherAction",
887 context: None,
888 use_key_equivalents: false,
889 input: None,
890 }),
891 r#"[
892 {
893 "bindings": {
894 "ctrl-a": "zed::SomeAction"
895 }
896 },
897 {
898 "bindings": {
899 "ctrl-b": "zed::SomeOtherAction"
900 }
901 }
902 ]"#
903 .unindent(),
904 );
905
906 check_keymap_update(
907 r#"[
908 {
909 "bindings": {
910 "ctrl-a": "zed::SomeAction"
911 }
912 }
913 ]"#
914 .unindent(),
915 KeybindUpdateOperation::Add(KeybindUpdateTarget {
916 keystrokes: &parse_keystrokes("ctrl-b"),
917 action_name: "zed::SomeOtherAction",
918 context: None,
919 use_key_equivalents: false,
920 input: Some(r#"{"foo": "bar"}"#),
921 }),
922 r#"[
923 {
924 "bindings": {
925 "ctrl-a": "zed::SomeAction"
926 }
927 },
928 {
929 "bindings": {
930 "ctrl-b": [
931 "zed::SomeOtherAction",
932 {
933 "foo": "bar"
934 }
935 ]
936 }
937 }
938 ]"#
939 .unindent(),
940 );
941
942 check_keymap_update(
943 r#"[
944 {
945 "bindings": {
946 "ctrl-a": "zed::SomeAction"
947 }
948 }
949 ]"#
950 .unindent(),
951 KeybindUpdateOperation::Add(KeybindUpdateTarget {
952 keystrokes: &parse_keystrokes("ctrl-b"),
953 action_name: "zed::SomeOtherAction",
954 context: Some("Zed > Editor && some_condition = true"),
955 use_key_equivalents: true,
956 input: Some(r#"{"foo": "bar"}"#),
957 }),
958 r#"[
959 {
960 "bindings": {
961 "ctrl-a": "zed::SomeAction"
962 }
963 },
964 {
965 "context": "Zed > Editor && some_condition = true",
966 "use_key_equivalents": true,
967 "bindings": {
968 "ctrl-b": [
969 "zed::SomeOtherAction",
970 {
971 "foo": "bar"
972 }
973 ]
974 }
975 }
976 ]"#
977 .unindent(),
978 );
979
980 check_keymap_update(
981 r#"[
982 {
983 "bindings": {
984 "ctrl-a": "zed::SomeAction"
985 }
986 }
987 ]"#
988 .unindent(),
989 KeybindUpdateOperation::Replace {
990 target: KeybindUpdateTarget {
991 keystrokes: &parse_keystrokes("ctrl-a"),
992 action_name: "zed::SomeAction",
993 context: None,
994 use_key_equivalents: false,
995 input: None,
996 },
997 source: KeybindUpdateTarget {
998 keystrokes: &parse_keystrokes("ctrl-b"),
999 action_name: "zed::SomeOtherAction",
1000 context: None,
1001 use_key_equivalents: false,
1002 input: Some(r#"{"foo": "bar"}"#),
1003 },
1004 target_source: KeybindSource::Base,
1005 },
1006 r#"[
1007 {
1008 "bindings": {
1009 "ctrl-a": "zed::SomeAction"
1010 }
1011 },
1012 {
1013 "bindings": {
1014 "ctrl-b": [
1015 "zed::SomeOtherAction",
1016 {
1017 "foo": "bar"
1018 }
1019 ]
1020 }
1021 }
1022 ]"#
1023 .unindent(),
1024 );
1025
1026 check_keymap_update(
1027 r#"[
1028 {
1029 "bindings": {
1030 "ctrl-a": "zed::SomeAction"
1031 }
1032 }
1033 ]"#
1034 .unindent(),
1035 KeybindUpdateOperation::Replace {
1036 target: KeybindUpdateTarget {
1037 keystrokes: &parse_keystrokes("ctrl-a"),
1038 action_name: "zed::SomeAction",
1039 context: None,
1040 use_key_equivalents: false,
1041 input: None,
1042 },
1043 source: KeybindUpdateTarget {
1044 keystrokes: &parse_keystrokes("ctrl-b"),
1045 action_name: "zed::SomeOtherAction",
1046 context: None,
1047 use_key_equivalents: false,
1048 input: Some(r#"{"foo": "bar"}"#),
1049 },
1050 target_source: KeybindSource::User,
1051 },
1052 r#"[
1053 {
1054 "bindings": {
1055 "ctrl-b": [
1056 "zed::SomeOtherAction",
1057 {
1058 "foo": "bar"
1059 }
1060 ]
1061 }
1062 }
1063 ]"#
1064 .unindent(),
1065 );
1066
1067 check_keymap_update(
1068 r#"[
1069 {
1070 "bindings": {
1071 "ctrl-a": "zed::SomeAction"
1072 }
1073 }
1074 ]"#
1075 .unindent(),
1076 KeybindUpdateOperation::Replace {
1077 target: KeybindUpdateTarget {
1078 keystrokes: &parse_keystrokes("ctrl-a"),
1079 action_name: "zed::SomeNonexistentAction",
1080 context: None,
1081 use_key_equivalents: false,
1082 input: None,
1083 },
1084 source: KeybindUpdateTarget {
1085 keystrokes: &parse_keystrokes("ctrl-b"),
1086 action_name: "zed::SomeOtherAction",
1087 context: None,
1088 use_key_equivalents: false,
1089 input: None,
1090 },
1091 target_source: KeybindSource::User,
1092 },
1093 r#"[
1094 {
1095 "bindings": {
1096 "ctrl-a": "zed::SomeAction"
1097 }
1098 },
1099 {
1100 "bindings": {
1101 "ctrl-b": "zed::SomeOtherAction"
1102 }
1103 }
1104 ]"#
1105 .unindent(),
1106 );
1107
1108 check_keymap_update(
1109 r#"[
1110 {
1111 "bindings": {
1112 // some comment
1113 "ctrl-a": "zed::SomeAction"
1114 // some other comment
1115 }
1116 }
1117 ]"#
1118 .unindent(),
1119 KeybindUpdateOperation::Replace {
1120 target: KeybindUpdateTarget {
1121 keystrokes: &parse_keystrokes("ctrl-a"),
1122 action_name: "zed::SomeAction",
1123 context: None,
1124 use_key_equivalents: false,
1125 input: None,
1126 },
1127 source: KeybindUpdateTarget {
1128 keystrokes: &parse_keystrokes("ctrl-b"),
1129 action_name: "zed::SomeOtherAction",
1130 context: None,
1131 use_key_equivalents: false,
1132 input: Some(r#"{"foo": "bar"}"#),
1133 },
1134 target_source: KeybindSource::User,
1135 },
1136 r#"[
1137 {
1138 "bindings": {
1139 // some comment
1140 "ctrl-b": [
1141 "zed::SomeOtherAction",
1142 {
1143 "foo": "bar"
1144 }
1145 ]
1146 // some other comment
1147 }
1148 }
1149 ]"#
1150 .unindent(),
1151 );
1152 }
1153}