1use std::{
2 cmp::{self},
3 ops::{Not as _, Range},
4 sync::Arc,
5 time::Duration,
6};
7
8mod ui_components;
9
10use anyhow::{Context as _, anyhow};
11use collections::{HashMap, HashSet};
12use editor::{CompletionProvider, Editor, EditorEvent};
13use fs::Fs;
14use fuzzy::{StringMatch, StringMatchCandidate};
15use gpui::{
16 Action, AppContext as _, AsyncApp, ClickEvent, Context, DismissEvent, Entity, EventEmitter,
17 FocusHandle, Focusable, Global, IsZero,
18 KeyBindingContextPredicate::{And, Descendant, Equal, Identifier, Not, NotEqual, Or},
19 KeyContext, KeybindingKeystroke, MouseButton, PlatformKeyboardMapper, Point, ScrollStrategy,
20 ScrollWheelEvent, Stateful, StyledText, Subscription, Task, TextStyleRefinement, WeakEntity,
21 actions, anchored, deferred, div,
22};
23use language::{Language, LanguageConfig, ToOffset as _};
24use notifications::status_toast::{StatusToast, ToastIcon};
25use project::{CompletionDisplayOptions, Project};
26use settings::{BaseKeymap, KeybindSource, KeymapFile, Settings as _, SettingsAssets};
27use ui::{
28 ActiveTheme as _, App, Banner, BorrowAppContext, ContextMenu, IconButtonShape, Indicator,
29 Modal, ModalFooter, ModalHeader, ParentElement as _, PopoverMenu, Render, Section,
30 SharedString, Styled as _, Table, TableColumnWidths, TableInteractionState,
31 TableResizeBehavior, Tooltip, Window, prelude::*,
32};
33use ui_input::SingleLineInput;
34use util::ResultExt;
35use workspace::{
36 Item, ModalView, SerializableItem, Workspace, notifications::NotifyTaskExt as _,
37 register_serializable_item,
38};
39
40pub use ui_components::*;
41use zed_actions::OpenKeymapEditor;
42
43use crate::{
44 persistence::KEYBINDING_EDITORS,
45 ui_components::keystroke_input::{
46 ClearKeystrokes, KeystrokeInput, StartRecording, StopRecording,
47 },
48};
49
50const NO_ACTION_ARGUMENTS_TEXT: SharedString = SharedString::new_static("<no arguments>");
51
52actions!(
53 keymap_editor,
54 [
55 /// Edits the selected key binding.
56 EditBinding,
57 /// Creates a new key binding for the selected action.
58 CreateBinding,
59 /// Deletes the selected key binding.
60 DeleteBinding,
61 /// Copies the action name to clipboard.
62 CopyAction,
63 /// Copies the context predicate to clipboard.
64 CopyContext,
65 /// Toggles Conflict Filtering
66 ToggleConflictFilter,
67 /// Toggle Keystroke search
68 ToggleKeystrokeSearch,
69 /// Toggles exact matching for keystroke search
70 ToggleExactKeystrokeMatching,
71 /// Shows matching keystrokes for the currently selected binding
72 ShowMatchingKeybinds
73 ]
74);
75
76pub fn init(cx: &mut App) {
77 let keymap_event_channel = KeymapEventChannel::new();
78 cx.set_global(keymap_event_channel);
79
80 cx.on_action(|_: &OpenKeymapEditor, cx| {
81 workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
82 workspace
83 .with_local_workspace(window, cx, |workspace, window, cx| {
84 let existing = workspace
85 .active_pane()
86 .read(cx)
87 .items()
88 .find_map(|item| item.downcast::<KeymapEditor>());
89
90 if let Some(existing) = existing {
91 workspace.activate_item(&existing, true, true, window, cx);
92 } else {
93 let keymap_editor =
94 cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
95 workspace.add_item_to_active_pane(
96 Box::new(keymap_editor),
97 None,
98 true,
99 window,
100 cx,
101 );
102 }
103 })
104 .detach();
105 })
106 });
107
108 register_serializable_item::<KeymapEditor>(cx);
109}
110
111pub struct KeymapEventChannel {}
112
113impl Global for KeymapEventChannel {}
114
115impl KeymapEventChannel {
116 fn new() -> Self {
117 Self {}
118 }
119
120 pub fn trigger_keymap_changed(cx: &mut App) {
121 let Some(_event_channel) = cx.try_global::<Self>() else {
122 // don't panic if no global defined. This usually happens in tests
123 return;
124 };
125 cx.update_global(|_event_channel: &mut Self, _| {
126 /* triggers observers in KeymapEditors */
127 });
128 }
129}
130
131#[derive(Default, PartialEq)]
132enum SearchMode {
133 #[default]
134 Normal,
135 KeyStroke {
136 exact_match: bool,
137 },
138}
139
140impl SearchMode {
141 fn invert(&self) -> Self {
142 match self {
143 SearchMode::Normal => SearchMode::KeyStroke { exact_match: false },
144 SearchMode::KeyStroke { .. } => SearchMode::Normal,
145 }
146 }
147
148 fn exact_match(&self) -> bool {
149 match self {
150 SearchMode::Normal => false,
151 SearchMode::KeyStroke { exact_match } => *exact_match,
152 }
153 }
154}
155
156#[derive(Default, PartialEq, Copy, Clone)]
157enum FilterState {
158 #[default]
159 All,
160 Conflicts,
161}
162
163impl FilterState {
164 fn invert(&self) -> Self {
165 match self {
166 FilterState::All => FilterState::Conflicts,
167 FilterState::Conflicts => FilterState::All,
168 }
169 }
170}
171
172#[derive(Debug, Default, PartialEq, Eq, Clone, Hash)]
173struct ActionMapping {
174 keystrokes: Vec<KeybindingKeystroke>,
175 context: Option<SharedString>,
176}
177
178#[derive(Debug)]
179struct KeybindConflict {
180 first_conflict_index: usize,
181 remaining_conflict_amount: usize,
182}
183
184#[derive(Clone, Copy, PartialEq)]
185struct ConflictOrigin {
186 override_source: KeybindSource,
187 overridden_source: Option<KeybindSource>,
188 index: usize,
189}
190
191impl ConflictOrigin {
192 fn new(source: KeybindSource, index: usize) -> Self {
193 Self {
194 override_source: source,
195 index,
196 overridden_source: None,
197 }
198 }
199
200 fn with_overridden_source(self, source: KeybindSource) -> Self {
201 Self {
202 overridden_source: Some(source),
203 ..self
204 }
205 }
206
207 fn get_conflict_with(&self, other: &Self) -> Option<Self> {
208 if self.override_source == KeybindSource::User
209 && other.override_source == KeybindSource::User
210 {
211 Some(
212 Self::new(KeybindSource::User, other.index)
213 .with_overridden_source(self.override_source),
214 )
215 } else if self.override_source > other.override_source {
216 Some(other.with_overridden_source(self.override_source))
217 } else {
218 None
219 }
220 }
221
222 fn is_user_keybind_conflict(&self) -> bool {
223 self.override_source == KeybindSource::User
224 && self.overridden_source == Some(KeybindSource::User)
225 }
226}
227
228#[derive(Default)]
229struct ConflictState {
230 conflicts: Vec<Option<ConflictOrigin>>,
231 keybind_mapping: ConflictKeybindMapping,
232 has_user_conflicts: bool,
233}
234
235type ConflictKeybindMapping = HashMap<
236 Vec<KeybindingKeystroke>,
237 Vec<(
238 Option<gpui::KeyBindingContextPredicate>,
239 Vec<ConflictOrigin>,
240 )>,
241>;
242
243impl ConflictState {
244 fn new(key_bindings: &[ProcessedBinding]) -> Self {
245 let mut action_keybind_mapping = ConflictKeybindMapping::default();
246
247 let mut largest_index = 0;
248 for (index, binding) in key_bindings
249 .iter()
250 .enumerate()
251 .flat_map(|(index, binding)| Some(index).zip(binding.keybind_information()))
252 {
253 let mapping = binding.get_action_mapping();
254 let predicate = mapping
255 .context
256 .and_then(|ctx| gpui::KeyBindingContextPredicate::parse(&ctx).ok());
257 let entry = action_keybind_mapping
258 .entry(mapping.keystrokes)
259 .or_default();
260 let origin = ConflictOrigin::new(binding.source, index);
261 if let Some((_, origins)) =
262 entry
263 .iter_mut()
264 .find(|(other_predicate, _)| match (&predicate, other_predicate) {
265 (None, None) => true,
266 (Some(a), Some(b)) => normalized_ctx_eq(a, b),
267 _ => false,
268 })
269 {
270 origins.push(origin);
271 } else {
272 entry.push((predicate, vec![origin]));
273 }
274 largest_index = index;
275 }
276
277 let mut conflicts = vec![None; largest_index + 1];
278 let mut has_user_conflicts = false;
279
280 for entries in action_keybind_mapping.values_mut() {
281 for (_, indices) in entries.iter_mut() {
282 indices.sort_unstable_by_key(|origin| origin.override_source);
283 let Some((fst, snd)) = indices.get(0).zip(indices.get(1)) else {
284 continue;
285 };
286
287 for origin in indices.iter() {
288 conflicts[origin.index] =
289 origin.get_conflict_with(if origin == fst { snd } else { fst })
290 }
291
292 has_user_conflicts |= fst.override_source == KeybindSource::User
293 && snd.override_source == KeybindSource::User;
294 }
295 }
296
297 Self {
298 conflicts,
299 keybind_mapping: action_keybind_mapping,
300 has_user_conflicts,
301 }
302 }
303
304 fn conflicting_indices_for_mapping(
305 &self,
306 action_mapping: &ActionMapping,
307 keybind_idx: Option<usize>,
308 ) -> Option<KeybindConflict> {
309 let ActionMapping {
310 keystrokes,
311 context,
312 } = action_mapping;
313 let predicate = context
314 .as_deref()
315 .and_then(|ctx| gpui::KeyBindingContextPredicate::parse(&ctx).ok());
316 self.keybind_mapping.get(keystrokes).and_then(|entries| {
317 entries
318 .iter()
319 .find_map(|(other_predicate, indices)| {
320 match (&predicate, other_predicate) {
321 (None, None) => true,
322 (Some(pred), Some(other)) => normalized_ctx_eq(pred, other),
323 _ => false,
324 }
325 .then_some(indices)
326 })
327 .and_then(|indices| {
328 let mut indices = indices
329 .iter()
330 .filter(|&conflict| Some(conflict.index) != keybind_idx);
331 indices.next().map(|origin| KeybindConflict {
332 first_conflict_index: origin.index,
333 remaining_conflict_amount: indices.count(),
334 })
335 })
336 })
337 }
338
339 fn conflict_for_idx(&self, idx: usize) -> Option<ConflictOrigin> {
340 self.conflicts.get(idx).copied().flatten()
341 }
342
343 fn has_user_conflict(&self, candidate_idx: usize) -> bool {
344 self.conflict_for_idx(candidate_idx)
345 .is_some_and(|conflict| conflict.is_user_keybind_conflict())
346 }
347
348 fn any_user_binding_conflicts(&self) -> bool {
349 self.has_user_conflicts
350 }
351}
352
353struct KeymapEditor {
354 workspace: WeakEntity<Workspace>,
355 focus_handle: FocusHandle,
356 _keymap_subscription: Subscription,
357 keybindings: Vec<ProcessedBinding>,
358 keybinding_conflict_state: ConflictState,
359 filter_state: FilterState,
360 search_mode: SearchMode,
361 search_query_debounce: Option<Task<()>>,
362 // corresponds 1 to 1 with keybindings
363 string_match_candidates: Arc<Vec<StringMatchCandidate>>,
364 matches: Vec<StringMatch>,
365 table_interaction_state: Entity<TableInteractionState>,
366 filter_editor: Entity<Editor>,
367 keystroke_editor: Entity<KeystrokeInput>,
368 selected_index: Option<usize>,
369 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
370 previous_edit: Option<PreviousEdit>,
371 humanized_action_names: HumanizedActionNameCache,
372 current_widths: Entity<TableColumnWidths<6>>,
373 show_hover_menus: bool,
374 /// In order for the JSON LSP to run in the actions arguments editor, we
375 /// require a backing file In order to avoid issues (primarily log spam)
376 /// with drop order between the buffer, file, worktree, etc, we create a
377 /// temporary directory for these backing files in the keymap editor struct
378 /// instead of here. This has the added benefit of only having to create a
379 /// worktree and directory once, although the perf improvement is negligible.
380 action_args_temp_dir_worktree: Option<Entity<project::Worktree>>,
381 action_args_temp_dir: Option<tempfile::TempDir>,
382}
383
384enum PreviousEdit {
385 /// When deleting, we want to maintain the same scroll position
386 ScrollBarOffset(Point<Pixels>),
387 /// When editing or creating, because the new keybinding could be in a different position in the sort order
388 /// we store metadata about the new binding (either the modified version or newly created one)
389 /// and upon reload, we search for this binding in the list of keybindings, and if we find the one that matches
390 /// this metadata, we set the selected index to it and scroll to it,
391 /// and if we don't find it, we scroll to 0 and don't set a selected index
392 Keybinding {
393 action_mapping: ActionMapping,
394 action_name: &'static str,
395 /// The scrollbar position to fallback to if we don't find the keybinding during a refresh
396 /// this can happen if there's a filter applied to the search and the keybinding modification
397 /// filters the binding from the search results
398 fallback: Point<Pixels>,
399 },
400}
401
402impl EventEmitter<()> for KeymapEditor {}
403
404impl Focusable for KeymapEditor {
405 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
406 if self.selected_index.is_some() {
407 self.focus_handle.clone()
408 } else {
409 self.filter_editor.focus_handle(cx)
410 }
411 }
412}
413/// Helper function to check if two keystroke sequences match exactly
414fn keystrokes_match_exactly(
415 keystrokes1: &[KeybindingKeystroke],
416 keystrokes2: &[KeybindingKeystroke],
417) -> bool {
418 keystrokes1.len() == keystrokes2.len()
419 && keystrokes1.iter().zip(keystrokes2).all(|(k1, k2)| {
420 k1.inner().key == k2.inner().key && k1.inner().modifiers == k2.inner().modifiers
421 })
422}
423
424impl KeymapEditor {
425 fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
426 let _keymap_subscription =
427 cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed);
428 let table_interaction_state = cx.new(|cx| {
429 TableInteractionState::new(cx)
430 .with_custom_scrollbar(ui::Scrollbars::for_settings::<editor::EditorSettings>())
431 });
432
433 let keystroke_editor = cx.new(|cx| {
434 let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
435 keystroke_editor.set_search(true);
436 keystroke_editor
437 });
438
439 let filter_editor = cx.new(|cx| {
440 let mut editor = Editor::single_line(window, cx);
441 editor.set_placeholder_text("Filter action names…", window, cx);
442 editor
443 });
444
445 cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
446 if !matches!(e, EditorEvent::BufferEdited) {
447 return;
448 }
449
450 this.on_query_changed(cx);
451 })
452 .detach();
453
454 cx.subscribe(&keystroke_editor, |this, _, _, cx| {
455 if matches!(this.search_mode, SearchMode::Normal) {
456 return;
457 }
458
459 this.on_query_changed(cx);
460 })
461 .detach();
462
463 cx.spawn({
464 let workspace = workspace.clone();
465 async move |this, cx| {
466 let temp_dir = tempfile::tempdir_in(paths::temp_dir())?;
467 let worktree = workspace
468 .update(cx, |ws, cx| {
469 ws.project()
470 .update(cx, |p, cx| p.create_worktree(temp_dir.path(), false, cx))
471 })?
472 .await?;
473 this.update(cx, |this, _| {
474 this.action_args_temp_dir = Some(temp_dir);
475 this.action_args_temp_dir_worktree = Some(worktree);
476 })
477 }
478 })
479 .detach();
480
481 let mut this = Self {
482 workspace,
483 keybindings: vec![],
484 keybinding_conflict_state: ConflictState::default(),
485 filter_state: FilterState::default(),
486 search_mode: SearchMode::default(),
487 string_match_candidates: Arc::new(vec![]),
488 matches: vec![],
489 focus_handle: cx.focus_handle(),
490 _keymap_subscription,
491 table_interaction_state,
492 filter_editor,
493 keystroke_editor,
494 selected_index: None,
495 context_menu: None,
496 previous_edit: None,
497 search_query_debounce: None,
498 humanized_action_names: HumanizedActionNameCache::new(cx),
499 show_hover_menus: true,
500 action_args_temp_dir: None,
501 action_args_temp_dir_worktree: None,
502 current_widths: cx.new(|cx| TableColumnWidths::new(cx)),
503 };
504
505 this.on_keymap_changed(window, cx);
506
507 this
508 }
509
510 fn current_action_query(&self, cx: &App) -> String {
511 self.filter_editor.read(cx).text(cx)
512 }
513
514 fn current_keystroke_query(&self, cx: &App) -> Vec<KeybindingKeystroke> {
515 match self.search_mode {
516 SearchMode::KeyStroke { .. } => self.keystroke_editor.read(cx).keystrokes().to_vec(),
517 SearchMode::Normal => Default::default(),
518 }
519 }
520
521 fn on_query_changed(&mut self, cx: &mut Context<Self>) {
522 let action_query = self.current_action_query(cx);
523 let keystroke_query = self.current_keystroke_query(cx);
524 let exact_match = self.search_mode.exact_match();
525
526 let timer = cx.background_executor().timer(Duration::from_secs(1));
527 self.search_query_debounce = Some(cx.background_spawn({
528 let action_query = action_query.clone();
529 let keystroke_query = keystroke_query.clone();
530 async move {
531 timer.await;
532
533 let keystroke_query = keystroke_query
534 .into_iter()
535 .map(|keystroke| keystroke.inner().unparse())
536 .collect::<Vec<String>>()
537 .join(" ");
538
539 telemetry::event!(
540 "Keystroke Search Completed",
541 action_query = action_query,
542 keystroke_query = keystroke_query,
543 keystroke_exact_match = exact_match
544 )
545 }
546 }));
547 cx.spawn(async move |this, cx| {
548 Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
549 this.update(cx, |this, cx| {
550 this.scroll_to_item(0, ScrollStrategy::Top, cx)
551 })
552 })
553 .detach();
554 }
555
556 async fn update_matches(
557 this: WeakEntity<Self>,
558 action_query: String,
559 keystroke_query: Vec<KeybindingKeystroke>,
560 cx: &mut AsyncApp,
561 ) -> anyhow::Result<()> {
562 let action_query = command_palette::normalize_action_query(&action_query);
563 let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
564 (this.string_match_candidates.clone(), this.keybindings.len())
565 })?;
566 let executor = cx.background_executor().clone();
567 let mut matches = fuzzy::match_strings(
568 &string_match_candidates,
569 &action_query,
570 true,
571 true,
572 keybind_count,
573 &Default::default(),
574 executor,
575 )
576 .await;
577 this.update(cx, |this, cx| {
578 match this.filter_state {
579 FilterState::Conflicts => {
580 matches.retain(|candidate| {
581 this.keybinding_conflict_state
582 .has_user_conflict(candidate.candidate_id)
583 });
584 }
585 FilterState::All => {}
586 }
587
588 match this.search_mode {
589 SearchMode::KeyStroke { exact_match } => {
590 matches.retain(|item| {
591 this.keybindings[item.candidate_id]
592 .keystrokes()
593 .is_some_and(|keystrokes| {
594 if exact_match {
595 keystrokes_match_exactly(&keystroke_query, keystrokes)
596 } else if keystroke_query.len() > keystrokes.len() {
597 false
598 } else {
599 for keystroke_offset in 0..keystrokes.len() {
600 let mut found_count = 0;
601 let mut query_cursor = 0;
602 let mut keystroke_cursor = keystroke_offset;
603 while query_cursor < keystroke_query.len()
604 && keystroke_cursor < keystrokes.len()
605 {
606 let query = &keystroke_query[query_cursor];
607 let keystroke = &keystrokes[keystroke_cursor];
608 let matches = query
609 .inner()
610 .modifiers
611 .is_subset_of(&keystroke.inner().modifiers)
612 && ((query.inner().key.is_empty()
613 || query.inner().key == keystroke.inner().key)
614 && query.inner().key_char.as_ref().is_none_or(
615 |q_kc| q_kc == &keystroke.inner().key,
616 ));
617 if matches {
618 found_count += 1;
619 query_cursor += 1;
620 }
621 keystroke_cursor += 1;
622 }
623
624 if found_count == keystroke_query.len() {
625 return true;
626 }
627 }
628 false
629 }
630 })
631 });
632 }
633 SearchMode::Normal => {}
634 }
635
636 if action_query.is_empty() {
637 matches.sort_by(|item1, item2| {
638 let binding1 = &this.keybindings[item1.candidate_id];
639 let binding2 = &this.keybindings[item2.candidate_id];
640
641 binding1.cmp(binding2)
642 });
643 }
644 this.selected_index.take();
645 this.matches = matches;
646
647 cx.notify();
648 })
649 }
650
651 fn get_conflict(&self, row_index: usize) -> Option<ConflictOrigin> {
652 self.matches.get(row_index).and_then(|candidate| {
653 self.keybinding_conflict_state
654 .conflict_for_idx(candidate.candidate_id)
655 })
656 }
657
658 fn process_bindings(
659 json_language: Arc<Language>,
660 zed_keybind_context_language: Arc<Language>,
661 humanized_action_names: &HumanizedActionNameCache,
662 cx: &mut App,
663 ) -> (Vec<ProcessedBinding>, Vec<StringMatchCandidate>) {
664 let key_bindings_ptr = cx.key_bindings();
665 let lock = key_bindings_ptr.borrow();
666 let key_bindings = lock.bindings();
667 let mut unmapped_action_names = HashSet::from_iter(cx.all_action_names().iter().copied());
668 let action_documentation = cx.action_documentation();
669 let mut generator = KeymapFile::action_schema_generator();
670 let actions_with_schemas = HashSet::from_iter(
671 cx.action_schemas(&mut generator)
672 .into_iter()
673 .filter_map(|(name, schema)| schema.is_some().then_some(name)),
674 );
675
676 let mut processed_bindings = Vec::new();
677 let mut string_match_candidates = Vec::new();
678
679 for key_binding in key_bindings {
680 let source = key_binding
681 .meta()
682 .map(KeybindSource::from_meta)
683 .unwrap_or(KeybindSource::Unknown);
684
685 let keystroke_text = ui::text_for_keybinding_keystrokes(key_binding.keystrokes(), cx);
686 let ui_key_binding = ui::KeyBinding::new_from_gpui(key_binding.clone(), cx)
687 .vim_mode(source == KeybindSource::Vim);
688
689 let context = key_binding
690 .predicate()
691 .map(|predicate| {
692 KeybindContextString::Local(
693 predicate.to_string().into(),
694 zed_keybind_context_language.clone(),
695 )
696 })
697 .unwrap_or(KeybindContextString::Global);
698
699 let action_name = key_binding.action().name();
700 unmapped_action_names.remove(&action_name);
701
702 let action_arguments = key_binding
703 .action_input()
704 .map(|arguments| SyntaxHighlightedText::new(arguments, json_language.clone()));
705 let action_information = ActionInformation::new(
706 action_name,
707 action_arguments,
708 &actions_with_schemas,
709 action_documentation,
710 humanized_action_names,
711 );
712
713 let index = processed_bindings.len();
714 let string_match_candidate =
715 StringMatchCandidate::new(index, &action_information.humanized_name);
716 processed_bindings.push(ProcessedBinding::new_mapped(
717 keystroke_text,
718 ui_key_binding,
719 context,
720 source,
721 action_information,
722 ));
723 string_match_candidates.push(string_match_candidate);
724 }
725
726 for action_name in unmapped_action_names.into_iter() {
727 let index = processed_bindings.len();
728 let action_information = ActionInformation::new(
729 action_name,
730 None,
731 &actions_with_schemas,
732 action_documentation,
733 humanized_action_names,
734 );
735 let string_match_candidate =
736 StringMatchCandidate::new(index, &action_information.humanized_name);
737
738 processed_bindings.push(ProcessedBinding::Unmapped(action_information));
739 string_match_candidates.push(string_match_candidate);
740 }
741
742 (processed_bindings, string_match_candidates)
743 }
744
745 fn on_keymap_changed(&mut self, window: &mut Window, cx: &mut Context<KeymapEditor>) {
746 let workspace = self.workspace.clone();
747 cx.spawn_in(window, async move |this, cx| {
748 let json_language = load_json_language(workspace.clone(), cx).await;
749 let zed_keybind_context_language =
750 load_keybind_context_language(workspace.clone(), cx).await;
751
752 let (action_query, keystroke_query) = this.update(cx, |this, cx| {
753 let (key_bindings, string_match_candidates) = Self::process_bindings(
754 json_language,
755 zed_keybind_context_language,
756 &this.humanized_action_names,
757 cx,
758 );
759
760 this.keybinding_conflict_state = ConflictState::new(&key_bindings);
761
762 this.keybindings = key_bindings;
763 this.string_match_candidates = Arc::new(string_match_candidates);
764 this.matches = this
765 .string_match_candidates
766 .iter()
767 .enumerate()
768 .map(|(ix, candidate)| StringMatch {
769 candidate_id: ix,
770 score: 0.0,
771 positions: vec![],
772 string: candidate.string.clone(),
773 })
774 .collect();
775 (
776 this.current_action_query(cx),
777 this.current_keystroke_query(cx),
778 )
779 })?;
780 // calls cx.notify
781 Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
782 this.update_in(cx, |this, window, cx| {
783 if let Some(previous_edit) = this.previous_edit.take() {
784 match previous_edit {
785 // should remove scroll from process_query
786 PreviousEdit::ScrollBarOffset(offset) => {
787 this.table_interaction_state
788 .update(cx, |table, _| table.set_scroll_offset(offset))
789 // set selected index and scroll
790 }
791 PreviousEdit::Keybinding {
792 action_mapping,
793 action_name,
794 fallback,
795 } => {
796 let scroll_position =
797 this.matches.iter().enumerate().find_map(|(index, item)| {
798 let binding = &this.keybindings[item.candidate_id];
799 if binding.get_action_mapping().is_some_and(|binding_mapping| {
800 binding_mapping == action_mapping
801 }) && binding.action().name == action_name
802 {
803 Some(index)
804 } else {
805 None
806 }
807 });
808
809 if let Some(scroll_position) = scroll_position {
810 this.select_index(
811 scroll_position,
812 Some(ScrollStrategy::Top),
813 window,
814 cx,
815 );
816 } else {
817 this.table_interaction_state
818 .update(cx, |table, _| table.set_scroll_offset(fallback));
819 }
820 cx.notify();
821 }
822 }
823 }
824 })
825 })
826 .detach_and_log_err(cx);
827 }
828
829 fn key_context(&self) -> KeyContext {
830 let mut dispatch_context = KeyContext::new_with_defaults();
831 dispatch_context.add("KeymapEditor");
832 dispatch_context.add("menu");
833
834 dispatch_context
835 }
836
837 fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
838 let index = usize::min(index, self.matches.len().saturating_sub(1));
839 self.table_interaction_state.update(cx, |this, _cx| {
840 this.scroll_handle.scroll_to_item(index, strategy);
841 });
842 }
843
844 fn focus_search(
845 &mut self,
846 _: &search::FocusSearch,
847 window: &mut Window,
848 cx: &mut Context<Self>,
849 ) {
850 if !self
851 .filter_editor
852 .focus_handle(cx)
853 .contains_focused(window, cx)
854 {
855 window.focus(&self.filter_editor.focus_handle(cx));
856 } else {
857 self.filter_editor.update(cx, |editor, cx| {
858 editor.select_all(&Default::default(), window, cx);
859 });
860 }
861 self.selected_index.take();
862 }
863
864 fn selected_keybind_index(&self) -> Option<usize> {
865 self.selected_index
866 .and_then(|match_index| self.matches.get(match_index))
867 .map(|r#match| r#match.candidate_id)
868 }
869
870 fn selected_keybind_and_index(&self) -> Option<(&ProcessedBinding, usize)> {
871 self.selected_keybind_index()
872 .map(|keybind_index| (&self.keybindings[keybind_index], keybind_index))
873 }
874
875 fn selected_binding(&self) -> Option<&ProcessedBinding> {
876 self.selected_keybind_index()
877 .and_then(|keybind_index| self.keybindings.get(keybind_index))
878 }
879
880 fn select_index(
881 &mut self,
882 index: usize,
883 scroll: Option<ScrollStrategy>,
884 window: &mut Window,
885 cx: &mut Context<Self>,
886 ) {
887 if self.selected_index != Some(index) {
888 self.selected_index = Some(index);
889 if let Some(scroll_strategy) = scroll {
890 self.scroll_to_item(index, scroll_strategy, cx);
891 }
892 window.focus(&self.focus_handle);
893 cx.notify();
894 }
895 }
896
897 fn create_context_menu(
898 &mut self,
899 position: Point<Pixels>,
900 window: &mut Window,
901 cx: &mut Context<Self>,
902 ) {
903 self.context_menu = self.selected_binding().map(|selected_binding| {
904 let selected_binding_has_no_context = selected_binding
905 .context()
906 .and_then(KeybindContextString::local)
907 .is_none();
908
909 let selected_binding_is_unbound = selected_binding.is_unbound();
910
911 let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
912 menu.context(self.focus_handle.clone())
913 .action_disabled_when(
914 selected_binding_is_unbound,
915 "Edit",
916 Box::new(EditBinding),
917 )
918 .action("Create", Box::new(CreateBinding))
919 .action_disabled_when(
920 selected_binding_is_unbound,
921 "Delete",
922 Box::new(DeleteBinding),
923 )
924 .separator()
925 .action("Copy Action", Box::new(CopyAction))
926 .action_disabled_when(
927 selected_binding_has_no_context,
928 "Copy Context",
929 Box::new(CopyContext),
930 )
931 .separator()
932 .action_disabled_when(
933 selected_binding_has_no_context,
934 "Show Matching Keybindings",
935 Box::new(ShowMatchingKeybinds),
936 )
937 });
938
939 let context_menu_handle = context_menu.focus_handle(cx);
940 window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
941 let subscription = cx.subscribe_in(
942 &context_menu,
943 window,
944 |this, _, _: &DismissEvent, window, cx| {
945 this.dismiss_context_menu(window, cx);
946 },
947 );
948 (context_menu, position, subscription)
949 });
950
951 cx.notify();
952 }
953
954 fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
955 self.context_menu.take();
956 window.focus(&self.focus_handle);
957 cx.notify();
958 }
959
960 fn context_menu_deployed(&self) -> bool {
961 self.context_menu.is_some()
962 }
963
964 fn create_row_button(
965 &self,
966 index: usize,
967 conflict: Option<ConflictOrigin>,
968 cx: &mut Context<Self>,
969 ) -> IconButton {
970 if self.filter_state != FilterState::Conflicts
971 && let Some(conflict) = conflict
972 {
973 if conflict.is_user_keybind_conflict() {
974 base_button_style(index, IconName::Warning)
975 .icon_color(Color::Warning)
976 .tooltip(|window, cx| {
977 Tooltip::with_meta(
978 "View conflicts",
979 Some(&ToggleConflictFilter),
980 "Use alt+click to show all conflicts",
981 window,
982 cx,
983 )
984 })
985 .on_click(cx.listener(move |this, click: &ClickEvent, window, cx| {
986 if click.modifiers().alt {
987 this.set_filter_state(FilterState::Conflicts, cx);
988 } else {
989 this.select_index(index, None, window, cx);
990 this.open_edit_keybinding_modal(false, window, cx);
991 cx.stop_propagation();
992 }
993 }))
994 } else if self.search_mode.exact_match() {
995 base_button_style(index, IconName::Info)
996 .tooltip(|window, cx| {
997 Tooltip::with_meta(
998 "Edit this binding",
999 Some(&ShowMatchingKeybinds),
1000 "This binding is overridden by other bindings.",
1001 window,
1002 cx,
1003 )
1004 })
1005 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
1006 this.select_index(index, None, window, cx);
1007 this.open_edit_keybinding_modal(false, window, cx);
1008 cx.stop_propagation();
1009 }))
1010 } else {
1011 base_button_style(index, IconName::Info)
1012 .tooltip(|window, cx| {
1013 Tooltip::with_meta(
1014 "Show matching keybinds",
1015 Some(&ShowMatchingKeybinds),
1016 "This binding is overridden by other bindings.\nUse alt+click to edit this binding",
1017 window,
1018 cx,
1019 )
1020 })
1021 .on_click(cx.listener(move |this, click: &ClickEvent, window, cx| {
1022 if click.modifiers().alt {
1023 this.select_index(index, None, window, cx);
1024 this.open_edit_keybinding_modal(false, window, cx);
1025 cx.stop_propagation();
1026 } else {
1027 this.show_matching_keystrokes(&Default::default(), window, cx);
1028 }
1029 }))
1030 }
1031 } else {
1032 base_button_style(index, IconName::Pencil)
1033 .visible_on_hover(if self.selected_index == Some(index) {
1034 "".into()
1035 } else if self.show_hover_menus {
1036 row_group_id(index)
1037 } else {
1038 "never-show".into()
1039 })
1040 .when(
1041 self.show_hover_menus && !self.context_menu_deployed(),
1042 |this| this.tooltip(Tooltip::for_action_title("Edit Keybinding", &EditBinding)),
1043 )
1044 .on_click(cx.listener(move |this, _, window, cx| {
1045 this.select_index(index, None, window, cx);
1046 this.open_edit_keybinding_modal(false, window, cx);
1047 cx.stop_propagation();
1048 }))
1049 }
1050 }
1051
1052 fn render_no_matches_hint(&self, _window: &mut Window, _cx: &App) -> AnyElement {
1053 let hint = match (self.filter_state, &self.search_mode) {
1054 (FilterState::Conflicts, _) => {
1055 if self.keybinding_conflict_state.any_user_binding_conflicts() {
1056 "No conflicting keybinds found that match the provided query"
1057 } else {
1058 "No conflicting keybinds found"
1059 }
1060 }
1061 (FilterState::All, SearchMode::KeyStroke { .. }) => {
1062 "No keybinds found matching the entered keystrokes"
1063 }
1064 (FilterState::All, SearchMode::Normal) => "No matches found for the provided query",
1065 };
1066
1067 Label::new(hint).color(Color::Muted).into_any_element()
1068 }
1069
1070 fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1071 self.show_hover_menus = false;
1072 if let Some(selected) = self.selected_index {
1073 let selected = selected + 1;
1074 if selected >= self.matches.len() {
1075 self.select_last(&Default::default(), window, cx);
1076 } else {
1077 self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
1078 }
1079 } else {
1080 self.select_first(&Default::default(), window, cx);
1081 }
1082 }
1083
1084 fn select_previous(
1085 &mut self,
1086 _: &menu::SelectPrevious,
1087 window: &mut Window,
1088 cx: &mut Context<Self>,
1089 ) {
1090 self.show_hover_menus = false;
1091 if let Some(selected) = self.selected_index {
1092 if selected == 0 {
1093 return;
1094 }
1095
1096 let selected = selected - 1;
1097
1098 if selected >= self.matches.len() {
1099 self.select_last(&Default::default(), window, cx);
1100 } else {
1101 self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
1102 }
1103 } else {
1104 self.select_last(&Default::default(), window, cx);
1105 }
1106 }
1107
1108 fn select_first(&mut self, _: &menu::SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
1109 self.show_hover_menus = false;
1110 if self.matches.get(0).is_some() {
1111 self.select_index(0, Some(ScrollStrategy::Center), window, cx);
1112 }
1113 }
1114
1115 fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
1116 self.show_hover_menus = false;
1117 if self.matches.last().is_some() {
1118 let index = self.matches.len() - 1;
1119 self.select_index(index, Some(ScrollStrategy::Center), window, cx);
1120 }
1121 }
1122
1123 fn open_edit_keybinding_modal(
1124 &mut self,
1125 create: bool,
1126 window: &mut Window,
1127 cx: &mut Context<Self>,
1128 ) {
1129 self.show_hover_menus = false;
1130 let Some((keybind, keybind_index)) = self.selected_keybind_and_index() else {
1131 return;
1132 };
1133 let keybind = keybind.clone();
1134 let keymap_editor = cx.entity();
1135
1136 let keystroke = keybind.keystroke_text().cloned().unwrap_or_default();
1137 let arguments = keybind
1138 .action()
1139 .arguments
1140 .as_ref()
1141 .map(|arguments| arguments.text.clone());
1142 let context = keybind
1143 .context()
1144 .map(|context| context.local_str().unwrap_or("global"));
1145 let action = keybind.action().name;
1146 let source = keybind.keybind_source().map(|source| source.name());
1147
1148 telemetry::event!(
1149 "Edit Keybinding Modal Opened",
1150 keystroke = keystroke,
1151 action = action,
1152 source = source,
1153 context = context,
1154 arguments = arguments,
1155 );
1156
1157 let temp_dir = self.action_args_temp_dir.as_ref().map(|dir| dir.path());
1158
1159 self.workspace
1160 .update(cx, |workspace, cx| {
1161 let fs = workspace.app_state().fs.clone();
1162 let workspace_weak = cx.weak_entity();
1163 workspace.toggle_modal(window, cx, |window, cx| {
1164 let modal = KeybindingEditorModal::new(
1165 create,
1166 keybind,
1167 keybind_index,
1168 keymap_editor,
1169 temp_dir,
1170 workspace_weak,
1171 fs,
1172 window,
1173 cx,
1174 );
1175 window.focus(&modal.focus_handle(cx));
1176 modal
1177 });
1178 })
1179 .log_err();
1180 }
1181
1182 fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
1183 self.open_edit_keybinding_modal(false, window, cx);
1184 }
1185
1186 fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
1187 self.open_edit_keybinding_modal(true, window, cx);
1188 }
1189
1190 fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
1191 let Some(to_remove) = self.selected_binding().cloned() else {
1192 return;
1193 };
1194
1195 let std::result::Result::Ok(fs) = self
1196 .workspace
1197 .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
1198 else {
1199 return;
1200 };
1201 let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1202 self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
1203 self.table_interaction_state.read(cx).scroll_offset(),
1204 ));
1205 let keyboard_mapper = cx.keyboard_mapper().clone();
1206 cx.spawn(async move |_, _| {
1207 remove_keybinding(to_remove, &fs, tab_size, keyboard_mapper.as_ref()).await
1208 })
1209 .detach_and_notify_err(window, cx);
1210 }
1211
1212 fn copy_context_to_clipboard(
1213 &mut self,
1214 _: &CopyContext,
1215 _window: &mut Window,
1216 cx: &mut Context<Self>,
1217 ) {
1218 let context = self
1219 .selected_binding()
1220 .and_then(|binding| binding.context())
1221 .and_then(KeybindContextString::local_str)
1222 .map(|context| context.to_string());
1223 let Some(context) = context else {
1224 return;
1225 };
1226
1227 telemetry::event!("Keybinding Context Copied", context = context);
1228 cx.write_to_clipboard(gpui::ClipboardItem::new_string(context));
1229 }
1230
1231 fn copy_action_to_clipboard(
1232 &mut self,
1233 _: &CopyAction,
1234 _window: &mut Window,
1235 cx: &mut Context<Self>,
1236 ) {
1237 let action = self
1238 .selected_binding()
1239 .map(|binding| binding.action().name.to_string());
1240 let Some(action) = action else {
1241 return;
1242 };
1243
1244 telemetry::event!("Keybinding Action Copied", action = action);
1245 cx.write_to_clipboard(gpui::ClipboardItem::new_string(action));
1246 }
1247
1248 fn toggle_conflict_filter(
1249 &mut self,
1250 _: &ToggleConflictFilter,
1251 _: &mut Window,
1252 cx: &mut Context<Self>,
1253 ) {
1254 self.set_filter_state(self.filter_state.invert(), cx);
1255 }
1256
1257 fn set_filter_state(&mut self, filter_state: FilterState, cx: &mut Context<Self>) {
1258 if self.filter_state != filter_state {
1259 self.filter_state = filter_state;
1260 self.on_query_changed(cx);
1261 }
1262 }
1263
1264 fn toggle_keystroke_search(
1265 &mut self,
1266 _: &ToggleKeystrokeSearch,
1267 window: &mut Window,
1268 cx: &mut Context<Self>,
1269 ) {
1270 self.search_mode = self.search_mode.invert();
1271 self.on_query_changed(cx);
1272
1273 match self.search_mode {
1274 SearchMode::KeyStroke { .. } => {
1275 self.keystroke_editor.update(cx, |editor, cx| {
1276 editor.start_recording(&StartRecording, window, cx);
1277 });
1278 }
1279 SearchMode::Normal => {
1280 self.keystroke_editor.update(cx, |editor, cx| {
1281 editor.stop_recording(&StopRecording, window, cx);
1282 editor.clear_keystrokes(&ClearKeystrokes, window, cx);
1283 });
1284 window.focus(&self.filter_editor.focus_handle(cx));
1285 }
1286 }
1287 }
1288
1289 fn toggle_exact_keystroke_matching(
1290 &mut self,
1291 _: &ToggleExactKeystrokeMatching,
1292 _: &mut Window,
1293 cx: &mut Context<Self>,
1294 ) {
1295 let SearchMode::KeyStroke { exact_match } = &mut self.search_mode else {
1296 return;
1297 };
1298
1299 *exact_match = !(*exact_match);
1300 self.on_query_changed(cx);
1301 }
1302
1303 fn show_matching_keystrokes(
1304 &mut self,
1305 _: &ShowMatchingKeybinds,
1306 _: &mut Window,
1307 cx: &mut Context<Self>,
1308 ) {
1309 let Some(selected_binding) = self.selected_binding() else {
1310 return;
1311 };
1312
1313 let keystrokes = selected_binding
1314 .keystrokes()
1315 .map(Vec::from)
1316 .unwrap_or_default();
1317
1318 self.filter_state = FilterState::All;
1319 self.search_mode = SearchMode::KeyStroke { exact_match: true };
1320
1321 self.keystroke_editor.update(cx, |editor, cx| {
1322 editor.set_keystrokes(keystrokes, cx);
1323 });
1324 }
1325}
1326
1327struct HumanizedActionNameCache {
1328 cache: HashMap<&'static str, SharedString>,
1329}
1330
1331impl HumanizedActionNameCache {
1332 fn new(cx: &App) -> Self {
1333 let cache = HashMap::from_iter(cx.all_action_names().iter().map(|&action_name| {
1334 (
1335 action_name,
1336 command_palette::humanize_action_name(action_name).into(),
1337 )
1338 }));
1339 Self { cache }
1340 }
1341
1342 fn get(&self, action_name: &'static str) -> SharedString {
1343 match self.cache.get(action_name) {
1344 Some(name) => name.clone(),
1345 None => action_name.into(),
1346 }
1347 }
1348}
1349
1350#[derive(Clone)]
1351struct KeybindInformation {
1352 keystroke_text: SharedString,
1353 ui_binding: ui::KeyBinding,
1354 context: KeybindContextString,
1355 source: KeybindSource,
1356}
1357
1358impl KeybindInformation {
1359 fn get_action_mapping(&self) -> ActionMapping {
1360 ActionMapping {
1361 keystrokes: self.ui_binding.keystrokes.clone(),
1362 context: self.context.local().cloned(),
1363 }
1364 }
1365}
1366
1367#[derive(Clone)]
1368struct ActionInformation {
1369 name: &'static str,
1370 humanized_name: SharedString,
1371 arguments: Option<SyntaxHighlightedText>,
1372 documentation: Option<&'static str>,
1373 has_schema: bool,
1374}
1375
1376impl ActionInformation {
1377 fn new(
1378 action_name: &'static str,
1379 action_arguments: Option<SyntaxHighlightedText>,
1380 actions_with_schemas: &HashSet<&'static str>,
1381 action_documentation: &HashMap<&'static str, &'static str>,
1382 action_name_cache: &HumanizedActionNameCache,
1383 ) -> Self {
1384 Self {
1385 humanized_name: action_name_cache.get(action_name),
1386 has_schema: actions_with_schemas.contains(action_name),
1387 arguments: action_arguments,
1388 documentation: action_documentation.get(action_name).copied(),
1389 name: action_name,
1390 }
1391 }
1392}
1393
1394#[derive(Clone)]
1395enum ProcessedBinding {
1396 Mapped(KeybindInformation, ActionInformation),
1397 Unmapped(ActionInformation),
1398}
1399
1400impl ProcessedBinding {
1401 fn new_mapped(
1402 keystroke_text: impl Into<SharedString>,
1403 ui_key_binding: ui::KeyBinding,
1404 context: KeybindContextString,
1405 source: KeybindSource,
1406 action_information: ActionInformation,
1407 ) -> Self {
1408 Self::Mapped(
1409 KeybindInformation {
1410 keystroke_text: keystroke_text.into(),
1411 ui_binding: ui_key_binding,
1412 context,
1413 source,
1414 },
1415 action_information,
1416 )
1417 }
1418
1419 fn is_unbound(&self) -> bool {
1420 matches!(self, Self::Unmapped(_))
1421 }
1422
1423 fn get_action_mapping(&self) -> Option<ActionMapping> {
1424 self.keybind_information()
1425 .map(|keybind| keybind.get_action_mapping())
1426 }
1427
1428 fn keystrokes(&self) -> Option<&[KeybindingKeystroke]> {
1429 self.ui_key_binding()
1430 .map(|binding| binding.keystrokes.as_slice())
1431 }
1432
1433 fn keybind_information(&self) -> Option<&KeybindInformation> {
1434 match self {
1435 Self::Mapped(keybind_information, _) => Some(keybind_information),
1436 Self::Unmapped(_) => None,
1437 }
1438 }
1439
1440 fn keybind_source(&self) -> Option<KeybindSource> {
1441 self.keybind_information().map(|keybind| keybind.source)
1442 }
1443
1444 fn context(&self) -> Option<&KeybindContextString> {
1445 self.keybind_information().map(|keybind| &keybind.context)
1446 }
1447
1448 fn ui_key_binding(&self) -> Option<&ui::KeyBinding> {
1449 self.keybind_information()
1450 .map(|keybind| &keybind.ui_binding)
1451 }
1452
1453 fn keystroke_text(&self) -> Option<&SharedString> {
1454 self.keybind_information()
1455 .map(|binding| &binding.keystroke_text)
1456 }
1457
1458 fn action(&self) -> &ActionInformation {
1459 match self {
1460 Self::Mapped(_, action) | Self::Unmapped(action) => action,
1461 }
1462 }
1463
1464 fn cmp(&self, other: &Self) -> cmp::Ordering {
1465 match (self, other) {
1466 (Self::Mapped(keybind1, action1), Self::Mapped(keybind2, action2)) => {
1467 match keybind1.source.cmp(&keybind2.source) {
1468 cmp::Ordering::Equal => action1.humanized_name.cmp(&action2.humanized_name),
1469 ordering => ordering,
1470 }
1471 }
1472 (Self::Mapped(_, _), Self::Unmapped(_)) => cmp::Ordering::Less,
1473 (Self::Unmapped(_), Self::Mapped(_, _)) => cmp::Ordering::Greater,
1474 (Self::Unmapped(action1), Self::Unmapped(action2)) => {
1475 action1.humanized_name.cmp(&action2.humanized_name)
1476 }
1477 }
1478 }
1479}
1480
1481#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
1482enum KeybindContextString {
1483 Global,
1484 Local(SharedString, Arc<Language>),
1485}
1486
1487impl KeybindContextString {
1488 const GLOBAL: SharedString = SharedString::new_static("<global>");
1489
1490 pub fn local(&self) -> Option<&SharedString> {
1491 match self {
1492 KeybindContextString::Global => None,
1493 KeybindContextString::Local(name, _) => Some(name),
1494 }
1495 }
1496
1497 pub fn local_str(&self) -> Option<&str> {
1498 match self {
1499 KeybindContextString::Global => None,
1500 KeybindContextString::Local(name, _) => Some(name),
1501 }
1502 }
1503}
1504
1505impl RenderOnce for KeybindContextString {
1506 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1507 match self {
1508 KeybindContextString::Global => {
1509 muted_styled_text(KeybindContextString::GLOBAL, cx).into_any_element()
1510 }
1511 KeybindContextString::Local(name, language) => {
1512 SyntaxHighlightedText::new(name, language).into_any_element()
1513 }
1514 }
1515 }
1516}
1517
1518fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
1519 let len = text.len();
1520 StyledText::new(text).with_highlights([(
1521 0..len,
1522 gpui::HighlightStyle::color(cx.theme().colors().text_muted),
1523 )])
1524}
1525
1526impl Item for KeymapEditor {
1527 type Event = ();
1528
1529 fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
1530 "Keymap Editor".into()
1531 }
1532}
1533
1534impl Render for KeymapEditor {
1535 fn render(&mut self, _window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
1536 let row_count = self.matches.len();
1537 let theme = cx.theme();
1538 let focus_handle = &self.focus_handle;
1539
1540 v_flex()
1541 .id("keymap-editor")
1542 .track_focus(focus_handle)
1543 .key_context(self.key_context())
1544 .on_action(cx.listener(Self::select_next))
1545 .on_action(cx.listener(Self::select_previous))
1546 .on_action(cx.listener(Self::select_first))
1547 .on_action(cx.listener(Self::select_last))
1548 .on_action(cx.listener(Self::focus_search))
1549 .on_action(cx.listener(Self::edit_binding))
1550 .on_action(cx.listener(Self::create_binding))
1551 .on_action(cx.listener(Self::delete_binding))
1552 .on_action(cx.listener(Self::copy_action_to_clipboard))
1553 .on_action(cx.listener(Self::copy_context_to_clipboard))
1554 .on_action(cx.listener(Self::toggle_conflict_filter))
1555 .on_action(cx.listener(Self::toggle_keystroke_search))
1556 .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1557 .on_action(cx.listener(Self::show_matching_keystrokes))
1558 .on_mouse_move(cx.listener(|this, _, _window, _cx| {
1559 this.show_hover_menus = true;
1560 }))
1561 .size_full()
1562 .p_2()
1563 .gap_1()
1564 .bg(theme.colors().editor_background)
1565 .child(
1566 v_flex()
1567 .gap_2()
1568 .child(
1569 h_flex()
1570 .gap_2()
1571 .child(
1572 h_flex()
1573 .key_context({
1574 let mut context = KeyContext::new_with_defaults();
1575 context.add("BufferSearchBar");
1576 context
1577 })
1578 .size_full()
1579 .h_8()
1580 .pl_2()
1581 .pr_1()
1582 .py_1()
1583 .border_1()
1584 .border_color(theme.colors().border)
1585 .rounded_md()
1586 .child(self.filter_editor.clone()),
1587 )
1588 .child(
1589 h_flex()
1590 .gap_1()
1591 .min_w_64()
1592 .child(
1593 IconButton::new(
1594 "KeymapEditorToggleFiltersIcon",
1595 IconName::Keyboard,
1596 )
1597 .icon_size(IconSize::Small)
1598 .tooltip({
1599 let focus_handle = focus_handle.clone();
1600
1601 move |window, cx| {
1602 Tooltip::for_action_in(
1603 "Search by Keystroke",
1604 &ToggleKeystrokeSearch,
1605 &focus_handle.clone(),
1606 window,
1607 cx,
1608 )
1609 }
1610 })
1611 .toggle_state(matches!(
1612 self.search_mode,
1613 SearchMode::KeyStroke { .. }
1614 ))
1615 .on_click(|_, window, cx| {
1616 window.dispatch_action(
1617 ToggleKeystrokeSearch.boxed_clone(),
1618 cx,
1619 );
1620 }),
1621 )
1622 .child(
1623 IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1624 .icon_size(IconSize::Small)
1625 .when(
1626 self.keybinding_conflict_state
1627 .any_user_binding_conflicts(),
1628 |this| {
1629 this.indicator(
1630 Indicator::dot().color(Color::Warning),
1631 )
1632 },
1633 )
1634 .tooltip({
1635 let filter_state = self.filter_state;
1636 let focus_handle = focus_handle.clone();
1637
1638 move |window, cx| {
1639 Tooltip::for_action_in(
1640 match filter_state {
1641 FilterState::All => "Show Conflicts",
1642 FilterState::Conflicts => {
1643 "Hide Conflicts"
1644 }
1645 },
1646 &ToggleConflictFilter,
1647 &focus_handle.clone(),
1648 window,
1649 cx,
1650 )
1651 }
1652 })
1653 .selected_icon_color(Color::Warning)
1654 .toggle_state(matches!(
1655 self.filter_state,
1656 FilterState::Conflicts
1657 ))
1658 .on_click(|_, window, cx| {
1659 window.dispatch_action(
1660 ToggleConflictFilter.boxed_clone(),
1661 cx,
1662 );
1663 }),
1664 )
1665 .child(
1666 h_flex()
1667 .w_full()
1668 .pl_2()
1669 .gap_1()
1670 .justify_end()
1671 .child(
1672 PopoverMenu::new("open-keymap-menu")
1673 .menu(move |window, cx| {
1674 Some(ContextMenu::build(window, cx, |menu, _, _| {
1675 menu.header("View Default...")
1676 .action(
1677 "Zed Key Bindings",
1678 zed_actions::OpenDefaultKeymap
1679 .boxed_clone(),
1680 )
1681 .action(
1682 "Vim Bindings",
1683 vim::OpenDefaultKeymap.boxed_clone(),
1684 )
1685 }))
1686 })
1687 .anchor(gpui::Corner::TopRight)
1688 .offset(gpui::Point {
1689 x: px(0.0),
1690 y: px(2.0),
1691 })
1692 .trigger_with_tooltip(
1693 IconButton::new(
1694 "OpenKeymapJsonButton",
1695 IconName::Ellipsis,
1696 )
1697 .icon_size(IconSize::Small),
1698 {
1699 let focus_handle = focus_handle.clone();
1700 move |window, cx| {
1701 Tooltip::for_action_in(
1702 "View Default...",
1703 &zed_actions::OpenKeymap,
1704 &focus_handle,
1705 window,
1706 cx,
1707 )
1708 }
1709 },
1710 ),
1711 )
1712 .child(
1713 Button::new("edit-in-json", "Edit in keymap.json")
1714 .style(ButtonStyle::Outlined)
1715 .on_click(|_, window, cx| {
1716 window.dispatch_action(
1717 zed_actions::OpenKeymap.boxed_clone(),
1718 cx,
1719 );
1720 })
1721 ),
1722 )
1723 ),
1724 )
1725 .when_some(
1726 match self.search_mode {
1727 SearchMode::Normal => None,
1728 SearchMode::KeyStroke { exact_match } => Some(exact_match),
1729 },
1730 |this, exact_match| {
1731 this.child(
1732 h_flex()
1733 .gap_2()
1734 .child(self.keystroke_editor.clone())
1735 .child(
1736 h_flex()
1737 .min_w_64()
1738 .child(
1739 IconButton::new(
1740 "keystrokes-exact-match",
1741 IconName::CaseSensitive,
1742 )
1743 .tooltip({
1744 let keystroke_focus_handle =
1745 self.keystroke_editor.read(cx).focus_handle(cx);
1746
1747 move |window, cx| {
1748 Tooltip::for_action_in(
1749 "Toggle Exact Match Mode",
1750 &ToggleExactKeystrokeMatching,
1751 &keystroke_focus_handle,
1752 window,
1753 cx,
1754 )
1755 }
1756 })
1757 .shape(IconButtonShape::Square)
1758 .toggle_state(exact_match)
1759 .on_click(
1760 cx.listener(|_, _, window, cx| {
1761 window.dispatch_action(
1762 ToggleExactKeystrokeMatching.boxed_clone(),
1763 cx,
1764 );
1765 }),
1766 ),
1767 ),
1768 )
1769 )
1770 },
1771 ),
1772 )
1773 .child(
1774 Table::new()
1775 .interactable(&self.table_interaction_state)
1776 .striped()
1777 .empty_table_callback({
1778 let this = cx.entity();
1779 move |window, cx| this.read(cx).render_no_matches_hint(window, cx)
1780 })
1781 .column_widths([
1782 DefiniteLength::Absolute(AbsoluteLength::Pixels(px(36.))),
1783 DefiniteLength::Fraction(0.25),
1784 DefiniteLength::Fraction(0.20),
1785 DefiniteLength::Fraction(0.14),
1786 DefiniteLength::Fraction(0.45),
1787 DefiniteLength::Fraction(0.08),
1788 ])
1789 .resizable_columns(
1790 [
1791 TableResizeBehavior::None,
1792 TableResizeBehavior::Resizable,
1793 TableResizeBehavior::Resizable,
1794 TableResizeBehavior::Resizable,
1795 TableResizeBehavior::Resizable,
1796 TableResizeBehavior::Resizable, // this column doesn't matter
1797 ],
1798 &self.current_widths,
1799 cx,
1800 )
1801 .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1802 .uniform_list(
1803 "keymap-editor-table",
1804 row_count,
1805 cx.processor(move |this, range: Range<usize>, _window, cx| {
1806 let context_menu_deployed = this.context_menu_deployed();
1807 range
1808 .filter_map(|index| {
1809 let candidate_id = this.matches.get(index)?.candidate_id;
1810 let binding = &this.keybindings[candidate_id];
1811 let action_name = binding.action().name;
1812 let conflict = this.get_conflict(index);
1813 let is_overridden = conflict.is_some_and(|conflict| {
1814 !conflict.is_user_keybind_conflict()
1815 });
1816
1817 let icon = this.create_row_button(index, conflict, cx);
1818
1819 let action = div()
1820 .id(("keymap action", index))
1821 .child({
1822 if action_name != gpui::NoAction.name() {
1823 binding
1824 .action()
1825 .humanized_name
1826 .clone()
1827 .into_any_element()
1828 } else {
1829 const NULL: SharedString =
1830 SharedString::new_static("<null>");
1831 muted_styled_text(NULL, cx)
1832 .into_any_element()
1833 }
1834 })
1835 .when(
1836 !context_menu_deployed
1837 && this.show_hover_menus
1838 && !is_overridden,
1839 |this| {
1840 this.tooltip({
1841 let action_name = binding.action().name;
1842 let action_docs =
1843 binding.action().documentation;
1844 move |_, cx| {
1845 let action_tooltip =
1846 Tooltip::new(action_name);
1847 let action_tooltip = match action_docs {
1848 Some(docs) => action_tooltip.meta(docs),
1849 None => action_tooltip,
1850 };
1851 cx.new(|_| action_tooltip).into()
1852 }
1853 })
1854 },
1855 )
1856 .into_any_element();
1857
1858 let keystrokes = binding.ui_key_binding().cloned().map_or(
1859 binding
1860 .keystroke_text()
1861 .cloned()
1862 .unwrap_or_default()
1863 .into_any_element(),
1864 IntoElement::into_any_element,
1865 );
1866
1867 let action_arguments = match binding.action().arguments.clone()
1868 {
1869 Some(arguments) => arguments.into_any_element(),
1870 None => {
1871 if binding.action().has_schema {
1872 muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1873 .into_any_element()
1874 } else {
1875 gpui::Empty.into_any_element()
1876 }
1877 }
1878 };
1879
1880 let context = binding.context().cloned().map_or(
1881 gpui::Empty.into_any_element(),
1882 |context| {
1883 let is_local = context.local().is_some();
1884
1885 div()
1886 .id(("keymap context", index))
1887 .child(context.clone())
1888 .when(
1889 is_local
1890 && !context_menu_deployed
1891 && !is_overridden
1892 && this.show_hover_menus,
1893 |this| {
1894 this.tooltip(Tooltip::element({
1895 move |_, _| {
1896 context.clone().into_any_element()
1897 }
1898 }))
1899 },
1900 )
1901 .into_any_element()
1902 },
1903 );
1904
1905 let source = binding
1906 .keybind_source()
1907 .map(|source| source.name())
1908 .unwrap_or_default()
1909 .into_any_element();
1910
1911 Some([
1912 icon.into_any_element(),
1913 action,
1914 action_arguments,
1915 keystrokes,
1916 context,
1917 source,
1918 ])
1919 })
1920 .collect()
1921 }),
1922 )
1923 .map_row(cx.processor(
1924 |this, (row_index, row): (usize, Stateful<Div>), _window, cx| {
1925 let conflict = this.get_conflict(row_index);
1926 let is_selected = this.selected_index == Some(row_index);
1927
1928 let row_id = row_group_id(row_index);
1929
1930 div()
1931 .id(("keymap-row-wrapper", row_index))
1932 .child(
1933 row.id(row_id.clone())
1934 .on_any_mouse_down(cx.listener(
1935 move |this,
1936 mouse_down_event: &gpui::MouseDownEvent,
1937 window,
1938 cx| {
1939 if mouse_down_event.button == MouseButton::Right {
1940 this.select_index(
1941 row_index, None, window, cx,
1942 );
1943 this.create_context_menu(
1944 mouse_down_event.position,
1945 window,
1946 cx,
1947 );
1948 }
1949 },
1950 ))
1951 .on_click(cx.listener(
1952 move |this, event: &ClickEvent, window, cx| {
1953 this.select_index(row_index, None, window, cx);
1954 if event.click_count() == 2 {
1955 this.open_edit_keybinding_modal(
1956 false, window, cx,
1957 );
1958 }
1959 },
1960 ))
1961 .group(row_id)
1962 .when(
1963 conflict.is_some_and(|conflict| {
1964 !conflict.is_user_keybind_conflict()
1965 }),
1966 |row| {
1967 const OVERRIDDEN_OPACITY: f32 = 0.5;
1968 row.opacity(OVERRIDDEN_OPACITY)
1969 },
1970 )
1971 .when_some(
1972 conflict.filter(|conflict| {
1973 !this.context_menu_deployed() &&
1974 !conflict.is_user_keybind_conflict()
1975 }),
1976 |row, conflict| {
1977 let overriding_binding = this.keybindings.get(conflict.index);
1978 let context = overriding_binding.and_then(|binding| {
1979 match conflict.override_source {
1980 KeybindSource::User => Some("your keymap"),
1981 KeybindSource::Vim => Some("the vim keymap"),
1982 KeybindSource::Base => Some("your base keymap"),
1983 _ => {
1984 log::error!("Unexpected override from the {} keymap", conflict.override_source.name());
1985 None
1986 }
1987 }.map(|source| format!("This keybinding is overridden by the '{}' binding from {}.", binding.action().humanized_name, source))
1988 }).unwrap_or_else(|| "This binding is overridden.".to_string());
1989
1990 row.tooltip(Tooltip::text(context))},
1991 ),
1992 )
1993 .border_2()
1994 .when(
1995 conflict.is_some_and(|conflict| {
1996 conflict.is_user_keybind_conflict()
1997 }),
1998 |row| row.bg(cx.theme().status().error_background),
1999 )
2000 .when(is_selected, |row| {
2001 row.border_color(cx.theme().colors().panel_focused_border)
2002 })
2003 .into_any_element()
2004 }),
2005 ),
2006 )
2007 .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
2008 // This ensures that the menu is not dismissed in cases where scroll events
2009 // with a delta of zero are emitted
2010 if !event.delta.pixel_delta(px(1.)).y.is_zero() {
2011 this.context_menu.take();
2012 cx.notify();
2013 }
2014 }))
2015 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2016 deferred(
2017 anchored()
2018 .position(*position)
2019 .anchor(gpui::Corner::TopLeft)
2020 .child(menu.clone()),
2021 )
2022 .with_priority(1)
2023 }))
2024 }
2025}
2026
2027fn row_group_id(row_index: usize) -> SharedString {
2028 SharedString::new(format!("keymap-table-row-{}", row_index))
2029}
2030
2031fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
2032 IconButton::new(("keymap-icon", row_index), icon)
2033 .shape(IconButtonShape::Square)
2034 .size(ButtonSize::Compact)
2035}
2036
2037#[derive(Debug, Clone, IntoElement)]
2038struct SyntaxHighlightedText {
2039 text: SharedString,
2040 language: Arc<Language>,
2041}
2042
2043impl SyntaxHighlightedText {
2044 pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
2045 Self {
2046 text: text.into(),
2047 language,
2048 }
2049 }
2050}
2051
2052impl RenderOnce for SyntaxHighlightedText {
2053 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
2054 let text_style = window.text_style();
2055 let syntax_theme = cx.theme().syntax();
2056
2057 let text = self.text.clone();
2058
2059 let highlights = self
2060 .language
2061 .highlight_text(&text.as_ref().into(), 0..text.len());
2062 let mut runs = Vec::with_capacity(highlights.len());
2063 let mut offset = 0;
2064
2065 for (highlight_range, highlight_id) in highlights {
2066 // Add un-highlighted text before the current highlight
2067 if highlight_range.start > offset {
2068 runs.push(text_style.to_run(highlight_range.start - offset));
2069 }
2070
2071 let mut run_style = text_style.clone();
2072 if let Some(highlight_style) = highlight_id.style(syntax_theme) {
2073 run_style = run_style.highlight(highlight_style);
2074 }
2075 // add the highlighted range
2076 runs.push(run_style.to_run(highlight_range.len()));
2077 offset = highlight_range.end;
2078 }
2079
2080 // Add any remaining un-highlighted text
2081 if offset < text.len() {
2082 runs.push(text_style.to_run(text.len() - offset));
2083 }
2084
2085 StyledText::new(text).with_runs(runs)
2086 }
2087}
2088
2089#[derive(PartialEq)]
2090struct InputError {
2091 severity: Severity,
2092 content: SharedString,
2093}
2094
2095impl InputError {
2096 fn warning(message: impl Into<SharedString>) -> Self {
2097 Self {
2098 severity: Severity::Warning,
2099 content: message.into(),
2100 }
2101 }
2102
2103 fn error(message: anyhow::Error) -> Self {
2104 Self {
2105 severity: Severity::Error,
2106 content: message.to_string().into(),
2107 }
2108 }
2109}
2110
2111struct KeybindingEditorModal {
2112 creating: bool,
2113 editing_keybind: ProcessedBinding,
2114 editing_keybind_idx: usize,
2115 keybind_editor: Entity<KeystrokeInput>,
2116 context_editor: Entity<SingleLineInput>,
2117 action_arguments_editor: Option<Entity<ActionArgumentsEditor>>,
2118 fs: Arc<dyn Fs>,
2119 error: Option<InputError>,
2120 keymap_editor: Entity<KeymapEditor>,
2121 workspace: WeakEntity<Workspace>,
2122 focus_state: KeybindingEditorModalFocusState,
2123}
2124
2125impl ModalView for KeybindingEditorModal {}
2126
2127impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
2128
2129impl Focusable for KeybindingEditorModal {
2130 fn focus_handle(&self, cx: &App) -> FocusHandle {
2131 self.keybind_editor.focus_handle(cx)
2132 }
2133}
2134
2135impl KeybindingEditorModal {
2136 pub fn new(
2137 create: bool,
2138 editing_keybind: ProcessedBinding,
2139 editing_keybind_idx: usize,
2140 keymap_editor: Entity<KeymapEditor>,
2141 action_args_temp_dir: Option<&std::path::Path>,
2142 workspace: WeakEntity<Workspace>,
2143 fs: Arc<dyn Fs>,
2144 window: &mut Window,
2145 cx: &mut App,
2146 ) -> Self {
2147 let keybind_editor = cx
2148 .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
2149
2150 let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
2151 let input = SingleLineInput::new(window, cx, "Keybinding Context")
2152 .label("Edit Context")
2153 .label_size(LabelSize::Default);
2154
2155 if let Some(context) = editing_keybind
2156 .context()
2157 .and_then(KeybindContextString::local)
2158 {
2159 input.editor().update(cx, |editor, cx| {
2160 editor.set_text(context.clone(), window, cx);
2161 });
2162 }
2163
2164 let editor_entity = input.editor().clone();
2165 let workspace = workspace.clone();
2166 cx.spawn(async move |_input_handle, cx| {
2167 let contexts = cx
2168 .background_spawn(async { collect_contexts_from_assets() })
2169 .await;
2170
2171 let language = load_keybind_context_language(workspace, cx).await;
2172 editor_entity
2173 .update(cx, |editor, cx| {
2174 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2175 buffer.update(cx, |buffer, cx| {
2176 buffer.set_language(Some(language), cx);
2177 });
2178 }
2179 editor.set_completion_provider(Some(std::rc::Rc::new(
2180 KeyContextCompletionProvider { contexts },
2181 )));
2182 })
2183 .context("Failed to load completions for keybinding context")
2184 })
2185 .detach_and_log_err(cx);
2186
2187 input
2188 });
2189
2190 let action_arguments_editor = editing_keybind.action().has_schema.then(|| {
2191 let arguments = editing_keybind
2192 .action()
2193 .arguments
2194 .as_ref()
2195 .map(|args| args.text.clone());
2196 cx.new(|cx| {
2197 ActionArgumentsEditor::new(
2198 editing_keybind.action().name,
2199 arguments,
2200 action_args_temp_dir,
2201 workspace.clone(),
2202 window,
2203 cx,
2204 )
2205 })
2206 });
2207
2208 let focus_state = KeybindingEditorModalFocusState::new(
2209 keybind_editor.focus_handle(cx),
2210 action_arguments_editor
2211 .as_ref()
2212 .map(|args_editor| args_editor.focus_handle(cx)),
2213 context_editor.focus_handle(cx),
2214 );
2215
2216 Self {
2217 creating: create,
2218 editing_keybind,
2219 editing_keybind_idx,
2220 fs,
2221 keybind_editor,
2222 context_editor,
2223 action_arguments_editor,
2224 error: None,
2225 keymap_editor,
2226 workspace,
2227 focus_state,
2228 }
2229 }
2230
2231 fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
2232 if self
2233 .error
2234 .as_ref()
2235 .is_some_and(|old_error| old_error.severity == Severity::Warning && *old_error == error)
2236 {
2237 false
2238 } else {
2239 self.error = Some(error);
2240 cx.notify();
2241 true
2242 }
2243 }
2244
2245 fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
2246 let action_arguments = self
2247 .action_arguments_editor
2248 .as_ref()
2249 .map(|arguments_editor| arguments_editor.read(cx).editor.read(cx).text(cx))
2250 .filter(|args| !args.is_empty());
2251
2252 let value = action_arguments
2253 .as_ref()
2254 .map(|args| {
2255 serde_json::from_str(args).context("Failed to parse action arguments as JSON")
2256 })
2257 .transpose()?;
2258
2259 cx.build_action(self.editing_keybind.action().name, value)
2260 .context("Failed to validate action arguments")?;
2261 Ok(action_arguments)
2262 }
2263
2264 fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<KeybindingKeystroke>> {
2265 let new_keystrokes = self
2266 .keybind_editor
2267 .read_with(cx, |editor, _| editor.keystrokes().to_vec());
2268 anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
2269 Ok(new_keystrokes)
2270 }
2271
2272 fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
2273 let new_context = self
2274 .context_editor
2275 .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
2276 let Some(context) = new_context.is_empty().not().then_some(new_context) else {
2277 return Ok(None);
2278 };
2279 gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
2280
2281 Ok(Some(context))
2282 }
2283
2284 fn save_or_display_error(&mut self, cx: &mut Context<Self>) {
2285 self.save(cx).map_err(|err| self.set_error(err, cx)).ok();
2286 }
2287
2288 fn save(&mut self, cx: &mut Context<Self>) -> Result<(), InputError> {
2289 let existing_keybind = self.editing_keybind.clone();
2290 let fs = self.fs.clone();
2291 let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
2292
2293 let mut new_keystrokes = self.validate_keystrokes(cx).map_err(InputError::error)?;
2294 new_keystrokes
2295 .iter_mut()
2296 .for_each(|ks| ks.remove_key_char());
2297
2298 let new_context = self.validate_context(cx).map_err(InputError::error)?;
2299 let new_action_args = self
2300 .validate_action_arguments(cx)
2301 .map_err(InputError::error)?;
2302
2303 let action_mapping = ActionMapping {
2304 keystrokes: new_keystrokes,
2305 context: new_context.map(SharedString::from),
2306 };
2307
2308 let conflicting_indices = self
2309 .keymap_editor
2310 .read(cx)
2311 .keybinding_conflict_state
2312 .conflicting_indices_for_mapping(
2313 &action_mapping,
2314 self.creating.not().then_some(self.editing_keybind_idx),
2315 );
2316
2317 conflicting_indices.map(|KeybindConflict {
2318 first_conflict_index,
2319 remaining_conflict_amount,
2320 }|
2321 {
2322 let conflicting_action_name = self
2323 .keymap_editor
2324 .read(cx)
2325 .keybindings
2326 .get(first_conflict_index)
2327 .map(|keybind| keybind.action().name);
2328
2329 let warning_message = match conflicting_action_name {
2330 Some(name) => {
2331 if remaining_conflict_amount > 0 {
2332 format!(
2333 "Your keybind would conflict with the \"{}\" action and {} other bindings",
2334 name, remaining_conflict_amount
2335 )
2336 } else {
2337 format!("Your keybind would conflict with the \"{}\" action", name)
2338 }
2339 }
2340 None => {
2341 log::info!(
2342 "Could not find action in keybindings with index {}",
2343 first_conflict_index
2344 );
2345 "Your keybind would conflict with other actions".to_string()
2346 }
2347 };
2348
2349 let warning = InputError::warning(warning_message);
2350 if self.error.as_ref().is_some_and(|old_error| *old_error == warning) {
2351 Ok(())
2352 } else {
2353 Err(warning)
2354 }
2355 }).unwrap_or(Ok(()))?;
2356
2357 let create = self.creating;
2358 let keyboard_mapper = cx.keyboard_mapper().clone();
2359
2360 cx.spawn(async move |this, cx| {
2361 let action_name = existing_keybind.action().name;
2362 let humanized_action_name = existing_keybind.action().humanized_name.clone();
2363
2364 match save_keybinding_update(
2365 create,
2366 existing_keybind,
2367 &action_mapping,
2368 new_action_args.as_deref(),
2369 &fs,
2370 tab_size,
2371 keyboard_mapper.as_ref(),
2372 )
2373 .await
2374 {
2375 Ok(_) => {
2376 this.update(cx, |this, cx| {
2377 this.keymap_editor.update(cx, |keymap, cx| {
2378 keymap.previous_edit = Some(PreviousEdit::Keybinding {
2379 action_mapping,
2380 action_name,
2381 fallback: keymap.table_interaction_state.read(cx).scroll_offset(),
2382 });
2383 let status_toast = StatusToast::new(
2384 format!("Saved edits to the {} action.", humanized_action_name),
2385 cx,
2386 move |this, _cx| {
2387 this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
2388 .dismiss_button(true)
2389 // .action("Undo", f) todo: wire the undo functionality
2390 },
2391 );
2392
2393 this.workspace
2394 .update(cx, |workspace, cx| {
2395 workspace.toggle_status_toast(status_toast, cx);
2396 })
2397 .log_err();
2398 });
2399 cx.emit(DismissEvent);
2400 })
2401 .ok();
2402 }
2403 Err(err) => {
2404 this.update(cx, |this, cx| {
2405 this.set_error(InputError::error(err), cx);
2406 })
2407 .log_err();
2408 }
2409 }
2410 })
2411 .detach();
2412
2413 Ok(())
2414 }
2415
2416 fn key_context(&self) -> KeyContext {
2417 let mut key_context = KeyContext::new_with_defaults();
2418 key_context.add("KeybindEditorModal");
2419 key_context
2420 }
2421
2422 fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2423 self.focus_state.focus_next(window, cx);
2424 }
2425
2426 fn focus_prev(
2427 &mut self,
2428 _: &menu::SelectPrevious,
2429 window: &mut Window,
2430 cx: &mut Context<Self>,
2431 ) {
2432 self.focus_state.focus_previous(window, cx);
2433 }
2434
2435 fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2436 self.save_or_display_error(cx);
2437 }
2438
2439 fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
2440 cx.emit(DismissEvent);
2441 }
2442
2443 fn get_matching_bindings_count(&self, cx: &Context<Self>) -> usize {
2444 let current_keystrokes = self.keybind_editor.read(cx).keystrokes().to_vec();
2445
2446 if current_keystrokes.is_empty() {
2447 return 0;
2448 }
2449
2450 self.keymap_editor
2451 .read(cx)
2452 .keybindings
2453 .iter()
2454 .enumerate()
2455 .filter(|(idx, binding)| {
2456 // Don't count the binding we're currently editing
2457 if !self.creating && *idx == self.editing_keybind_idx {
2458 return false;
2459 }
2460
2461 binding
2462 .keystrokes()
2463 .map(|keystrokes| keystrokes_match_exactly(keystrokes, ¤t_keystrokes))
2464 .unwrap_or(false)
2465 })
2466 .count()
2467 }
2468
2469 fn show_matching_bindings(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2470 let keystrokes = self.keybind_editor.read(cx).keystrokes().to_vec();
2471
2472 // Dismiss the modal
2473 cx.emit(DismissEvent);
2474
2475 // Update the keymap editor to show matching keystrokes
2476 self.keymap_editor.update(cx, |editor, cx| {
2477 editor.filter_state = FilterState::All;
2478 editor.search_mode = SearchMode::KeyStroke { exact_match: true };
2479 editor.keystroke_editor.update(cx, |keystroke_editor, cx| {
2480 keystroke_editor.set_keystrokes(keystrokes, cx);
2481 });
2482 });
2483 }
2484}
2485
2486impl Render for KeybindingEditorModal {
2487 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2488 let theme = cx.theme().colors();
2489 let matching_bindings_count = self.get_matching_bindings_count(cx);
2490
2491 v_flex()
2492 .w(rems(34.))
2493 .elevation_3(cx)
2494 .key_context(self.key_context())
2495 .on_action(cx.listener(Self::focus_next))
2496 .on_action(cx.listener(Self::focus_prev))
2497 .on_action(cx.listener(Self::confirm))
2498 .on_action(cx.listener(Self::cancel))
2499 .child(
2500 Modal::new("keybinding_editor_modal", None)
2501 .header(
2502 ModalHeader::new().child(
2503 v_flex()
2504 .w_full()
2505 .pb_1p5()
2506 .mb_1()
2507 .gap_0p5()
2508 .border_b_1()
2509 .border_color(theme.border_variant)
2510 .child(Label::new(
2511 self.editing_keybind.action().humanized_name.clone(),
2512 ))
2513 .when_some(
2514 self.editing_keybind.action().documentation,
2515 |this, docs| {
2516 this.child(
2517 Label::new(docs)
2518 .size(LabelSize::Small)
2519 .color(Color::Muted),
2520 )
2521 },
2522 ),
2523 ),
2524 )
2525 .section(
2526 Section::new().child(
2527 v_flex()
2528 .gap_2p5()
2529 .child(
2530 v_flex()
2531 .gap_1()
2532 .child(Label::new("Edit Keystroke"))
2533 .child(self.keybind_editor.clone())
2534 .child(h_flex().gap_px().when(
2535 matching_bindings_count > 0,
2536 |this| {
2537 let label = format!(
2538 "There {} {} {} with the same keystrokes.",
2539 if matching_bindings_count == 1 {
2540 "is"
2541 } else {
2542 "are"
2543 },
2544 matching_bindings_count,
2545 if matching_bindings_count == 1 {
2546 "binding"
2547 } else {
2548 "bindings"
2549 }
2550 );
2551
2552 this.child(
2553 Label::new(label)
2554 .size(LabelSize::Small)
2555 .color(Color::Muted),
2556 )
2557 .child(
2558 Button::new("show_matching", "View")
2559 .label_size(LabelSize::Small)
2560 .icon(IconName::ArrowUpRight)
2561 .icon_color(Color::Muted)
2562 .icon_size(IconSize::Small)
2563 .on_click(cx.listener(
2564 |this, _, window, cx| {
2565 this.show_matching_bindings(
2566 window, cx,
2567 );
2568 },
2569 )),
2570 )
2571 },
2572 )),
2573 )
2574 .when_some(self.action_arguments_editor.clone(), |this, editor| {
2575 this.child(
2576 v_flex()
2577 .gap_1()
2578 .child(Label::new("Edit Arguments"))
2579 .child(editor),
2580 )
2581 })
2582 .child(self.context_editor.clone())
2583 .when_some(self.error.as_ref(), |this, error| {
2584 this.child(
2585 Banner::new()
2586 .severity(error.severity)
2587 .child(Label::new(error.content.clone())),
2588 )
2589 }),
2590 ),
2591 )
2592 .footer(
2593 ModalFooter::new().end_slot(
2594 h_flex()
2595 .gap_1()
2596 .child(
2597 Button::new("cancel", "Cancel")
2598 .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
2599 )
2600 .child(Button::new("save-btn", "Save").on_click(cx.listener(
2601 |this, _event, _window, cx| {
2602 this.save_or_display_error(cx);
2603 },
2604 ))),
2605 ),
2606 ),
2607 )
2608 }
2609}
2610
2611struct KeybindingEditorModalFocusState {
2612 handles: Vec<FocusHandle>,
2613}
2614
2615impl KeybindingEditorModalFocusState {
2616 fn new(
2617 keystrokes: FocusHandle,
2618 action_input: Option<FocusHandle>,
2619 context: FocusHandle,
2620 ) -> Self {
2621 Self {
2622 handles: Vec::from_iter(
2623 [Some(keystrokes), action_input, Some(context)]
2624 .into_iter()
2625 .flatten(),
2626 ),
2627 }
2628 }
2629
2630 fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
2631 self.handles
2632 .iter()
2633 .position(|handle| handle.contains_focused(window, cx))
2634 .map(|i| i as i32)
2635 }
2636
2637 fn focus_index(&self, mut index: i32, window: &mut Window) {
2638 if index < 0 {
2639 index = self.handles.len() as i32 - 1;
2640 }
2641 if index >= self.handles.len() as i32 {
2642 index = 0;
2643 }
2644 window.focus(&self.handles[index as usize]);
2645 }
2646
2647 fn focus_next(&self, window: &mut Window, cx: &App) {
2648 let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2649 index + 1
2650 } else {
2651 0
2652 };
2653 self.focus_index(index_to_focus, window);
2654 }
2655
2656 fn focus_previous(&self, window: &mut Window, cx: &App) {
2657 let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2658 index - 1
2659 } else {
2660 self.handles.len() as i32 - 1
2661 };
2662 self.focus_index(index_to_focus, window);
2663 }
2664}
2665
2666struct ActionArgumentsEditor {
2667 editor: Entity<Editor>,
2668 focus_handle: FocusHandle,
2669 is_loading: bool,
2670 /// See documentation in `KeymapEditor` for why a temp dir is needed.
2671 /// This field exists because the keymap editor temp dir creation may fail,
2672 /// and rather than implement a complicated retry mechanism, we simply
2673 /// fallback to trying to create a temporary directory in this editor on
2674 /// demand. Of note is that the TempDir struct will remove the directory
2675 /// when dropped.
2676 backup_temp_dir: Option<tempfile::TempDir>,
2677}
2678
2679impl Focusable for ActionArgumentsEditor {
2680 fn focus_handle(&self, _cx: &App) -> FocusHandle {
2681 self.focus_handle.clone()
2682 }
2683}
2684
2685impl ActionArgumentsEditor {
2686 fn new(
2687 action_name: &'static str,
2688 arguments: Option<SharedString>,
2689 temp_dir: Option<&std::path::Path>,
2690 workspace: WeakEntity<Workspace>,
2691 window: &mut Window,
2692 cx: &mut Context<Self>,
2693 ) -> Self {
2694 let focus_handle = cx.focus_handle();
2695 cx.on_focus_in(&focus_handle, window, |this, window, cx| {
2696 this.editor.focus_handle(cx).focus(window);
2697 })
2698 .detach();
2699 let editor = cx.new(|cx| {
2700 let mut editor = Editor::auto_height_unbounded(1, window, cx);
2701 Self::set_editor_text(&mut editor, arguments.clone(), window, cx);
2702 editor.set_read_only(true);
2703 editor
2704 });
2705
2706 let temp_dir = temp_dir.map(|path| path.to_owned());
2707 cx.spawn_in(window, async move |this, cx| {
2708 let result = async {
2709 let (project, fs) = workspace.read_with(cx, |workspace, _cx| {
2710 (
2711 workspace.project().downgrade(),
2712 workspace.app_state().fs.clone(),
2713 )
2714 })?;
2715
2716 let file_name = json_schema_store::normalized_action_file_name(action_name);
2717
2718 let (buffer, backup_temp_dir) =
2719 Self::create_temp_buffer(temp_dir, file_name.clone(), project.clone(), fs, cx)
2720 .await
2721 .context(concat!(
2722 "Failed to create temporary buffer for action arguments. ",
2723 "Auto-complete will not work"
2724 ))?;
2725
2726 let editor = cx.new_window_entity(|window, cx| {
2727 let multi_buffer = cx.new(|cx| editor::MultiBuffer::singleton(buffer, cx));
2728 let mut editor = Editor::new(
2729 editor::EditorMode::Full {
2730 scale_ui_elements_with_buffer_font_size: true,
2731 show_active_line_background: false,
2732 sized_by_content: true,
2733 },
2734 multi_buffer,
2735 project.upgrade(),
2736 window,
2737 cx,
2738 );
2739 editor.set_searchable(false);
2740 editor.disable_scrollbars_and_minimap(window, cx);
2741 editor.set_show_edit_predictions(Some(false), window, cx);
2742 editor.set_show_gutter(false, cx);
2743 Self::set_editor_text(&mut editor, arguments, window, cx);
2744 editor
2745 })?;
2746
2747 this.update_in(cx, |this, window, cx| {
2748 if this.editor.focus_handle(cx).is_focused(window) {
2749 editor.focus_handle(cx).focus(window);
2750 }
2751 this.editor = editor;
2752 this.backup_temp_dir = backup_temp_dir;
2753 this.is_loading = false;
2754 })?;
2755
2756 anyhow::Ok(())
2757 }
2758 .await;
2759 if result.is_err() {
2760 let json_language = load_json_language(workspace.clone(), cx).await;
2761 this.update(cx, |this, cx| {
2762 this.editor.update(cx, |editor, cx| {
2763 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2764 buffer.update(cx, |buffer, cx| {
2765 buffer.set_language(Some(json_language.clone()), cx)
2766 });
2767 }
2768 })
2769 // .context("Failed to load JSON language for editing keybinding action arguments input")
2770 })
2771 .ok();
2772 this.update(cx, |this, _cx| {
2773 this.is_loading = false;
2774 })
2775 .ok();
2776 }
2777 result
2778 })
2779 .detach_and_log_err(cx);
2780 Self {
2781 editor,
2782 focus_handle,
2783 is_loading: true,
2784 backup_temp_dir: None,
2785 }
2786 }
2787
2788 fn set_editor_text(
2789 editor: &mut Editor,
2790 arguments: Option<SharedString>,
2791 window: &mut Window,
2792 cx: &mut Context<Editor>,
2793 ) {
2794 if let Some(arguments) = arguments {
2795 editor.set_text(arguments, window, cx);
2796 } else {
2797 // TODO: default value from schema?
2798 editor.set_placeholder_text("Action Arguments", window, cx);
2799 }
2800 }
2801
2802 async fn create_temp_buffer(
2803 temp_dir: Option<std::path::PathBuf>,
2804 file_name: String,
2805 project: WeakEntity<Project>,
2806 fs: Arc<dyn Fs>,
2807 cx: &mut AsyncApp,
2808 ) -> anyhow::Result<(Entity<language::Buffer>, Option<tempfile::TempDir>)> {
2809 let (temp_file_path, temp_dir) = {
2810 let file_name = file_name.clone();
2811 async move {
2812 let temp_dir_backup = match temp_dir.as_ref() {
2813 Some(_) => None,
2814 None => {
2815 let temp_dir = paths::temp_dir();
2816 let sub_temp_dir = tempfile::Builder::new()
2817 .tempdir_in(temp_dir)
2818 .context("Failed to create temporary directory")?;
2819 Some(sub_temp_dir)
2820 }
2821 };
2822 let dir_path = temp_dir.as_deref().unwrap_or_else(|| {
2823 temp_dir_backup
2824 .as_ref()
2825 .expect("created backup tempdir")
2826 .path()
2827 });
2828 let path = dir_path.join(file_name);
2829 fs.create_file(
2830 &path,
2831 fs::CreateOptions {
2832 ignore_if_exists: true,
2833 overwrite: true,
2834 },
2835 )
2836 .await
2837 .context("Failed to create temporary file")?;
2838 anyhow::Ok((path, temp_dir_backup))
2839 }
2840 }
2841 .await
2842 .context("Failed to create backing file")?;
2843
2844 project
2845 .update(cx, |project, cx| {
2846 project.open_local_buffer(temp_file_path, cx)
2847 })?
2848 .await
2849 .context("Failed to create buffer")
2850 .map(|buffer| (buffer, temp_dir))
2851 }
2852}
2853
2854impl Render for ActionArgumentsEditor {
2855 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2856 let background_color;
2857 let border_color;
2858 let text_style = {
2859 let colors = cx.theme().colors();
2860 let settings = theme::ThemeSettings::get_global(cx);
2861 background_color = colors.editor_background;
2862 border_color = if self.is_loading {
2863 colors.border_disabled
2864 } else {
2865 colors.border_variant
2866 };
2867 TextStyleRefinement {
2868 font_size: Some(rems(0.875).into()),
2869 font_weight: Some(settings.buffer_font.weight),
2870 line_height: Some(relative(1.2)),
2871 font_style: Some(gpui::FontStyle::Normal),
2872 color: self.is_loading.then_some(colors.text_disabled),
2873 ..Default::default()
2874 }
2875 };
2876
2877 self.editor
2878 .update(cx, |editor, _| editor.set_text_style_refinement(text_style));
2879
2880 v_flex().w_full().child(
2881 h_flex()
2882 .min_h_8()
2883 .min_w_48()
2884 .px_2()
2885 .py_1p5()
2886 .flex_grow()
2887 .rounded_lg()
2888 .bg(background_color)
2889 .border_1()
2890 .border_color(border_color)
2891 .track_focus(&self.focus_handle)
2892 .child(self.editor.clone()),
2893 )
2894 }
2895}
2896
2897struct KeyContextCompletionProvider {
2898 contexts: Vec<SharedString>,
2899}
2900
2901impl CompletionProvider for KeyContextCompletionProvider {
2902 fn completions(
2903 &self,
2904 _excerpt_id: editor::ExcerptId,
2905 buffer: &Entity<language::Buffer>,
2906 buffer_position: language::Anchor,
2907 _trigger: editor::CompletionContext,
2908 _window: &mut Window,
2909 cx: &mut Context<Editor>,
2910 ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2911 let buffer = buffer.read(cx);
2912 let mut count_back = 0;
2913 for char in buffer.reversed_chars_at(buffer_position) {
2914 if char.is_ascii_alphanumeric() || char == '_' {
2915 count_back += 1;
2916 } else {
2917 break;
2918 }
2919 }
2920 let start_anchor =
2921 buffer.anchor_before(buffer_position.to_offset(buffer).saturating_sub(count_back));
2922 let replace_range = start_anchor..buffer_position;
2923 gpui::Task::ready(Ok(vec![project::CompletionResponse {
2924 completions: self
2925 .contexts
2926 .iter()
2927 .map(|context| project::Completion {
2928 replace_range: replace_range.clone(),
2929 label: language::CodeLabel::plain(context.to_string(), None),
2930 new_text: context.to_string(),
2931 documentation: None,
2932 source: project::CompletionSource::Custom,
2933 icon_path: None,
2934 insert_text_mode: None,
2935 confirm: None,
2936 })
2937 .collect(),
2938 display_options: CompletionDisplayOptions::default(),
2939 is_incomplete: false,
2940 }]))
2941 }
2942
2943 fn is_completion_trigger(
2944 &self,
2945 _buffer: &Entity<language::Buffer>,
2946 _position: language::Anchor,
2947 text: &str,
2948 _trigger_in_words: bool,
2949 _menu_is_open: bool,
2950 _cx: &mut Context<Editor>,
2951 ) -> bool {
2952 text.chars()
2953 .last()
2954 .is_some_and(|last_char| last_char.is_ascii_alphanumeric() || last_char == '_')
2955 }
2956}
2957
2958async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2959 let json_language_task = workspace
2960 .read_with(cx, |workspace, cx| {
2961 workspace
2962 .project()
2963 .read(cx)
2964 .languages()
2965 .language_for_name("JSON")
2966 })
2967 .context("Failed to load JSON language")
2968 .log_err();
2969 let json_language = match json_language_task {
2970 Some(task) => task.await.context("Failed to load JSON language").log_err(),
2971 None => None,
2972 };
2973 json_language.unwrap_or_else(|| {
2974 Arc::new(Language::new(
2975 LanguageConfig {
2976 name: "JSON".into(),
2977 ..Default::default()
2978 },
2979 Some(tree_sitter_json::LANGUAGE.into()),
2980 ))
2981 })
2982}
2983
2984async fn load_keybind_context_language(
2985 workspace: WeakEntity<Workspace>,
2986 cx: &mut AsyncApp,
2987) -> Arc<Language> {
2988 let language_task = workspace
2989 .read_with(cx, |workspace, cx| {
2990 workspace
2991 .project()
2992 .read(cx)
2993 .languages()
2994 .language_for_name("Zed Keybind Context")
2995 })
2996 .context("Failed to load Zed Keybind Context language")
2997 .log_err();
2998 let language = match language_task {
2999 Some(task) => task
3000 .await
3001 .context("Failed to load Zed Keybind Context language")
3002 .log_err(),
3003 None => None,
3004 };
3005 language.unwrap_or_else(|| {
3006 Arc::new(Language::new(
3007 LanguageConfig {
3008 name: "Zed Keybind Context".into(),
3009 ..Default::default()
3010 },
3011 Some(tree_sitter_rust::LANGUAGE.into()),
3012 ))
3013 })
3014}
3015
3016async fn save_keybinding_update(
3017 create: bool,
3018 existing: ProcessedBinding,
3019 action_mapping: &ActionMapping,
3020 new_args: Option<&str>,
3021 fs: &Arc<dyn Fs>,
3022 tab_size: usize,
3023 keyboard_mapper: &dyn PlatformKeyboardMapper,
3024) -> anyhow::Result<()> {
3025 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3026 .await
3027 .context("Failed to load keymap file")?;
3028
3029 let existing_keystrokes = existing.keystrokes().unwrap_or_default();
3030 let existing_context = existing.context().and_then(KeybindContextString::local_str);
3031 let existing_args = existing
3032 .action()
3033 .arguments
3034 .as_ref()
3035 .map(|args| args.text.as_ref());
3036
3037 let target = settings::KeybindUpdateTarget {
3038 context: existing_context,
3039 keystrokes: existing_keystrokes,
3040 action_name: existing.action().name,
3041 action_arguments: existing_args,
3042 };
3043
3044 let source = settings::KeybindUpdateTarget {
3045 context: action_mapping.context.as_ref().map(|a| &***a),
3046 keystrokes: &action_mapping.keystrokes,
3047 action_name: existing.action().name,
3048 action_arguments: new_args,
3049 };
3050
3051 let operation = if !create {
3052 settings::KeybindUpdateOperation::Replace {
3053 target,
3054 target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
3055 source,
3056 }
3057 } else {
3058 settings::KeybindUpdateOperation::Add {
3059 source,
3060 from: Some(target),
3061 }
3062 };
3063
3064 let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
3065
3066 let updated_keymap_contents = settings::KeymapFile::update_keybinding(
3067 operation,
3068 keymap_contents,
3069 tab_size,
3070 keyboard_mapper,
3071 )
3072 .map_err(|err| anyhow::anyhow!("Could not save updated keybinding: {}", err))?;
3073 fs.write(
3074 paths::keymap_file().as_path(),
3075 updated_keymap_contents.as_bytes(),
3076 )
3077 .await
3078 .context("Failed to write keymap file")?;
3079
3080 telemetry::event!(
3081 "Keybinding Updated",
3082 new_keybinding = new_keybinding,
3083 removed_keybinding = removed_keybinding,
3084 source = source
3085 );
3086 Ok(())
3087}
3088
3089async fn remove_keybinding(
3090 existing: ProcessedBinding,
3091 fs: &Arc<dyn Fs>,
3092 tab_size: usize,
3093 keyboard_mapper: &dyn PlatformKeyboardMapper,
3094) -> anyhow::Result<()> {
3095 let Some(keystrokes) = existing.keystrokes() else {
3096 anyhow::bail!("Cannot remove a keybinding that does not exist");
3097 };
3098 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3099 .await
3100 .context("Failed to load keymap file")?;
3101
3102 let operation = settings::KeybindUpdateOperation::Remove {
3103 target: settings::KeybindUpdateTarget {
3104 context: existing.context().and_then(KeybindContextString::local_str),
3105 keystrokes,
3106 action_name: existing.action().name,
3107 action_arguments: existing
3108 .action()
3109 .arguments
3110 .as_ref()
3111 .map(|arguments| arguments.text.as_ref()),
3112 },
3113 target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
3114 };
3115
3116 let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
3117 let updated_keymap_contents = settings::KeymapFile::update_keybinding(
3118 operation,
3119 keymap_contents,
3120 tab_size,
3121 keyboard_mapper,
3122 )
3123 .context("Failed to update keybinding")?;
3124 fs.write(
3125 paths::keymap_file().as_path(),
3126 updated_keymap_contents.as_bytes(),
3127 )
3128 .await
3129 .context("Failed to write keymap file")?;
3130
3131 telemetry::event!(
3132 "Keybinding Removed",
3133 new_keybinding = new_keybinding,
3134 removed_keybinding = removed_keybinding,
3135 source = source
3136 );
3137 Ok(())
3138}
3139
3140fn collect_contexts_from_assets() -> Vec<SharedString> {
3141 let mut keymap_assets = vec![
3142 util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
3143 util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
3144 ];
3145 keymap_assets.extend(
3146 BaseKeymap::OPTIONS
3147 .iter()
3148 .filter_map(|(_, base_keymap)| base_keymap.asset_path())
3149 .map(util::asset_str::<SettingsAssets>),
3150 );
3151
3152 let mut contexts = HashSet::default();
3153
3154 for keymap_asset in keymap_assets {
3155 let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
3156 continue;
3157 };
3158
3159 for section in keymap.sections() {
3160 let context_expr = §ion.context;
3161 let mut queue = Vec::new();
3162 let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
3163 continue;
3164 };
3165
3166 queue.push(root_context);
3167 while let Some(context) = queue.pop() {
3168 match context {
3169 Identifier(ident) => {
3170 contexts.insert(ident);
3171 }
3172 Equal(ident_a, ident_b) => {
3173 contexts.insert(ident_a);
3174 contexts.insert(ident_b);
3175 }
3176 NotEqual(ident_a, ident_b) => {
3177 contexts.insert(ident_a);
3178 contexts.insert(ident_b);
3179 }
3180 Descendant(ctx_a, ctx_b) => {
3181 queue.push(*ctx_a);
3182 queue.push(*ctx_b);
3183 }
3184 Not(ctx) => {
3185 queue.push(*ctx);
3186 }
3187 And(ctx_a, ctx_b) => {
3188 queue.push(*ctx_a);
3189 queue.push(*ctx_b);
3190 }
3191 Or(ctx_a, ctx_b) => {
3192 queue.push(*ctx_a);
3193 queue.push(*ctx_b);
3194 }
3195 }
3196 }
3197 }
3198 }
3199
3200 let mut contexts = contexts.into_iter().collect::<Vec<_>>();
3201 contexts.sort();
3202
3203 contexts
3204}
3205
3206fn normalized_ctx_eq(
3207 a: &gpui::KeyBindingContextPredicate,
3208 b: &gpui::KeyBindingContextPredicate,
3209) -> bool {
3210 use gpui::KeyBindingContextPredicate::*;
3211 return match (a, b) {
3212 (Identifier(_), Identifier(_)) => a == b,
3213 (Equal(a_left, a_right), Equal(b_left, b_right)) => {
3214 (a_left == b_left && a_right == b_right) || (a_left == b_right && a_right == b_left)
3215 }
3216 (NotEqual(a_left, a_right), NotEqual(b_left, b_right)) => {
3217 (a_left == b_left && a_right == b_right) || (a_left == b_right && a_right == b_left)
3218 }
3219 (Descendant(a_parent, a_child), Descendant(b_parent, b_child)) => {
3220 normalized_ctx_eq(a_parent, b_parent) && normalized_ctx_eq(a_child, b_child)
3221 }
3222 (Not(a_expr), Not(b_expr)) => normalized_ctx_eq(a_expr, b_expr),
3223 // Handle double negation: !(!a) == a
3224 (Not(a_expr), b) if matches!(a_expr.as_ref(), Not(_)) => {
3225 let Not(a_inner) = a_expr.as_ref() else {
3226 unreachable!();
3227 };
3228 normalized_ctx_eq(b, a_inner)
3229 }
3230 (a, Not(b_expr)) if matches!(b_expr.as_ref(), Not(_)) => {
3231 let Not(b_inner) = b_expr.as_ref() else {
3232 unreachable!();
3233 };
3234 normalized_ctx_eq(a, b_inner)
3235 }
3236 (And(a_left, a_right), And(b_left, b_right))
3237 if matches!(a_left.as_ref(), And(_, _))
3238 || matches!(a_right.as_ref(), And(_, _))
3239 || matches!(b_left.as_ref(), And(_, _))
3240 || matches!(b_right.as_ref(), And(_, _)) =>
3241 {
3242 let mut a_operands = Vec::new();
3243 flatten_and(a, &mut a_operands);
3244 let mut b_operands = Vec::new();
3245 flatten_and(b, &mut b_operands);
3246 compare_operand_sets(&a_operands, &b_operands)
3247 }
3248 (And(a_left, a_right), And(b_left, b_right)) => {
3249 (normalized_ctx_eq(a_left, b_left) && normalized_ctx_eq(a_right, b_right))
3250 || (normalized_ctx_eq(a_left, b_right) && normalized_ctx_eq(a_right, b_left))
3251 }
3252 (Or(a_left, a_right), Or(b_left, b_right))
3253 if matches!(a_left.as_ref(), Or(_, _))
3254 || matches!(a_right.as_ref(), Or(_, _))
3255 || matches!(b_left.as_ref(), Or(_, _))
3256 || matches!(b_right.as_ref(), Or(_, _)) =>
3257 {
3258 let mut a_operands = Vec::new();
3259 flatten_or(a, &mut a_operands);
3260 let mut b_operands = Vec::new();
3261 flatten_or(b, &mut b_operands);
3262 compare_operand_sets(&a_operands, &b_operands)
3263 }
3264 (Or(a_left, a_right), Or(b_left, b_right)) => {
3265 (normalized_ctx_eq(a_left, b_left) && normalized_ctx_eq(a_right, b_right))
3266 || (normalized_ctx_eq(a_left, b_right) && normalized_ctx_eq(a_right, b_left))
3267 }
3268 _ => false,
3269 };
3270
3271 fn flatten_and<'a>(
3272 pred: &'a gpui::KeyBindingContextPredicate,
3273 operands: &mut Vec<&'a gpui::KeyBindingContextPredicate>,
3274 ) {
3275 use gpui::KeyBindingContextPredicate::*;
3276 match pred {
3277 And(left, right) => {
3278 flatten_and(left, operands);
3279 flatten_and(right, operands);
3280 }
3281 _ => operands.push(pred),
3282 }
3283 }
3284
3285 fn flatten_or<'a>(
3286 pred: &'a gpui::KeyBindingContextPredicate,
3287 operands: &mut Vec<&'a gpui::KeyBindingContextPredicate>,
3288 ) {
3289 use gpui::KeyBindingContextPredicate::*;
3290 match pred {
3291 Or(left, right) => {
3292 flatten_or(left, operands);
3293 flatten_or(right, operands);
3294 }
3295 _ => operands.push(pred),
3296 }
3297 }
3298
3299 fn compare_operand_sets(
3300 a: &[&gpui::KeyBindingContextPredicate],
3301 b: &[&gpui::KeyBindingContextPredicate],
3302 ) -> bool {
3303 if a.len() != b.len() {
3304 return false;
3305 }
3306
3307 // For each operand in a, find a matching operand in b
3308 let mut b_matched = vec![false; b.len()];
3309 for a_operand in a {
3310 let mut found = false;
3311 for (b_idx, b_operand) in b.iter().enumerate() {
3312 if !b_matched[b_idx] && normalized_ctx_eq(a_operand, b_operand) {
3313 b_matched[b_idx] = true;
3314 found = true;
3315 break;
3316 }
3317 }
3318 if !found {
3319 return false;
3320 }
3321 }
3322
3323 true
3324 }
3325}
3326
3327impl SerializableItem for KeymapEditor {
3328 fn serialized_item_kind() -> &'static str {
3329 "KeymapEditor"
3330 }
3331
3332 fn cleanup(
3333 workspace_id: workspace::WorkspaceId,
3334 alive_items: Vec<workspace::ItemId>,
3335 _window: &mut Window,
3336 cx: &mut App,
3337 ) -> gpui::Task<gpui::Result<()>> {
3338 workspace::delete_unloaded_items(
3339 alive_items,
3340 workspace_id,
3341 "keybinding_editors",
3342 &KEYBINDING_EDITORS,
3343 cx,
3344 )
3345 }
3346
3347 fn deserialize(
3348 _project: Entity<project::Project>,
3349 workspace: WeakEntity<Workspace>,
3350 workspace_id: workspace::WorkspaceId,
3351 item_id: workspace::ItemId,
3352 window: &mut Window,
3353 cx: &mut App,
3354 ) -> gpui::Task<gpui::Result<Entity<Self>>> {
3355 window.spawn(cx, async move |cx| {
3356 if KEYBINDING_EDITORS
3357 .get_keybinding_editor(item_id, workspace_id)?
3358 .is_some()
3359 {
3360 cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
3361 } else {
3362 Err(anyhow!("No keybinding editor to deserialize"))
3363 }
3364 })
3365 }
3366
3367 fn serialize(
3368 &mut self,
3369 workspace: &mut Workspace,
3370 item_id: workspace::ItemId,
3371 _closing: bool,
3372 _window: &mut Window,
3373 cx: &mut ui::Context<Self>,
3374 ) -> Option<gpui::Task<gpui::Result<()>>> {
3375 let workspace_id = workspace.database_id()?;
3376 Some(cx.background_spawn(async move {
3377 KEYBINDING_EDITORS
3378 .save_keybinding_editor(item_id, workspace_id)
3379 .await
3380 }))
3381 }
3382
3383 fn should_serialize(&self, _event: &Self::Event) -> bool {
3384 false
3385 }
3386}
3387
3388mod persistence {
3389 use db::{query, sqlez::domain::Domain, sqlez_macros::sql};
3390 use workspace::WorkspaceDb;
3391
3392 pub struct KeybindingEditorDb(db::sqlez::thread_safe_connection::ThreadSafeConnection);
3393
3394 impl Domain for KeybindingEditorDb {
3395 const NAME: &str = stringify!(KeybindingEditorDb);
3396
3397 const MIGRATIONS: &[&str] = &[sql!(
3398 CREATE TABLE keybinding_editors (
3399 workspace_id INTEGER,
3400 item_id INTEGER UNIQUE,
3401
3402 PRIMARY KEY(workspace_id, item_id),
3403 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
3404 ON DELETE CASCADE
3405 ) STRICT;
3406 )];
3407 }
3408
3409 db::static_connection!(KEYBINDING_EDITORS, KeybindingEditorDb, [WorkspaceDb]);
3410
3411 impl KeybindingEditorDb {
3412 query! {
3413 pub async fn save_keybinding_editor(
3414 item_id: workspace::ItemId,
3415 workspace_id: workspace::WorkspaceId
3416 ) -> Result<()> {
3417 INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3418 VALUES (?, ?)
3419 }
3420 }
3421
3422 query! {
3423 pub fn get_keybinding_editor(
3424 item_id: workspace::ItemId,
3425 workspace_id: workspace::WorkspaceId
3426 ) -> Result<Option<workspace::ItemId>> {
3427 SELECT item_id
3428 FROM keybinding_editors
3429 WHERE item_id = ? AND workspace_id = ?
3430 }
3431 }
3432 }
3433}
3434
3435#[cfg(test)]
3436mod tests {
3437 use super::*;
3438
3439 #[test]
3440 fn normalized_ctx_cmp() {
3441 #[track_caller]
3442 fn cmp(a: &str, b: &str) -> bool {
3443 let a = gpui::KeyBindingContextPredicate::parse(a)
3444 .expect("Failed to parse keybinding context a");
3445 let b = gpui::KeyBindingContextPredicate::parse(b)
3446 .expect("Failed to parse keybinding context b");
3447 normalized_ctx_eq(&a, &b)
3448 }
3449
3450 // Basic equality - identical expressions
3451 assert!(cmp("a && b", "a && b"));
3452 assert!(cmp("a || b", "a || b"));
3453 assert!(cmp("a == b", "a == b"));
3454 assert!(cmp("a != b", "a != b"));
3455 assert!(cmp("a > b", "a > b"));
3456 assert!(cmp("!a", "!a"));
3457
3458 // AND operator - associative/commutative
3459 assert!(cmp("a && b", "b && a"));
3460 assert!(cmp("a && b && c", "c && b && a"));
3461 assert!(cmp("a && b && c", "b && a && c"));
3462 assert!(cmp("a && b && c && d", "d && c && b && a"));
3463
3464 // OR operator - associative/commutative
3465 assert!(cmp("a || b", "b || a"));
3466 assert!(cmp("a || b || c", "c || b || a"));
3467 assert!(cmp("a || b || c", "b || a || c"));
3468 assert!(cmp("a || b || c || d", "d || c || b || a"));
3469
3470 // Equality operator - associative/commutative
3471 assert!(cmp("a == b", "b == a"));
3472 assert!(cmp("x == y", "y == x"));
3473
3474 // Inequality operator - associative/commutative
3475 assert!(cmp("a != b", "b != a"));
3476 assert!(cmp("x != y", "y != x"));
3477
3478 // Complex nested expressions with associative operators
3479 assert!(cmp("(a && b) || c", "c || (a && b)"));
3480 assert!(cmp("(a && b) || c", "c || (b && a)"));
3481 assert!(cmp("(a || b) && c", "c && (a || b)"));
3482 assert!(cmp("(a || b) && c", "c && (b || a)"));
3483 assert!(cmp("(a && b) || (c && d)", "(c && d) || (a && b)"));
3484 assert!(cmp("(a && b) || (c && d)", "(d && c) || (b && a)"));
3485
3486 // Multiple levels of nesting
3487 assert!(cmp("((a && b) || c) && d", "d && ((a && b) || c)"));
3488 assert!(cmp("((a && b) || c) && d", "d && (c || (b && a))"));
3489 assert!(cmp("a && (b || (c && d))", "(b || (c && d)) && a"));
3490 assert!(cmp("a && (b || (c && d))", "(b || (d && c)) && a"));
3491
3492 // Negation with associative operators
3493 assert!(cmp("!a && b", "b && !a"));
3494 assert!(cmp("!a || b", "b || !a"));
3495 assert!(cmp("!(a && b) || c", "c || !(a && b)"));
3496 assert!(cmp("!(a && b) || c", "c || !(b && a)"));
3497
3498 // Descendant operator (>) - NOT associative/commutative
3499 assert!(cmp("a > b", "a > b"));
3500 assert!(!cmp("a > b", "b > a"));
3501 assert!(!cmp("a > b > c", "c > b > a"));
3502 assert!(!cmp("a > b > c", "a > c > b"));
3503
3504 // Mixed operators with descendant
3505 assert!(cmp("(a > b) && c", "c && (a > b)"));
3506 assert!(!cmp("(a > b) && c", "c && (b > a)"));
3507 assert!(cmp("(a > b) || (c > d)", "(c > d) || (a > b)"));
3508 assert!(!cmp("(a > b) || (c > d)", "(b > a) || (d > c)"));
3509
3510 // Negative cases - different operators
3511 assert!(!cmp("a && b", "a || b"));
3512 assert!(!cmp("a == b", "a != b"));
3513 assert!(!cmp("a && b", "a > b"));
3514 assert!(!cmp("a || b", "a > b"));
3515 assert!(!cmp("a == b", "a && b"));
3516 assert!(!cmp("a != b", "a || b"));
3517
3518 // Negative cases - different operands
3519 assert!(!cmp("a && b", "a && c"));
3520 assert!(!cmp("a && b", "c && d"));
3521 assert!(!cmp("a || b", "a || c"));
3522 assert!(!cmp("a || b", "c || d"));
3523 assert!(!cmp("a == b", "a == c"));
3524 assert!(!cmp("a != b", "a != c"));
3525 assert!(!cmp("a > b", "a > c"));
3526 assert!(!cmp("a > b", "c > b"));
3527
3528 // Negative cases - with negation
3529 assert!(!cmp("!a", "a"));
3530 assert!(!cmp("!a && b", "a && b"));
3531 assert!(!cmp("!(a && b)", "a && b"));
3532 assert!(!cmp("!a || b", "a || b"));
3533 assert!(!cmp("!(a || b)", "a || b"));
3534
3535 // Negative cases - complex expressions
3536 assert!(!cmp("(a && b) || c", "(a || b) && c"));
3537 assert!(!cmp("a && (b || c)", "a || (b && c)"));
3538 assert!(!cmp("(a && b) || (c && d)", "(a || b) && (c || d)"));
3539 assert!(!cmp("a > b && c", "a && b > c"));
3540
3541 // Edge cases - multiple same operands
3542 assert!(cmp("a && a", "a && a"));
3543 assert!(cmp("a || a", "a || a"));
3544 assert!(cmp("a && a && b", "b && a && a"));
3545 assert!(cmp("a || a || b", "b || a || a"));
3546
3547 // Edge cases - deeply nested
3548 assert!(cmp(
3549 "((a && b) || (c && d)) && ((e || f) && g)",
3550 "((e || f) && g) && ((c && d) || (a && b))"
3551 ));
3552 assert!(cmp(
3553 "((a && b) || (c && d)) && ((e || f) && g)",
3554 "(g && (f || e)) && ((d && c) || (b && a))"
3555 ));
3556
3557 // Edge cases - repeated patterns
3558 assert!(cmp("(a && b) || (a && b)", "(b && a) || (b && a)"));
3559 assert!(cmp("(a || b) && (a || b)", "(b || a) && (b || a)"));
3560
3561 // Negative cases - subtle differences
3562 assert!(!cmp("a && b && c", "a && b"));
3563 assert!(!cmp("a || b || c", "a || b"));
3564 assert!(!cmp("(a && b) || c", "a && (b || c)"));
3565
3566 // a > b > c is not the same as a > c, should not be equal
3567 assert!(!cmp("a > b > c", "a > c"));
3568
3569 // Double negation with complex expressions
3570 assert!(cmp("!(!(a && b))", "a && b"));
3571 assert!(cmp("!(!(a || b))", "a || b"));
3572 assert!(cmp("!(!(a > b))", "a > b"));
3573 assert!(cmp("!(!a) && b", "a && b"));
3574 assert!(cmp("!(!a) || b", "a || b"));
3575 assert!(cmp("!(!(a && b)) || c", "(a && b) || c"));
3576 assert!(cmp("!(!(a && b)) || c", "(b && a) || c"));
3577 assert!(cmp("!(!a)", "a"));
3578 assert!(cmp("a", "!(!a)"));
3579 assert!(cmp("!(!(!a))", "!a"));
3580 assert!(cmp("!(!(!(!a)))", "a"));
3581 }
3582}