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