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