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