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