1use std::{
2 cmp::{self},
3 ops::{Not as _, Range},
4 sync::Arc,
5 time::Duration,
6};
7
8mod ui_components;
9
10use anyhow::{Context as _, anyhow};
11use collections::{HashMap, HashSet};
12use editor::{CompletionProvider, Editor, EditorEvent};
13use fs::Fs;
14use fuzzy::{StringMatch, StringMatchCandidate};
15use gpui::{
16 Action, AppContext as _, AsyncApp, Axis, ClickEvent, Context, DismissEvent, Entity,
17 EventEmitter, FocusHandle, Focusable, Global, IsZero,
18 KeyBindingContextPredicate::{And, Descendant, Equal, Identifier, Not, NotEqual, Or},
19 KeyContext, KeybindingKeystroke, MouseButton, PlatformKeyboardMapper, Point, ScrollStrategy,
20 ScrollWheelEvent, Stateful, StyledText, Subscription, Task, TextStyleRefinement, WeakEntity,
21 actions, anchored, deferred, div,
22};
23use language::{Language, LanguageConfig, ToOffset as _};
24use notifications::status_toast::{StatusToast, ToastIcon};
25use project::{CompletionDisplayOptions, Project};
26use settings::{BaseKeymap, KeybindSource, KeymapFile, Settings as _, SettingsAssets};
27use ui::{
28 ActiveTheme as _, App, Banner, BorrowAppContext, ContextMenu, IconButtonShape, Indicator,
29 Modal, ModalFooter, ModalHeader, ParentElement as _, Render, Section, SharedString,
30 Styled as _, Tooltip, Window, prelude::*, right_click_menu,
31};
32use ui_input::SingleLineInput;
33use util::ResultExt;
34use workspace::{
35 Item, ModalView, SerializableItem, Workspace, notifications::NotifyTaskExt as _,
36 register_serializable_item,
37};
38
39pub use ui_components::*;
40
41use crate::{
42 persistence::KEYBINDING_EDITORS,
43 ui_components::{
44 keystroke_input::{ClearKeystrokes, KeystrokeInput, StartRecording, StopRecording},
45 table::{ColumnWidths, ResizeBehavior, Table, TableInteractionState},
46 },
47};
48
49const NO_ACTION_ARGUMENTS_TEXT: SharedString = SharedString::new_static("<no arguments>");
50
51actions!(
52 zed,
53 [
54 /// Opens the keymap editor.
55 OpenKeymapEditor
56 ]
57);
58
59actions!(
60 keymap_editor,
61 [
62 /// Edits the selected key binding.
63 EditBinding,
64 /// Creates a new key binding for the selected action.
65 CreateBinding,
66 /// Deletes the selected key binding.
67 DeleteBinding,
68 /// Copies the action name to clipboard.
69 CopyAction,
70 /// Copies the context predicate to clipboard.
71 CopyContext,
72 /// Toggles Conflict Filtering
73 ToggleConflictFilter,
74 /// Toggle Keystroke search
75 ToggleKeystrokeSearch,
76 /// Toggles exact matching for keystroke search
77 ToggleExactKeystrokeMatching,
78 /// Shows matching keystrokes for the currently selected binding
79 ShowMatchingKeybinds
80 ]
81);
82
83pub fn init(cx: &mut App) {
84 let keymap_event_channel = KeymapEventChannel::new();
85 cx.set_global(keymap_event_channel);
86
87 cx.on_action(|_: &OpenKeymapEditor, cx| {
88 workspace::with_active_or_new_workspace(cx, move |workspace, window, cx| {
89 workspace
90 .with_local_workspace(window, cx, |workspace, window, cx| {
91 let existing = workspace
92 .active_pane()
93 .read(cx)
94 .items()
95 .find_map(|item| item.downcast::<KeymapEditor>());
96
97 if let Some(existing) = existing {
98 workspace.activate_item(&existing, true, true, window, cx);
99 } else {
100 let keymap_editor =
101 cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
102 workspace.add_item_to_active_pane(
103 Box::new(keymap_editor),
104 None,
105 true,
106 window,
107 cx,
108 );
109 }
110 })
111 .detach();
112 })
113 });
114
115 register_serializable_item::<KeymapEditor>(cx);
116}
117
118pub struct KeymapEventChannel {}
119
120impl Global for KeymapEventChannel {}
121
122impl KeymapEventChannel {
123 fn new() -> Self {
124 Self {}
125 }
126
127 pub fn trigger_keymap_changed(cx: &mut App) {
128 let Some(_event_channel) = cx.try_global::<Self>() else {
129 // don't panic if no global defined. This usually happens in tests
130 return;
131 };
132 cx.update_global(|_event_channel: &mut Self, _| {
133 /* triggers observers in KeymapEditors */
134 });
135 }
136}
137
138#[derive(Default, PartialEq)]
139enum SearchMode {
140 #[default]
141 Normal,
142 KeyStroke {
143 exact_match: bool,
144 },
145}
146
147impl SearchMode {
148 fn invert(&self) -> Self {
149 match self {
150 SearchMode::Normal => SearchMode::KeyStroke { exact_match: false },
151 SearchMode::KeyStroke { .. } => SearchMode::Normal,
152 }
153 }
154
155 fn exact_match(&self) -> bool {
156 match self {
157 SearchMode::Normal => false,
158 SearchMode::KeyStroke { exact_match } => *exact_match,
159 }
160 }
161}
162
163#[derive(Default, PartialEq, Copy, Clone)]
164enum FilterState {
165 #[default]
166 All,
167 Conflicts,
168}
169
170impl FilterState {
171 fn invert(&self) -> Self {
172 match self {
173 FilterState::All => FilterState::Conflicts,
174 FilterState::Conflicts => FilterState::All,
175 }
176 }
177}
178
179#[derive(Debug, Default, PartialEq, Eq, Clone, Hash)]
180struct ActionMapping {
181 keystrokes: Vec<KeybindingKeystroke>,
182 context: Option<SharedString>,
183}
184
185#[derive(Debug)]
186struct KeybindConflict {
187 first_conflict_index: usize,
188 remaining_conflict_amount: usize,
189}
190
191#[derive(Clone, Copy, PartialEq)]
192struct ConflictOrigin {
193 override_source: KeybindSource,
194 overridden_source: Option<KeybindSource>,
195 index: usize,
196}
197
198impl ConflictOrigin {
199 fn new(source: KeybindSource, index: usize) -> Self {
200 Self {
201 override_source: source,
202 index,
203 overridden_source: None,
204 }
205 }
206
207 fn with_overridden_source(self, source: KeybindSource) -> Self {
208 Self {
209 overridden_source: Some(source),
210 ..self
211 }
212 }
213
214 fn get_conflict_with(&self, other: &Self) -> Option<Self> {
215 if self.override_source == KeybindSource::User
216 && other.override_source == KeybindSource::User
217 {
218 Some(
219 Self::new(KeybindSource::User, other.index)
220 .with_overridden_source(self.override_source),
221 )
222 } else if self.override_source > other.override_source {
223 Some(other.with_overridden_source(self.override_source))
224 } else {
225 None
226 }
227 }
228
229 fn is_user_keybind_conflict(&self) -> bool {
230 self.override_source == KeybindSource::User
231 && self.overridden_source == Some(KeybindSource::User)
232 }
233}
234
235#[derive(Default)]
236struct ConflictState {
237 conflicts: Vec<Option<ConflictOrigin>>,
238 keybind_mapping: ConflictKeybindMapping,
239 has_user_conflicts: bool,
240}
241
242type ConflictKeybindMapping = HashMap<
243 Vec<KeybindingKeystroke>,
244 Vec<(
245 Option<gpui::KeyBindingContextPredicate>,
246 Vec<ConflictOrigin>,
247 )>,
248>;
249
250impl ConflictState {
251 fn new(key_bindings: &[ProcessedBinding]) -> Self {
252 let mut action_keybind_mapping = ConflictKeybindMapping::default();
253
254 let mut largest_index = 0;
255 for (index, binding) in key_bindings
256 .iter()
257 .enumerate()
258 .flat_map(|(index, binding)| Some(index).zip(binding.keybind_information()))
259 {
260 let mapping = binding.get_action_mapping();
261 let predicate = mapping
262 .context
263 .and_then(|ctx| gpui::KeyBindingContextPredicate::parse(&ctx).ok());
264 let entry = action_keybind_mapping
265 .entry(mapping.keystrokes)
266 .or_default();
267 let origin = ConflictOrigin::new(binding.source, index);
268 if let Some((_, origins)) =
269 entry
270 .iter_mut()
271 .find(|(other_predicate, _)| match (&predicate, other_predicate) {
272 (None, None) => true,
273 (Some(a), Some(b)) => normalized_ctx_eq(a, b),
274 _ => false,
275 })
276 {
277 origins.push(origin);
278 } else {
279 entry.push((predicate, vec![origin]));
280 }
281 largest_index = index;
282 }
283
284 let mut conflicts = vec![None; largest_index + 1];
285 let mut has_user_conflicts = false;
286
287 for entries in action_keybind_mapping.values_mut() {
288 for (_, indices) in entries.iter_mut() {
289 indices.sort_unstable_by_key(|origin| origin.override_source);
290 let Some((fst, snd)) = indices.get(0).zip(indices.get(1)) else {
291 continue;
292 };
293
294 for origin in indices.iter() {
295 conflicts[origin.index] =
296 origin.get_conflict_with(if origin == fst { snd } else { fst })
297 }
298
299 has_user_conflicts |= fst.override_source == KeybindSource::User
300 && snd.override_source == KeybindSource::User;
301 }
302 }
303
304 Self {
305 conflicts,
306 keybind_mapping: action_keybind_mapping,
307 has_user_conflicts,
308 }
309 }
310
311 fn conflicting_indices_for_mapping(
312 &self,
313 action_mapping: &ActionMapping,
314 keybind_idx: Option<usize>,
315 ) -> Option<KeybindConflict> {
316 let ActionMapping {
317 keystrokes,
318 context,
319 } = action_mapping;
320 let predicate = context
321 .as_deref()
322 .and_then(|ctx| gpui::KeyBindingContextPredicate::parse(&ctx).ok());
323 self.keybind_mapping.get(keystrokes).and_then(|entries| {
324 entries
325 .iter()
326 .find_map(|(other_predicate, indices)| {
327 match (&predicate, other_predicate) {
328 (None, None) => true,
329 (Some(pred), Some(other)) => normalized_ctx_eq(pred, other),
330 _ => false,
331 }
332 .then_some(indices)
333 })
334 .and_then(|indices| {
335 let mut indices = indices
336 .iter()
337 .filter(|&conflict| Some(conflict.index) != keybind_idx);
338 indices.next().map(|origin| KeybindConflict {
339 first_conflict_index: origin.index,
340 remaining_conflict_amount: indices.count(),
341 })
342 })
343 })
344 }
345
346 fn conflict_for_idx(&self, idx: usize) -> Option<ConflictOrigin> {
347 self.conflicts.get(idx).copied().flatten()
348 }
349
350 fn has_user_conflict(&self, candidate_idx: usize) -> bool {
351 self.conflict_for_idx(candidate_idx)
352 .is_some_and(|conflict| conflict.is_user_keybind_conflict())
353 }
354
355 fn any_user_binding_conflicts(&self) -> bool {
356 self.has_user_conflicts
357 }
358}
359
360struct KeymapEditor {
361 workspace: WeakEntity<Workspace>,
362 focus_handle: FocusHandle,
363 _keymap_subscription: Subscription,
364 keybindings: Vec<ProcessedBinding>,
365 keybinding_conflict_state: ConflictState,
366 filter_state: FilterState,
367 search_mode: SearchMode,
368 search_query_debounce: Option<Task<()>>,
369 // corresponds 1 to 1 with keybindings
370 string_match_candidates: Arc<Vec<StringMatchCandidate>>,
371 matches: Vec<StringMatch>,
372 table_interaction_state: Entity<TableInteractionState>,
373 filter_editor: Entity<Editor>,
374 keystroke_editor: Entity<KeystrokeInput>,
375 selected_index: Option<usize>,
376 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
377 previous_edit: Option<PreviousEdit>,
378 humanized_action_names: HumanizedActionNameCache,
379 current_widths: Entity<ColumnWidths<6>>,
380 show_hover_menus: bool,
381 /// In order for the JSON LSP to run in the actions arguments editor, we
382 /// require a backing file In order to avoid issues (primarily log spam)
383 /// with drop order between the buffer, file, worktree, etc, we create a
384 /// temporary directory for these backing files in the keymap editor struct
385 /// instead of here. This has the added benefit of only having to create a
386 /// worktree and directory once, although the perf improvement is negligible.
387 action_args_temp_dir_worktree: Option<Entity<project::Worktree>>,
388 action_args_temp_dir: Option<tempfile::TempDir>,
389}
390
391enum PreviousEdit {
392 /// When deleting, we want to maintain the same scroll position
393 ScrollBarOffset(Point<Pixels>),
394 /// When editing or creating, because the new keybinding could be in a different position in the sort order
395 /// we store metadata about the new binding (either the modified version or newly created one)
396 /// and upon reload, we search for this binding in the list of keybindings, and if we find the one that matches
397 /// this metadata, we set the selected index to it and scroll to it,
398 /// and if we don't find it, we scroll to 0 and don't set a selected index
399 Keybinding {
400 action_mapping: ActionMapping,
401 action_name: &'static str,
402 /// The scrollbar position to fallback to if we don't find the keybinding during a refresh
403 /// this can happen if there's a filter applied to the search and the keybinding modification
404 /// filters the binding from the search results
405 fallback: Point<Pixels>,
406 },
407}
408
409impl EventEmitter<()> for KeymapEditor {}
410
411impl Focusable for KeymapEditor {
412 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
413 if self.selected_index.is_some() {
414 self.focus_handle.clone()
415 } else {
416 self.filter_editor.focus_handle(cx)
417 }
418 }
419}
420/// Helper function to check if two keystroke sequences match exactly
421fn keystrokes_match_exactly(
422 keystrokes1: &[KeybindingKeystroke],
423 keystrokes2: &[KeybindingKeystroke],
424) -> bool {
425 keystrokes1.len() == keystrokes2.len()
426 && keystrokes1.iter().zip(keystrokes2).all(|(k1, k2)| {
427 k1.inner().key == k2.inner().key && k1.inner().modifiers == k2.inner().modifiers
428 })
429}
430
431impl KeymapEditor {
432 fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
433 let _keymap_subscription =
434 cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed);
435 let table_interaction_state = TableInteractionState::new(window, cx);
436
437 let keystroke_editor = cx.new(|cx| {
438 let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
439 keystroke_editor.set_search(true);
440 keystroke_editor
441 });
442
443 let filter_editor = cx.new(|cx| {
444 let mut editor = Editor::single_line(window, cx);
445 editor.set_placeholder_text("Filter action names…", cx);
446 editor
447 });
448
449 cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
450 if !matches!(e, EditorEvent::BufferEdited) {
451 return;
452 }
453
454 this.on_query_changed(cx);
455 })
456 .detach();
457
458 cx.subscribe(&keystroke_editor, |this, _, _, cx| {
459 if matches!(this.search_mode, SearchMode::Normal) {
460 return;
461 }
462
463 this.on_query_changed(cx);
464 })
465 .detach();
466
467 cx.spawn({
468 let workspace = workspace.clone();
469 async move |this, cx| {
470 let temp_dir = tempfile::tempdir_in(paths::temp_dir())?;
471 let worktree = workspace
472 .update(cx, |ws, cx| {
473 ws.project()
474 .update(cx, |p, cx| p.create_worktree(temp_dir.path(), false, cx))
475 })?
476 .await?;
477 this.update(cx, |this, _| {
478 this.action_args_temp_dir = Some(temp_dir);
479 this.action_args_temp_dir_worktree = Some(worktree);
480 })
481 }
482 })
483 .detach();
484
485 let mut this = Self {
486 workspace,
487 keybindings: vec![],
488 keybinding_conflict_state: ConflictState::default(),
489 filter_state: FilterState::default(),
490 search_mode: SearchMode::default(),
491 string_match_candidates: Arc::new(vec![]),
492 matches: vec![],
493 focus_handle: cx.focus_handle(),
494 _keymap_subscription,
495 table_interaction_state,
496 filter_editor,
497 keystroke_editor,
498 selected_index: None,
499 context_menu: None,
500 previous_edit: None,
501 search_query_debounce: None,
502 humanized_action_names: HumanizedActionNameCache::new(cx),
503 show_hover_menus: true,
504 action_args_temp_dir: None,
505 action_args_temp_dir_worktree: None,
506 current_widths: cx.new(|cx| ColumnWidths::new(cx)),
507 };
508
509 this.on_keymap_changed(window, cx);
510
511 this
512 }
513
514 fn current_action_query(&self, cx: &App) -> String {
515 self.filter_editor.read(cx).text(cx)
516 }
517
518 fn current_keystroke_query(&self, cx: &App) -> Vec<KeybindingKeystroke> {
519 match self.search_mode {
520 SearchMode::KeyStroke { .. } => self.keystroke_editor.read(cx).keystrokes().to_vec(),
521 SearchMode::Normal => Default::default(),
522 }
523 }
524
525 fn on_query_changed(&mut self, cx: &mut Context<Self>) {
526 let action_query = self.current_action_query(cx);
527 let keystroke_query = self.current_keystroke_query(cx);
528 let exact_match = self.search_mode.exact_match();
529
530 let timer = cx.background_executor().timer(Duration::from_secs(1));
531 self.search_query_debounce = Some(cx.background_spawn({
532 let action_query = action_query.clone();
533 let keystroke_query = keystroke_query.clone();
534 async move {
535 timer.await;
536
537 let keystroke_query = keystroke_query
538 .into_iter()
539 .map(|keystroke| keystroke.inner().unparse())
540 .collect::<Vec<String>>()
541 .join(" ");
542
543 telemetry::event!(
544 "Keystroke Search Completed",
545 action_query = action_query,
546 keystroke_query = keystroke_query,
547 keystroke_exact_match = exact_match
548 )
549 }
550 }));
551 cx.spawn(async move |this, cx| {
552 Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
553 this.update(cx, |this, cx| {
554 this.scroll_to_item(0, ScrollStrategy::Top, cx)
555 })
556 })
557 .detach();
558 }
559
560 async fn update_matches(
561 this: WeakEntity<Self>,
562 action_query: String,
563 keystroke_query: Vec<KeybindingKeystroke>,
564 cx: &mut AsyncApp,
565 ) -> anyhow::Result<()> {
566 let action_query = command_palette::normalize_action_query(&action_query);
567 let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
568 (this.string_match_candidates.clone(), this.keybindings.len())
569 })?;
570 let executor = cx.background_executor().clone();
571 let mut matches = fuzzy::match_strings(
572 &string_match_candidates,
573 &action_query,
574 true,
575 true,
576 keybind_count,
577 &Default::default(),
578 executor,
579 )
580 .await;
581 this.update(cx, |this, cx| {
582 match this.filter_state {
583 FilterState::Conflicts => {
584 matches.retain(|candidate| {
585 this.keybinding_conflict_state
586 .has_user_conflict(candidate.candidate_id)
587 });
588 }
589 FilterState::All => {}
590 }
591
592 match this.search_mode {
593 SearchMode::KeyStroke { exact_match } => {
594 matches.retain(|item| {
595 this.keybindings[item.candidate_id]
596 .keystrokes()
597 .is_some_and(|keystrokes| {
598 if exact_match {
599 keystrokes_match_exactly(&keystroke_query, keystrokes)
600 } else if keystroke_query.len() > keystrokes.len() {
601 false
602 } else {
603 for keystroke_offset in 0..keystrokes.len() {
604 let mut found_count = 0;
605 let mut query_cursor = 0;
606 let mut keystroke_cursor = keystroke_offset;
607 while query_cursor < keystroke_query.len()
608 && keystroke_cursor < keystrokes.len()
609 {
610 let query = &keystroke_query[query_cursor];
611 let keystroke = &keystrokes[keystroke_cursor];
612 let matches = query
613 .inner()
614 .modifiers
615 .is_subset_of(&keystroke.inner().modifiers)
616 && ((query.inner().key.is_empty()
617 || query.inner().key == keystroke.inner().key)
618 && query.inner().key_char.as_ref().is_none_or(
619 |q_kc| q_kc == &keystroke.inner().key,
620 ));
621 if matches {
622 found_count += 1;
623 query_cursor += 1;
624 }
625 keystroke_cursor += 1;
626 }
627
628 if found_count == keystroke_query.len() {
629 return true;
630 }
631 }
632 false
633 }
634 })
635 });
636 }
637 SearchMode::Normal => {}
638 }
639
640 if action_query.is_empty() {
641 matches.sort_by(|item1, item2| {
642 let binding1 = &this.keybindings[item1.candidate_id];
643 let binding2 = &this.keybindings[item2.candidate_id];
644
645 binding1.cmp(binding2)
646 });
647 }
648 this.selected_index.take();
649 this.matches = matches;
650
651 cx.notify();
652 })
653 }
654
655 fn get_conflict(&self, row_index: usize) -> Option<ConflictOrigin> {
656 self.matches.get(row_index).and_then(|candidate| {
657 self.keybinding_conflict_state
658 .conflict_for_idx(candidate.candidate_id)
659 })
660 }
661
662 fn process_bindings(
663 json_language: Arc<Language>,
664 zed_keybind_context_language: Arc<Language>,
665 humanized_action_names: &HumanizedActionNameCache,
666 cx: &mut App,
667 ) -> (Vec<ProcessedBinding>, Vec<StringMatchCandidate>) {
668 let key_bindings_ptr = cx.key_bindings();
669 let lock = key_bindings_ptr.borrow();
670 let key_bindings = lock.bindings();
671 let mut unmapped_action_names = HashSet::from_iter(cx.all_action_names().iter().copied());
672 let action_documentation = cx.action_documentation();
673 let mut generator = KeymapFile::action_schema_generator();
674 let actions_with_schemas = HashSet::from_iter(
675 cx.action_schemas(&mut generator)
676 .into_iter()
677 .filter_map(|(name, schema)| schema.is_some().then_some(name)),
678 );
679
680 let mut processed_bindings = Vec::new();
681 let mut string_match_candidates = Vec::new();
682
683 for key_binding in key_bindings {
684 let source = key_binding
685 .meta()
686 .map(KeybindSource::from_meta)
687 .unwrap_or(KeybindSource::Unknown);
688
689 let keystroke_text = ui::text_for_keybinding_keystrokes(key_binding.keystrokes(), cx);
690 let ui_key_binding = ui::KeyBinding::new_from_gpui(key_binding.clone(), cx)
691 .vim_mode(source == KeybindSource::Vim);
692
693 let context = key_binding
694 .predicate()
695 .map(|predicate| {
696 KeybindContextString::Local(
697 predicate.to_string().into(),
698 zed_keybind_context_language.clone(),
699 )
700 })
701 .unwrap_or(KeybindContextString::Global);
702
703 let action_name = key_binding.action().name();
704 unmapped_action_names.remove(&action_name);
705
706 let action_arguments = key_binding
707 .action_input()
708 .map(|arguments| SyntaxHighlightedText::new(arguments, json_language.clone()));
709 let action_information = ActionInformation::new(
710 action_name,
711 action_arguments,
712 &actions_with_schemas,
713 action_documentation,
714 humanized_action_names,
715 );
716
717 let index = processed_bindings.len();
718 let string_match_candidate =
719 StringMatchCandidate::new(index, &action_information.humanized_name);
720 processed_bindings.push(ProcessedBinding::new_mapped(
721 keystroke_text,
722 ui_key_binding,
723 context,
724 source,
725 action_information,
726 ));
727 string_match_candidates.push(string_match_candidate);
728 }
729
730 for action_name in unmapped_action_names.into_iter() {
731 let index = processed_bindings.len();
732 let action_information = ActionInformation::new(
733 action_name,
734 None,
735 &actions_with_schemas,
736 action_documentation,
737 humanized_action_names,
738 );
739 let string_match_candidate =
740 StringMatchCandidate::new(index, &action_information.humanized_name);
741
742 processed_bindings.push(ProcessedBinding::Unmapped(action_information));
743 string_match_candidates.push(string_match_candidate);
744 }
745
746 (processed_bindings, string_match_candidates)
747 }
748
749 fn on_keymap_changed(&mut self, window: &mut Window, cx: &mut Context<KeymapEditor>) {
750 let workspace = self.workspace.clone();
751 cx.spawn_in(window, async move |this, cx| {
752 let json_language = load_json_language(workspace.clone(), cx).await;
753 let zed_keybind_context_language =
754 load_keybind_context_language(workspace.clone(), cx).await;
755
756 let (action_query, keystroke_query) = this.update(cx, |this, cx| {
757 let (key_bindings, string_match_candidates) = Self::process_bindings(
758 json_language,
759 zed_keybind_context_language,
760 &this.humanized_action_names,
761 cx,
762 );
763
764 this.keybinding_conflict_state = ConflictState::new(&key_bindings);
765
766 this.keybindings = key_bindings;
767 this.string_match_candidates = Arc::new(string_match_candidates);
768 this.matches = this
769 .string_match_candidates
770 .iter()
771 .enumerate()
772 .map(|(ix, candidate)| StringMatch {
773 candidate_id: ix,
774 score: 0.0,
775 positions: vec![],
776 string: candidate.string.clone(),
777 })
778 .collect();
779 (
780 this.current_action_query(cx),
781 this.current_keystroke_query(cx),
782 )
783 })?;
784 // calls cx.notify
785 Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
786 this.update_in(cx, |this, window, cx| {
787 if let Some(previous_edit) = this.previous_edit.take() {
788 match previous_edit {
789 // should remove scroll from process_query
790 PreviousEdit::ScrollBarOffset(offset) => {
791 this.table_interaction_state.update(cx, |table, _| {
792 table.set_scrollbar_offset(Axis::Vertical, offset)
793 })
794 // set selected index and scroll
795 }
796 PreviousEdit::Keybinding {
797 action_mapping,
798 action_name,
799 fallback,
800 } => {
801 let scroll_position =
802 this.matches.iter().enumerate().find_map(|(index, item)| {
803 let binding = &this.keybindings[item.candidate_id];
804 if binding.get_action_mapping().is_some_and(|binding_mapping| {
805 binding_mapping == action_mapping
806 }) && binding.action().name == action_name
807 {
808 Some(index)
809 } else {
810 None
811 }
812 });
813
814 if let Some(scroll_position) = scroll_position {
815 this.select_index(
816 scroll_position,
817 Some(ScrollStrategy::Top),
818 window,
819 cx,
820 );
821 } else {
822 this.table_interaction_state.update(cx, |table, _| {
823 table.set_scrollbar_offset(Axis::Vertical, fallback)
824 });
825 }
826 cx.notify();
827 }
828 }
829 }
830 })
831 })
832 .detach_and_log_err(cx);
833 }
834
835 fn key_context(&self) -> KeyContext {
836 let mut dispatch_context = KeyContext::new_with_defaults();
837 dispatch_context.add("KeymapEditor");
838 dispatch_context.add("menu");
839
840 dispatch_context
841 }
842
843 fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
844 let index = usize::min(index, self.matches.len().saturating_sub(1));
845 self.table_interaction_state.update(cx, |this, _cx| {
846 this.scroll_handle.scroll_to_item(index, strategy);
847 });
848 }
849
850 fn focus_search(
851 &mut self,
852 _: &search::FocusSearch,
853 window: &mut Window,
854 cx: &mut Context<Self>,
855 ) {
856 if !self
857 .filter_editor
858 .focus_handle(cx)
859 .contains_focused(window, cx)
860 {
861 window.focus(&self.filter_editor.focus_handle(cx));
862 } else {
863 self.filter_editor.update(cx, |editor, cx| {
864 editor.select_all(&Default::default(), window, cx);
865 });
866 }
867 self.selected_index.take();
868 }
869
870 fn selected_keybind_index(&self) -> Option<usize> {
871 self.selected_index
872 .and_then(|match_index| self.matches.get(match_index))
873 .map(|r#match| r#match.candidate_id)
874 }
875
876 fn selected_keybind_and_index(&self) -> Option<(&ProcessedBinding, usize)> {
877 self.selected_keybind_index()
878 .map(|keybind_index| (&self.keybindings[keybind_index], keybind_index))
879 }
880
881 fn selected_binding(&self) -> Option<&ProcessedBinding> {
882 self.selected_keybind_index()
883 .and_then(|keybind_index| self.keybindings.get(keybind_index))
884 }
885
886 fn select_index(
887 &mut self,
888 index: usize,
889 scroll: Option<ScrollStrategy>,
890 window: &mut Window,
891 cx: &mut Context<Self>,
892 ) {
893 if self.selected_index != Some(index) {
894 self.selected_index = Some(index);
895 if let Some(scroll_strategy) = scroll {
896 self.scroll_to_item(index, scroll_strategy, cx);
897 }
898 window.focus(&self.focus_handle);
899 cx.notify();
900 }
901 }
902
903 fn create_context_menu(
904 &mut self,
905 position: Point<Pixels>,
906 window: &mut Window,
907 cx: &mut Context<Self>,
908 ) {
909 self.context_menu = self.selected_binding().map(|selected_binding| {
910 let selected_binding_has_no_context = selected_binding
911 .context()
912 .and_then(KeybindContextString::local)
913 .is_none();
914
915 let selected_binding_is_unbound = selected_binding.is_unbound();
916
917 let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
918 menu.context(self.focus_handle.clone())
919 .action_disabled_when(
920 selected_binding_is_unbound,
921 "Edit",
922 Box::new(EditBinding),
923 )
924 .action("Create", Box::new(CreateBinding))
925 .action_disabled_when(
926 selected_binding_is_unbound,
927 "Delete",
928 Box::new(DeleteBinding),
929 )
930 .separator()
931 .action("Copy Action", Box::new(CopyAction))
932 .action_disabled_when(
933 selected_binding_has_no_context,
934 "Copy Context",
935 Box::new(CopyContext),
936 )
937 .separator()
938 .action_disabled_when(
939 selected_binding_has_no_context,
940 "Show Matching Keybindings",
941 Box::new(ShowMatchingKeybinds),
942 )
943 });
944
945 let context_menu_handle = context_menu.focus_handle(cx);
946 window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
947 let subscription = cx.subscribe_in(
948 &context_menu,
949 window,
950 |this, _, _: &DismissEvent, window, cx| {
951 this.dismiss_context_menu(window, cx);
952 },
953 );
954 (context_menu, position, subscription)
955 });
956
957 cx.notify();
958 }
959
960 fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
961 self.context_menu.take();
962 window.focus(&self.focus_handle);
963 cx.notify();
964 }
965
966 fn context_menu_deployed(&self) -> bool {
967 self.context_menu.is_some()
968 }
969
970 fn create_row_button(
971 &self,
972 index: usize,
973 conflict: Option<ConflictOrigin>,
974 cx: &mut Context<Self>,
975 ) -> IconButton {
976 if self.filter_state != FilterState::Conflicts
977 && let Some(conflict) = conflict
978 {
979 if conflict.is_user_keybind_conflict() {
980 base_button_style(index, IconName::Warning)
981 .icon_color(Color::Warning)
982 .tooltip(|window, cx| {
983 Tooltip::with_meta(
984 "View conflicts",
985 Some(&ToggleConflictFilter),
986 "Use alt+click to show all conflicts",
987 window,
988 cx,
989 )
990 })
991 .on_click(cx.listener(move |this, click: &ClickEvent, window, cx| {
992 if click.modifiers().alt {
993 this.set_filter_state(FilterState::Conflicts, cx);
994 } else {
995 this.select_index(index, None, window, cx);
996 this.open_edit_keybinding_modal(false, window, cx);
997 cx.stop_propagation();
998 }
999 }))
1000 } else if self.search_mode.exact_match() {
1001 base_button_style(index, IconName::Info)
1002 .tooltip(|window, cx| {
1003 Tooltip::with_meta(
1004 "Edit this binding",
1005 Some(&ShowMatchingKeybinds),
1006 "This binding is overridden by other bindings.",
1007 window,
1008 cx,
1009 )
1010 })
1011 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
1012 this.select_index(index, None, window, cx);
1013 this.open_edit_keybinding_modal(false, window, cx);
1014 cx.stop_propagation();
1015 }))
1016 } else {
1017 base_button_style(index, IconName::Info)
1018 .tooltip(|window, cx| {
1019 Tooltip::with_meta(
1020 "Show matching keybinds",
1021 Some(&ShowMatchingKeybinds),
1022 "This binding is overridden by other bindings.\nUse alt+click to edit this binding",
1023 window,
1024 cx,
1025 )
1026 })
1027 .on_click(cx.listener(move |this, click: &ClickEvent, window, cx| {
1028 if click.modifiers().alt {
1029 this.select_index(index, None, window, cx);
1030 this.open_edit_keybinding_modal(false, window, cx);
1031 cx.stop_propagation();
1032 } else {
1033 this.show_matching_keystrokes(&Default::default(), window, cx);
1034 }
1035 }))
1036 }
1037 } else {
1038 base_button_style(index, IconName::Pencil)
1039 .visible_on_hover(if self.selected_index == Some(index) {
1040 "".into()
1041 } else if self.show_hover_menus {
1042 row_group_id(index)
1043 } else {
1044 "never-show".into()
1045 })
1046 .when(
1047 self.show_hover_menus && !self.context_menu_deployed(),
1048 |this| this.tooltip(Tooltip::for_action_title("Edit Keybinding", &EditBinding)),
1049 )
1050 .on_click(cx.listener(move |this, _, window, cx| {
1051 this.select_index(index, None, window, cx);
1052 this.open_edit_keybinding_modal(false, window, cx);
1053 cx.stop_propagation();
1054 }))
1055 }
1056 }
1057
1058 fn render_no_matches_hint(&self, _window: &mut Window, _cx: &App) -> AnyElement {
1059 let hint = match (self.filter_state, &self.search_mode) {
1060 (FilterState::Conflicts, _) => {
1061 if self.keybinding_conflict_state.any_user_binding_conflicts() {
1062 "No conflicting keybinds found that match the provided query"
1063 } else {
1064 "No conflicting keybinds found"
1065 }
1066 }
1067 (FilterState::All, SearchMode::KeyStroke { .. }) => {
1068 "No keybinds found matching the entered keystrokes"
1069 }
1070 (FilterState::All, SearchMode::Normal) => "No matches found for the provided query",
1071 };
1072
1073 Label::new(hint).color(Color::Muted).into_any_element()
1074 }
1075
1076 fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1077 self.show_hover_menus = false;
1078 if let Some(selected) = self.selected_index {
1079 let selected = selected + 1;
1080 if selected >= self.matches.len() {
1081 self.select_last(&Default::default(), window, cx);
1082 } else {
1083 self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
1084 }
1085 } else {
1086 self.select_first(&Default::default(), window, cx);
1087 }
1088 }
1089
1090 fn select_previous(
1091 &mut self,
1092 _: &menu::SelectPrevious,
1093 window: &mut Window,
1094 cx: &mut Context<Self>,
1095 ) {
1096 self.show_hover_menus = false;
1097 if let Some(selected) = self.selected_index {
1098 if selected == 0 {
1099 return;
1100 }
1101
1102 let selected = selected - 1;
1103
1104 if selected >= self.matches.len() {
1105 self.select_last(&Default::default(), window, cx);
1106 } else {
1107 self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
1108 }
1109 } else {
1110 self.select_last(&Default::default(), window, cx);
1111 }
1112 }
1113
1114 fn select_first(&mut self, _: &menu::SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
1115 self.show_hover_menus = false;
1116 if self.matches.get(0).is_some() {
1117 self.select_index(0, Some(ScrollStrategy::Center), window, cx);
1118 }
1119 }
1120
1121 fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
1122 self.show_hover_menus = false;
1123 if self.matches.last().is_some() {
1124 let index = self.matches.len() - 1;
1125 self.select_index(index, Some(ScrollStrategy::Center), window, cx);
1126 }
1127 }
1128
1129 fn open_edit_keybinding_modal(
1130 &mut self,
1131 create: bool,
1132 window: &mut Window,
1133 cx: &mut Context<Self>,
1134 ) {
1135 self.show_hover_menus = false;
1136 let Some((keybind, keybind_index)) = self.selected_keybind_and_index() else {
1137 return;
1138 };
1139 let keybind = keybind.clone();
1140 let keymap_editor = cx.entity();
1141
1142 let keystroke = keybind.keystroke_text().cloned().unwrap_or_default();
1143 let arguments = keybind
1144 .action()
1145 .arguments
1146 .as_ref()
1147 .map(|arguments| arguments.text.clone());
1148 let context = keybind
1149 .context()
1150 .map(|context| context.local_str().unwrap_or("global"));
1151 let action = keybind.action().name;
1152 let source = keybind.keybind_source().map(|source| source.name());
1153
1154 telemetry::event!(
1155 "Edit Keybinding Modal Opened",
1156 keystroke = keystroke,
1157 action = action,
1158 source = source,
1159 context = context,
1160 arguments = arguments,
1161 );
1162
1163 let temp_dir = self.action_args_temp_dir.as_ref().map(|dir| dir.path());
1164
1165 self.workspace
1166 .update(cx, |workspace, cx| {
1167 let fs = workspace.app_state().fs.clone();
1168 let workspace_weak = cx.weak_entity();
1169 workspace.toggle_modal(window, cx, |window, cx| {
1170 let modal = KeybindingEditorModal::new(
1171 create,
1172 keybind,
1173 keybind_index,
1174 keymap_editor,
1175 temp_dir,
1176 workspace_weak,
1177 fs,
1178 window,
1179 cx,
1180 );
1181 window.focus(&modal.focus_handle(cx));
1182 modal
1183 });
1184 })
1185 .log_err();
1186 }
1187
1188 fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
1189 self.open_edit_keybinding_modal(false, window, cx);
1190 }
1191
1192 fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
1193 self.open_edit_keybinding_modal(true, window, cx);
1194 }
1195
1196 fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
1197 let Some(to_remove) = self.selected_binding().cloned() else {
1198 return;
1199 };
1200
1201 let std::result::Result::Ok(fs) = self
1202 .workspace
1203 .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
1204 else {
1205 return;
1206 };
1207 let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
1208 self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
1209 self.table_interaction_state
1210 .read(cx)
1211 .get_scrollbar_offset(Axis::Vertical),
1212 ));
1213 let keyboard_mapper = cx.keyboard_mapper().clone();
1214 cx.spawn(async move |_, _| {
1215 remove_keybinding(to_remove, &fs, tab_size, keyboard_mapper.as_ref()).await
1216 })
1217 .detach_and_notify_err(window, cx);
1218 }
1219
1220 fn copy_context_to_clipboard(
1221 &mut self,
1222 _: &CopyContext,
1223 _window: &mut Window,
1224 cx: &mut Context<Self>,
1225 ) {
1226 let context = self
1227 .selected_binding()
1228 .and_then(|binding| binding.context())
1229 .and_then(KeybindContextString::local_str)
1230 .map(|context| context.to_string());
1231 let Some(context) = context else {
1232 return;
1233 };
1234
1235 telemetry::event!("Keybinding Context Copied", context = context);
1236 cx.write_to_clipboard(gpui::ClipboardItem::new_string(context));
1237 }
1238
1239 fn copy_action_to_clipboard(
1240 &mut self,
1241 _: &CopyAction,
1242 _window: &mut Window,
1243 cx: &mut Context<Self>,
1244 ) {
1245 let action = self
1246 .selected_binding()
1247 .map(|binding| binding.action().name.to_string());
1248 let Some(action) = action else {
1249 return;
1250 };
1251
1252 telemetry::event!("Keybinding Action Copied", action = action);
1253 cx.write_to_clipboard(gpui::ClipboardItem::new_string(action));
1254 }
1255
1256 fn toggle_conflict_filter(
1257 &mut self,
1258 _: &ToggleConflictFilter,
1259 _: &mut Window,
1260 cx: &mut Context<Self>,
1261 ) {
1262 self.set_filter_state(self.filter_state.invert(), cx);
1263 }
1264
1265 fn set_filter_state(&mut self, filter_state: FilterState, cx: &mut Context<Self>) {
1266 if self.filter_state != filter_state {
1267 self.filter_state = filter_state;
1268 self.on_query_changed(cx);
1269 }
1270 }
1271
1272 fn toggle_keystroke_search(
1273 &mut self,
1274 _: &ToggleKeystrokeSearch,
1275 window: &mut Window,
1276 cx: &mut Context<Self>,
1277 ) {
1278 self.search_mode = self.search_mode.invert();
1279 self.on_query_changed(cx);
1280
1281 match self.search_mode {
1282 SearchMode::KeyStroke { .. } => {
1283 self.keystroke_editor.update(cx, |editor, cx| {
1284 editor.start_recording(&StartRecording, window, cx);
1285 });
1286 }
1287 SearchMode::Normal => {
1288 self.keystroke_editor.update(cx, |editor, cx| {
1289 editor.stop_recording(&StopRecording, window, cx);
1290 editor.clear_keystrokes(&ClearKeystrokes, window, cx);
1291 });
1292 window.focus(&self.filter_editor.focus_handle(cx));
1293 }
1294 }
1295 }
1296
1297 fn toggle_exact_keystroke_matching(
1298 &mut self,
1299 _: &ToggleExactKeystrokeMatching,
1300 _: &mut Window,
1301 cx: &mut Context<Self>,
1302 ) {
1303 let SearchMode::KeyStroke { exact_match } = &mut self.search_mode else {
1304 return;
1305 };
1306
1307 *exact_match = !(*exact_match);
1308 self.on_query_changed(cx);
1309 }
1310
1311 fn show_matching_keystrokes(
1312 &mut self,
1313 _: &ShowMatchingKeybinds,
1314 _: &mut Window,
1315 cx: &mut Context<Self>,
1316 ) {
1317 let Some(selected_binding) = self.selected_binding() else {
1318 return;
1319 };
1320
1321 let keystrokes = selected_binding
1322 .keystrokes()
1323 .map(Vec::from)
1324 .unwrap_or_default();
1325
1326 self.filter_state = FilterState::All;
1327 self.search_mode = SearchMode::KeyStroke { exact_match: true };
1328
1329 self.keystroke_editor.update(cx, |editor, cx| {
1330 editor.set_keystrokes(keystrokes, cx);
1331 });
1332 }
1333}
1334
1335struct HumanizedActionNameCache {
1336 cache: HashMap<&'static str, SharedString>,
1337}
1338
1339impl HumanizedActionNameCache {
1340 fn new(cx: &App) -> Self {
1341 let cache = HashMap::from_iter(cx.all_action_names().iter().map(|&action_name| {
1342 (
1343 action_name,
1344 command_palette::humanize_action_name(action_name).into(),
1345 )
1346 }));
1347 Self { cache }
1348 }
1349
1350 fn get(&self, action_name: &'static str) -> SharedString {
1351 match self.cache.get(action_name) {
1352 Some(name) => name.clone(),
1353 None => action_name.into(),
1354 }
1355 }
1356}
1357
1358#[derive(Clone)]
1359struct KeybindInformation {
1360 keystroke_text: SharedString,
1361 ui_binding: ui::KeyBinding,
1362 context: KeybindContextString,
1363 source: KeybindSource,
1364}
1365
1366impl KeybindInformation {
1367 fn get_action_mapping(&self) -> ActionMapping {
1368 ActionMapping {
1369 keystrokes: self.ui_binding.keystrokes.clone(),
1370 context: self.context.local().cloned(),
1371 }
1372 }
1373}
1374
1375#[derive(Clone)]
1376struct ActionInformation {
1377 name: &'static str,
1378 humanized_name: SharedString,
1379 arguments: Option<SyntaxHighlightedText>,
1380 documentation: Option<&'static str>,
1381 has_schema: bool,
1382}
1383
1384impl ActionInformation {
1385 fn new(
1386 action_name: &'static str,
1387 action_arguments: Option<SyntaxHighlightedText>,
1388 actions_with_schemas: &HashSet<&'static str>,
1389 action_documentation: &HashMap<&'static str, &'static str>,
1390 action_name_cache: &HumanizedActionNameCache,
1391 ) -> Self {
1392 Self {
1393 humanized_name: action_name_cache.get(action_name),
1394 has_schema: actions_with_schemas.contains(action_name),
1395 arguments: action_arguments,
1396 documentation: action_documentation.get(action_name).copied(),
1397 name: action_name,
1398 }
1399 }
1400}
1401
1402#[derive(Clone)]
1403enum ProcessedBinding {
1404 Mapped(KeybindInformation, ActionInformation),
1405 Unmapped(ActionInformation),
1406}
1407
1408impl ProcessedBinding {
1409 fn new_mapped(
1410 keystroke_text: impl Into<SharedString>,
1411 ui_key_binding: ui::KeyBinding,
1412 context: KeybindContextString,
1413 source: KeybindSource,
1414 action_information: ActionInformation,
1415 ) -> Self {
1416 Self::Mapped(
1417 KeybindInformation {
1418 keystroke_text: keystroke_text.into(),
1419 ui_binding: ui_key_binding,
1420 context,
1421 source,
1422 },
1423 action_information,
1424 )
1425 }
1426
1427 fn is_unbound(&self) -> bool {
1428 matches!(self, Self::Unmapped(_))
1429 }
1430
1431 fn get_action_mapping(&self) -> Option<ActionMapping> {
1432 self.keybind_information()
1433 .map(|keybind| keybind.get_action_mapping())
1434 }
1435
1436 fn keystrokes(&self) -> Option<&[KeybindingKeystroke]> {
1437 self.ui_key_binding()
1438 .map(|binding| binding.keystrokes.as_slice())
1439 }
1440
1441 fn keybind_information(&self) -> Option<&KeybindInformation> {
1442 match self {
1443 Self::Mapped(keybind_information, _) => Some(keybind_information),
1444 Self::Unmapped(_) => None,
1445 }
1446 }
1447
1448 fn keybind_source(&self) -> Option<KeybindSource> {
1449 self.keybind_information().map(|keybind| keybind.source)
1450 }
1451
1452 fn context(&self) -> Option<&KeybindContextString> {
1453 self.keybind_information().map(|keybind| &keybind.context)
1454 }
1455
1456 fn ui_key_binding(&self) -> Option<&ui::KeyBinding> {
1457 self.keybind_information()
1458 .map(|keybind| &keybind.ui_binding)
1459 }
1460
1461 fn keystroke_text(&self) -> Option<&SharedString> {
1462 self.keybind_information()
1463 .map(|binding| &binding.keystroke_text)
1464 }
1465
1466 fn action(&self) -> &ActionInformation {
1467 match self {
1468 Self::Mapped(_, action) | Self::Unmapped(action) => action,
1469 }
1470 }
1471
1472 fn cmp(&self, other: &Self) -> cmp::Ordering {
1473 match (self, other) {
1474 (Self::Mapped(keybind1, action1), Self::Mapped(keybind2, action2)) => {
1475 match keybind1.source.cmp(&keybind2.source) {
1476 cmp::Ordering::Equal => action1.humanized_name.cmp(&action2.humanized_name),
1477 ordering => ordering,
1478 }
1479 }
1480 (Self::Mapped(_, _), Self::Unmapped(_)) => cmp::Ordering::Less,
1481 (Self::Unmapped(_), Self::Mapped(_, _)) => cmp::Ordering::Greater,
1482 (Self::Unmapped(action1), Self::Unmapped(action2)) => {
1483 action1.humanized_name.cmp(&action2.humanized_name)
1484 }
1485 }
1486 }
1487}
1488
1489#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
1490enum KeybindContextString {
1491 Global,
1492 Local(SharedString, Arc<Language>),
1493}
1494
1495impl KeybindContextString {
1496 const GLOBAL: SharedString = SharedString::new_static("<global>");
1497
1498 pub fn local(&self) -> Option<&SharedString> {
1499 match self {
1500 KeybindContextString::Global => None,
1501 KeybindContextString::Local(name, _) => Some(name),
1502 }
1503 }
1504
1505 pub fn local_str(&self) -> Option<&str> {
1506 match self {
1507 KeybindContextString::Global => None,
1508 KeybindContextString::Local(name, _) => Some(name),
1509 }
1510 }
1511}
1512
1513impl RenderOnce for KeybindContextString {
1514 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1515 match self {
1516 KeybindContextString::Global => {
1517 muted_styled_text(KeybindContextString::GLOBAL, cx).into_any_element()
1518 }
1519 KeybindContextString::Local(name, language) => {
1520 SyntaxHighlightedText::new(name, language).into_any_element()
1521 }
1522 }
1523 }
1524}
1525
1526fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
1527 let len = text.len();
1528 StyledText::new(text).with_highlights([(
1529 0..len,
1530 gpui::HighlightStyle::color(cx.theme().colors().text_muted),
1531 )])
1532}
1533
1534impl Item for KeymapEditor {
1535 type Event = ();
1536
1537 fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
1538 "Keymap Editor".into()
1539 }
1540}
1541
1542impl Render for KeymapEditor {
1543 fn render(&mut self, _window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
1544 let row_count = self.matches.len();
1545 let theme = cx.theme();
1546 let focus_handle = &self.focus_handle;
1547
1548 v_flex()
1549 .id("keymap-editor")
1550 .track_focus(focus_handle)
1551 .key_context(self.key_context())
1552 .on_action(cx.listener(Self::select_next))
1553 .on_action(cx.listener(Self::select_previous))
1554 .on_action(cx.listener(Self::select_first))
1555 .on_action(cx.listener(Self::select_last))
1556 .on_action(cx.listener(Self::focus_search))
1557 .on_action(cx.listener(Self::edit_binding))
1558 .on_action(cx.listener(Self::create_binding))
1559 .on_action(cx.listener(Self::delete_binding))
1560 .on_action(cx.listener(Self::copy_action_to_clipboard))
1561 .on_action(cx.listener(Self::copy_context_to_clipboard))
1562 .on_action(cx.listener(Self::toggle_conflict_filter))
1563 .on_action(cx.listener(Self::toggle_keystroke_search))
1564 .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1565 .on_action(cx.listener(Self::show_matching_keystrokes))
1566 .on_mouse_move(cx.listener(|this, _, _window, _cx| {
1567 this.show_hover_menus = true;
1568 }))
1569 .size_full()
1570 .p_2()
1571 .gap_1()
1572 .bg(theme.colors().editor_background)
1573 .child(
1574 v_flex()
1575 .gap_2()
1576 .child(
1577 h_flex()
1578 .gap_2()
1579 .child(
1580 div()
1581 .key_context({
1582 let mut context = KeyContext::new_with_defaults();
1583 context.add("BufferSearchBar");
1584 context
1585 })
1586 .size_full()
1587 .h_8()
1588 .pl_2()
1589 .pr_1()
1590 .py_1()
1591 .border_1()
1592 .border_color(theme.colors().border)
1593 .rounded_md()
1594 .child(self.filter_editor.clone()),
1595 )
1596 .child(
1597 h_flex()
1598 .gap_1()
1599 .min_w_64()
1600 .child(
1601 IconButton::new(
1602 "KeymapEditorToggleFiltersIcon",
1603 IconName::Keyboard,
1604 )
1605 .icon_size(IconSize::Small)
1606 .tooltip({
1607 let focus_handle = focus_handle.clone();
1608
1609 move |window, cx| {
1610 Tooltip::for_action_in(
1611 "Search by Keystroke",
1612 &ToggleKeystrokeSearch,
1613 &focus_handle.clone(),
1614 window,
1615 cx,
1616 )
1617 }
1618 })
1619 .toggle_state(matches!(
1620 self.search_mode,
1621 SearchMode::KeyStroke { .. }
1622 ))
1623 .on_click(|_, window, cx| {
1624 window.dispatch_action(
1625 ToggleKeystrokeSearch.boxed_clone(),
1626 cx,
1627 );
1628 }),
1629 )
1630 .child(
1631 IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1632 .icon_size(IconSize::Small)
1633 .when(
1634 self.keybinding_conflict_state
1635 .any_user_binding_conflicts(),
1636 |this| {
1637 this.indicator(
1638 Indicator::dot().color(Color::Warning),
1639 )
1640 },
1641 )
1642 .tooltip({
1643 let filter_state = self.filter_state;
1644 let focus_handle = focus_handle.clone();
1645
1646 move |window, cx| {
1647 Tooltip::for_action_in(
1648 match filter_state {
1649 FilterState::All => "Show Conflicts",
1650 FilterState::Conflicts => {
1651 "Hide Conflicts"
1652 }
1653 },
1654 &ToggleConflictFilter,
1655 &focus_handle.clone(),
1656 window,
1657 cx,
1658 )
1659 }
1660 })
1661 .selected_icon_color(Color::Warning)
1662 .toggle_state(matches!(
1663 self.filter_state,
1664 FilterState::Conflicts
1665 ))
1666 .on_click(|_, window, cx| {
1667 window.dispatch_action(
1668 ToggleConflictFilter.boxed_clone(),
1669 cx,
1670 );
1671 }),
1672 )
1673 .child(
1674 div()
1675 .ml_1()
1676 .pl_2()
1677 .border_l_1()
1678 .border_color(cx.theme().colors().border_variant)
1679 .child(
1680 right_click_menu("open-keymap-menu")
1681 .menu(|window, cx| {
1682 ContextMenu::build(window, cx, |menu, _, _| {
1683 menu.header("Open Keymap JSON")
1684 .action(
1685 "User",
1686 zed_actions::OpenKeymap.boxed_clone(),
1687 )
1688 .action(
1689 "Zed Default",
1690 zed_actions::OpenDefaultKeymap
1691 .boxed_clone(),
1692 )
1693 .action(
1694 "Vim Default",
1695 vim::OpenDefaultKeymap.boxed_clone(),
1696 )
1697 })
1698 })
1699 .anchor(gpui::Corner::TopLeft)
1700 .trigger(|open, _, _| {
1701 IconButton::new(
1702 "OpenKeymapJsonButton",
1703 IconName::Json,
1704 )
1705 .icon_size(IconSize::Small)
1706 .when(!open, |this| {
1707 this.tooltip(move |window, cx| {
1708 Tooltip::with_meta(
1709 "Open keymap.json",
1710 Some(&zed_actions::OpenKeymap),
1711 "Right click to view more options",
1712 window,
1713 cx,
1714 )
1715 })
1716 })
1717 .on_click(|_, window, cx| {
1718 window.dispatch_action(
1719 zed_actions::OpenKeymap.boxed_clone(),
1720 cx,
1721 );
1722 })
1723 }),
1724 ),
1725 )
1726 ),
1727 )
1728 .when_some(
1729 match self.search_mode {
1730 SearchMode::Normal => None,
1731 SearchMode::KeyStroke { exact_match } => Some(exact_match),
1732 },
1733 |this, exact_match| {
1734 this.child(
1735 h_flex()
1736 .gap_2()
1737 .child(self.keystroke_editor.clone())
1738 .child(
1739 h_flex()
1740 .min_w_64()
1741 .child(
1742 IconButton::new(
1743 "keystrokes-exact-match",
1744 IconName::CaseSensitive,
1745 )
1746 .tooltip({
1747 let keystroke_focus_handle =
1748 self.keystroke_editor.read(cx).focus_handle(cx);
1749
1750 move |window, cx| {
1751 Tooltip::for_action_in(
1752 "Toggle Exact Match Mode",
1753 &ToggleExactKeystrokeMatching,
1754 &keystroke_focus_handle,
1755 window,
1756 cx,
1757 )
1758 }
1759 })
1760 .shape(IconButtonShape::Square)
1761 .toggle_state(exact_match)
1762 .on_click(
1763 cx.listener(|_, _, window, cx| {
1764 window.dispatch_action(
1765 ToggleExactKeystrokeMatching.boxed_clone(),
1766 cx,
1767 );
1768 }),
1769 ),
1770 ),
1771 )
1772 )
1773 },
1774 ),
1775 )
1776 .child(
1777 Table::new()
1778 .interactable(&self.table_interaction_state)
1779 .striped()
1780 .empty_table_callback({
1781 let this = cx.entity();
1782 move |window, cx| this.read(cx).render_no_matches_hint(window, cx)
1783 })
1784 .column_widths([
1785 DefiniteLength::Absolute(AbsoluteLength::Pixels(px(36.))),
1786 DefiniteLength::Fraction(0.25),
1787 DefiniteLength::Fraction(0.20),
1788 DefiniteLength::Fraction(0.14),
1789 DefiniteLength::Fraction(0.45),
1790 DefiniteLength::Fraction(0.08),
1791 ])
1792 .resizable_columns(
1793 [
1794 ResizeBehavior::None,
1795 ResizeBehavior::Resizable,
1796 ResizeBehavior::Resizable,
1797 ResizeBehavior::Resizable,
1798 ResizeBehavior::Resizable,
1799 ResizeBehavior::Resizable, // this column doesn't matter
1800 ],
1801 &self.current_widths,
1802 cx,
1803 )
1804 .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1805 .uniform_list(
1806 "keymap-editor-table",
1807 row_count,
1808 cx.processor(move |this, range: Range<usize>, _window, cx| {
1809 let context_menu_deployed = this.context_menu_deployed();
1810 range
1811 .filter_map(|index| {
1812 let candidate_id = this.matches.get(index)?.candidate_id;
1813 let binding = &this.keybindings[candidate_id];
1814 let action_name = binding.action().name;
1815 let conflict = this.get_conflict(index);
1816 let is_overridden = conflict.is_some_and(|conflict| {
1817 !conflict.is_user_keybind_conflict()
1818 });
1819
1820 let icon = this.create_row_button(index, conflict, cx);
1821
1822 let action = div()
1823 .id(("keymap action", index))
1824 .child({
1825 if action_name != gpui::NoAction.name() {
1826 binding
1827 .action()
1828 .humanized_name
1829 .clone()
1830 .into_any_element()
1831 } else {
1832 const NULL: SharedString =
1833 SharedString::new_static("<null>");
1834 muted_styled_text(NULL, cx)
1835 .into_any_element()
1836 }
1837 })
1838 .when(
1839 !context_menu_deployed
1840 && this.show_hover_menus
1841 && !is_overridden,
1842 |this| {
1843 this.tooltip({
1844 let action_name = binding.action().name;
1845 let action_docs =
1846 binding.action().documentation;
1847 move |_, cx| {
1848 let action_tooltip =
1849 Tooltip::new(action_name);
1850 let action_tooltip = match action_docs {
1851 Some(docs) => action_tooltip.meta(docs),
1852 None => action_tooltip,
1853 };
1854 cx.new(|_| action_tooltip).into()
1855 }
1856 })
1857 },
1858 )
1859 .into_any_element();
1860
1861 let keystrokes = binding.ui_key_binding().cloned().map_or(
1862 binding
1863 .keystroke_text()
1864 .cloned()
1865 .unwrap_or_default()
1866 .into_any_element(),
1867 IntoElement::into_any_element,
1868 );
1869
1870 let action_arguments = match binding.action().arguments.clone()
1871 {
1872 Some(arguments) => arguments.into_any_element(),
1873 None => {
1874 if binding.action().has_schema {
1875 muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1876 .into_any_element()
1877 } else {
1878 gpui::Empty.into_any_element()
1879 }
1880 }
1881 };
1882
1883 let context = binding.context().cloned().map_or(
1884 gpui::Empty.into_any_element(),
1885 |context| {
1886 let is_local = context.local().is_some();
1887
1888 div()
1889 .id(("keymap context", index))
1890 .child(context.clone())
1891 .when(
1892 is_local
1893 && !context_menu_deployed
1894 && !is_overridden
1895 && this.show_hover_menus,
1896 |this| {
1897 this.tooltip(Tooltip::element({
1898 move |_, _| {
1899 context.clone().into_any_element()
1900 }
1901 }))
1902 },
1903 )
1904 .into_any_element()
1905 },
1906 );
1907
1908 let source = binding
1909 .keybind_source()
1910 .map(|source| source.name())
1911 .unwrap_or_default()
1912 .into_any_element();
1913
1914 Some([
1915 icon.into_any_element(),
1916 action,
1917 action_arguments,
1918 keystrokes,
1919 context,
1920 source,
1921 ])
1922 })
1923 .collect()
1924 }),
1925 )
1926 .map_row(cx.processor(
1927 |this, (row_index, row): (usize, Stateful<Div>), _window, cx| {
1928 let conflict = this.get_conflict(row_index);
1929 let is_selected = this.selected_index == Some(row_index);
1930
1931 let row_id = row_group_id(row_index);
1932
1933 div()
1934 .id(("keymap-row-wrapper", row_index))
1935 .child(
1936 row.id(row_id.clone())
1937 .on_any_mouse_down(cx.listener(
1938 move |this,
1939 mouse_down_event: &gpui::MouseDownEvent,
1940 window,
1941 cx| {
1942 if mouse_down_event.button == MouseButton::Right {
1943 this.select_index(
1944 row_index, None, window, cx,
1945 );
1946 this.create_context_menu(
1947 mouse_down_event.position,
1948 window,
1949 cx,
1950 );
1951 }
1952 },
1953 ))
1954 .on_click(cx.listener(
1955 move |this, event: &ClickEvent, window, cx| {
1956 this.select_index(row_index, None, window, cx);
1957 if event.click_count() == 2 {
1958 this.open_edit_keybinding_modal(
1959 false, window, cx,
1960 );
1961 }
1962 },
1963 ))
1964 .group(row_id)
1965 .when(
1966 conflict.is_some_and(|conflict| {
1967 !conflict.is_user_keybind_conflict()
1968 }),
1969 |row| {
1970 const OVERRIDDEN_OPACITY: f32 = 0.5;
1971 row.opacity(OVERRIDDEN_OPACITY)
1972 },
1973 )
1974 .when_some(
1975 conflict.filter(|conflict| {
1976 !this.context_menu_deployed() &&
1977 !conflict.is_user_keybind_conflict()
1978 }),
1979 |row, conflict| {
1980 let overriding_binding = this.keybindings.get(conflict.index);
1981 let context = overriding_binding.and_then(|binding| {
1982 match conflict.override_source {
1983 KeybindSource::User => Some("your keymap"),
1984 KeybindSource::Vim => Some("the vim keymap"),
1985 KeybindSource::Base => Some("your base keymap"),
1986 _ => {
1987 log::error!("Unexpected override from the {} keymap", conflict.override_source.name());
1988 None
1989 }
1990 }.map(|source| format!("This keybinding is overridden by the '{}' binding from {}.", binding.action().humanized_name, source))
1991 }).unwrap_or_else(|| "This binding is overridden.".to_string());
1992
1993 row.tooltip(Tooltip::text(context))},
1994 ),
1995 )
1996 .border_2()
1997 .when(
1998 conflict.is_some_and(|conflict| {
1999 conflict.is_user_keybind_conflict()
2000 }),
2001 |row| row.bg(cx.theme().status().error_background),
2002 )
2003 .when(is_selected, |row| {
2004 row.border_color(cx.theme().colors().panel_focused_border)
2005 })
2006 .into_any_element()
2007 }),
2008 ),
2009 )
2010 .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
2011 // This ensures that the menu is not dismissed in cases where scroll events
2012 // with a delta of zero are emitted
2013 if !event.delta.pixel_delta(px(1.)).y.is_zero() {
2014 this.context_menu.take();
2015 cx.notify();
2016 }
2017 }))
2018 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2019 deferred(
2020 anchored()
2021 .position(*position)
2022 .anchor(gpui::Corner::TopLeft)
2023 .child(menu.clone()),
2024 )
2025 .with_priority(1)
2026 }))
2027 }
2028}
2029
2030fn row_group_id(row_index: usize) -> SharedString {
2031 SharedString::new(format!("keymap-table-row-{}", row_index))
2032}
2033
2034fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
2035 IconButton::new(("keymap-icon", row_index), icon)
2036 .shape(IconButtonShape::Square)
2037 .size(ButtonSize::Compact)
2038}
2039
2040#[derive(Debug, Clone, IntoElement)]
2041struct SyntaxHighlightedText {
2042 text: SharedString,
2043 language: Arc<Language>,
2044}
2045
2046impl SyntaxHighlightedText {
2047 pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
2048 Self {
2049 text: text.into(),
2050 language,
2051 }
2052 }
2053}
2054
2055impl RenderOnce for SyntaxHighlightedText {
2056 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
2057 let text_style = window.text_style();
2058 let syntax_theme = cx.theme().syntax();
2059
2060 let text = self.text.clone();
2061
2062 let highlights = self
2063 .language
2064 .highlight_text(&text.as_ref().into(), 0..text.len());
2065 let mut runs = Vec::with_capacity(highlights.len());
2066 let mut offset = 0;
2067
2068 for (highlight_range, highlight_id) in highlights {
2069 // Add un-highlighted text before the current highlight
2070 if highlight_range.start > offset {
2071 runs.push(text_style.to_run(highlight_range.start - offset));
2072 }
2073
2074 let mut run_style = text_style.clone();
2075 if let Some(highlight_style) = highlight_id.style(syntax_theme) {
2076 run_style = run_style.highlight(highlight_style);
2077 }
2078 // add the highlighted range
2079 runs.push(run_style.to_run(highlight_range.len()));
2080 offset = highlight_range.end;
2081 }
2082
2083 // Add any remaining un-highlighted text
2084 if offset < text.len() {
2085 runs.push(text_style.to_run(text.len() - offset));
2086 }
2087
2088 StyledText::new(text).with_runs(runs)
2089 }
2090}
2091
2092#[derive(PartialEq)]
2093struct InputError {
2094 severity: Severity,
2095 content: SharedString,
2096}
2097
2098impl InputError {
2099 fn warning(message: impl Into<SharedString>) -> Self {
2100 Self {
2101 severity: Severity::Warning,
2102 content: message.into(),
2103 }
2104 }
2105
2106 fn error(message: anyhow::Error) -> Self {
2107 Self {
2108 severity: Severity::Error,
2109 content: message.to_string().into(),
2110 }
2111 }
2112}
2113
2114struct KeybindingEditorModal {
2115 creating: bool,
2116 editing_keybind: ProcessedBinding,
2117 editing_keybind_idx: usize,
2118 keybind_editor: Entity<KeystrokeInput>,
2119 context_editor: Entity<SingleLineInput>,
2120 action_arguments_editor: Option<Entity<ActionArgumentsEditor>>,
2121 fs: Arc<dyn Fs>,
2122 error: Option<InputError>,
2123 keymap_editor: Entity<KeymapEditor>,
2124 workspace: WeakEntity<Workspace>,
2125 focus_state: KeybindingEditorModalFocusState,
2126}
2127
2128impl ModalView for KeybindingEditorModal {}
2129
2130impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
2131
2132impl Focusable for KeybindingEditorModal {
2133 fn focus_handle(&self, cx: &App) -> FocusHandle {
2134 self.keybind_editor.focus_handle(cx)
2135 }
2136}
2137
2138impl KeybindingEditorModal {
2139 pub fn new(
2140 create: bool,
2141 editing_keybind: ProcessedBinding,
2142 editing_keybind_idx: usize,
2143 keymap_editor: Entity<KeymapEditor>,
2144 action_args_temp_dir: Option<&std::path::Path>,
2145 workspace: WeakEntity<Workspace>,
2146 fs: Arc<dyn Fs>,
2147 window: &mut Window,
2148 cx: &mut App,
2149 ) -> Self {
2150 let keybind_editor = cx
2151 .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
2152
2153 let context_editor: Entity<SingleLineInput> = cx.new(|cx| {
2154 let input = SingleLineInput::new(window, cx, "Keybinding Context")
2155 .label("Edit Context")
2156 .label_size(LabelSize::Default);
2157
2158 if let Some(context) = editing_keybind
2159 .context()
2160 .and_then(KeybindContextString::local)
2161 {
2162 input.editor().update(cx, |editor, cx| {
2163 editor.set_text(context.clone(), window, cx);
2164 });
2165 }
2166
2167 let editor_entity = input.editor().clone();
2168 let workspace = workspace.clone();
2169 cx.spawn(async move |_input_handle, cx| {
2170 let contexts = cx
2171 .background_spawn(async { collect_contexts_from_assets() })
2172 .await;
2173
2174 let language = load_keybind_context_language(workspace, cx).await;
2175 editor_entity
2176 .update(cx, |editor, cx| {
2177 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2178 buffer.update(cx, |buffer, cx| {
2179 buffer.set_language(Some(language), cx);
2180 });
2181 }
2182 editor.set_completion_provider(Some(std::rc::Rc::new(
2183 KeyContextCompletionProvider { contexts },
2184 )));
2185 })
2186 .context("Failed to load completions for keybinding context")
2187 })
2188 .detach_and_log_err(cx);
2189
2190 input
2191 });
2192
2193 let action_arguments_editor = editing_keybind.action().has_schema.then(|| {
2194 let arguments = editing_keybind
2195 .action()
2196 .arguments
2197 .as_ref()
2198 .map(|args| args.text.clone());
2199 cx.new(|cx| {
2200 ActionArgumentsEditor::new(
2201 editing_keybind.action().name,
2202 arguments,
2203 action_args_temp_dir,
2204 workspace.clone(),
2205 window,
2206 cx,
2207 )
2208 })
2209 });
2210
2211 let focus_state = KeybindingEditorModalFocusState::new(
2212 keybind_editor.focus_handle(cx),
2213 action_arguments_editor
2214 .as_ref()
2215 .map(|args_editor| args_editor.focus_handle(cx)),
2216 context_editor.focus_handle(cx),
2217 );
2218
2219 Self {
2220 creating: create,
2221 editing_keybind,
2222 editing_keybind_idx,
2223 fs,
2224 keybind_editor,
2225 context_editor,
2226 action_arguments_editor,
2227 error: None,
2228 keymap_editor,
2229 workspace,
2230 focus_state,
2231 }
2232 }
2233
2234 fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
2235 if self
2236 .error
2237 .as_ref()
2238 .is_some_and(|old_error| old_error.severity == Severity::Warning && *old_error == error)
2239 {
2240 false
2241 } else {
2242 self.error = Some(error);
2243 cx.notify();
2244 true
2245 }
2246 }
2247
2248 fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
2249 let action_arguments = self
2250 .action_arguments_editor
2251 .as_ref()
2252 .map(|arguments_editor| arguments_editor.read(cx).editor.read(cx).text(cx))
2253 .filter(|args| !args.is_empty());
2254
2255 let value = action_arguments
2256 .as_ref()
2257 .map(|args| {
2258 serde_json::from_str(args).context("Failed to parse action arguments as JSON")
2259 })
2260 .transpose()?;
2261
2262 cx.build_action(self.editing_keybind.action().name, value)
2263 .context("Failed to validate action arguments")?;
2264 Ok(action_arguments)
2265 }
2266
2267 fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<KeybindingKeystroke>> {
2268 let new_keystrokes = self
2269 .keybind_editor
2270 .read_with(cx, |editor, _| editor.keystrokes().to_vec());
2271 anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
2272 Ok(new_keystrokes)
2273 }
2274
2275 fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
2276 let new_context = self
2277 .context_editor
2278 .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
2279 let Some(context) = new_context.is_empty().not().then_some(new_context) else {
2280 return Ok(None);
2281 };
2282 gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
2283
2284 Ok(Some(context))
2285 }
2286
2287 fn save_or_display_error(&mut self, cx: &mut Context<Self>) {
2288 self.save(cx).map_err(|err| self.set_error(err, cx)).ok();
2289 }
2290
2291 fn save(&mut self, cx: &mut Context<Self>) -> Result<(), InputError> {
2292 let existing_keybind = self.editing_keybind.clone();
2293 let fs = self.fs.clone();
2294 let tab_size = cx.global::<settings::SettingsStore>().json_tab_size();
2295
2296 let mut new_keystrokes = self.validate_keystrokes(cx).map_err(InputError::error)?;
2297 new_keystrokes
2298 .iter_mut()
2299 .for_each(|ks| ks.remove_key_char());
2300
2301 let new_context = self.validate_context(cx).map_err(InputError::error)?;
2302 let new_action_args = self
2303 .validate_action_arguments(cx)
2304 .map_err(InputError::error)?;
2305
2306 let action_mapping = ActionMapping {
2307 keystrokes: new_keystrokes,
2308 context: new_context.map(SharedString::from),
2309 };
2310
2311 let conflicting_indices = self
2312 .keymap_editor
2313 .read(cx)
2314 .keybinding_conflict_state
2315 .conflicting_indices_for_mapping(
2316 &action_mapping,
2317 self.creating.not().then_some(self.editing_keybind_idx),
2318 );
2319
2320 conflicting_indices.map(|KeybindConflict {
2321 first_conflict_index,
2322 remaining_conflict_amount,
2323 }|
2324 {
2325 let conflicting_action_name = self
2326 .keymap_editor
2327 .read(cx)
2328 .keybindings
2329 .get(first_conflict_index)
2330 .map(|keybind| keybind.action().name);
2331
2332 let warning_message = match conflicting_action_name {
2333 Some(name) => {
2334 if remaining_conflict_amount > 0 {
2335 format!(
2336 "Your keybind would conflict with the \"{}\" action and {} other bindings",
2337 name, remaining_conflict_amount
2338 )
2339 } else {
2340 format!("Your keybind would conflict with the \"{}\" action", name)
2341 }
2342 }
2343 None => {
2344 log::info!(
2345 "Could not find action in keybindings with index {}",
2346 first_conflict_index
2347 );
2348 "Your keybind would conflict with other actions".to_string()
2349 }
2350 };
2351
2352 let warning = InputError::warning(warning_message);
2353 if self.error.as_ref().is_some_and(|old_error| *old_error == warning) {
2354 Ok(())
2355 } else {
2356 Err(warning)
2357 }
2358 }).unwrap_or(Ok(()))?;
2359
2360 let create = self.creating;
2361 let keyboard_mapper = cx.keyboard_mapper().clone();
2362
2363 cx.spawn(async move |this, cx| {
2364 let action_name = existing_keybind.action().name;
2365 let humanized_action_name = existing_keybind.action().humanized_name.clone();
2366
2367 match save_keybinding_update(
2368 create,
2369 existing_keybind,
2370 &action_mapping,
2371 new_action_args.as_deref(),
2372 &fs,
2373 tab_size,
2374 keyboard_mapper.as_ref(),
2375 )
2376 .await
2377 {
2378 Ok(_) => {
2379 this.update(cx, |this, cx| {
2380 this.keymap_editor.update(cx, |keymap, cx| {
2381 keymap.previous_edit = Some(PreviousEdit::Keybinding {
2382 action_mapping,
2383 action_name,
2384 fallback: keymap
2385 .table_interaction_state
2386 .read(cx)
2387 .get_scrollbar_offset(Axis::Vertical),
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 =
2723 project::lsp_store::json_language_server_ext::normalized_action_file_name(
2724 action_name,
2725 );
2726
2727 let (buffer, backup_temp_dir) =
2728 Self::create_temp_buffer(temp_dir, file_name.clone(), project.clone(), fs, cx)
2729 .await
2730 .context(concat!(
2731 "Failed to create temporary buffer for action arguments. ",
2732 "Auto-complete will not work"
2733 ))?;
2734
2735 let editor = cx.new_window_entity(|window, cx| {
2736 let multi_buffer = cx.new(|cx| editor::MultiBuffer::singleton(buffer, cx));
2737 let mut editor = Editor::new(
2738 editor::EditorMode::Full {
2739 scale_ui_elements_with_buffer_font_size: true,
2740 show_active_line_background: false,
2741 sized_by_content: true,
2742 },
2743 multi_buffer,
2744 project.upgrade(),
2745 window,
2746 cx,
2747 );
2748 editor.set_searchable(false);
2749 editor.disable_scrollbars_and_minimap(window, cx);
2750 editor.set_show_edit_predictions(Some(false), window, cx);
2751 editor.set_show_gutter(false, cx);
2752 Self::set_editor_text(&mut editor, arguments, window, cx);
2753 editor
2754 })?;
2755
2756 this.update_in(cx, |this, window, cx| {
2757 if this.editor.focus_handle(cx).is_focused(window) {
2758 editor.focus_handle(cx).focus(window);
2759 }
2760 this.editor = editor;
2761 this.backup_temp_dir = backup_temp_dir;
2762 this.is_loading = false;
2763 })?;
2764
2765 anyhow::Ok(())
2766 }
2767 .await;
2768 if result.is_err() {
2769 let json_language = load_json_language(workspace.clone(), cx).await;
2770 this.update(cx, |this, cx| {
2771 this.editor.update(cx, |editor, cx| {
2772 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2773 buffer.update(cx, |buffer, cx| {
2774 buffer.set_language(Some(json_language.clone()), cx)
2775 });
2776 }
2777 })
2778 // .context("Failed to load JSON language for editing keybinding action arguments input")
2779 })
2780 .ok();
2781 this.update(cx, |this, _cx| {
2782 this.is_loading = false;
2783 })
2784 .ok();
2785 }
2786 result
2787 })
2788 .detach_and_log_err(cx);
2789 Self {
2790 editor,
2791 focus_handle,
2792 is_loading: true,
2793 backup_temp_dir: None,
2794 }
2795 }
2796
2797 fn set_editor_text(
2798 editor: &mut Editor,
2799 arguments: Option<SharedString>,
2800 window: &mut Window,
2801 cx: &mut Context<Editor>,
2802 ) {
2803 if let Some(arguments) = arguments {
2804 editor.set_text(arguments, window, cx);
2805 } else {
2806 // TODO: default value from schema?
2807 editor.set_placeholder_text("Action Arguments", cx);
2808 }
2809 }
2810
2811 async fn create_temp_buffer(
2812 temp_dir: Option<std::path::PathBuf>,
2813 file_name: String,
2814 project: WeakEntity<Project>,
2815 fs: Arc<dyn Fs>,
2816 cx: &mut AsyncApp,
2817 ) -> anyhow::Result<(Entity<language::Buffer>, Option<tempfile::TempDir>)> {
2818 let (temp_file_path, temp_dir) = {
2819 let file_name = file_name.clone();
2820 async move {
2821 let temp_dir_backup = match temp_dir.as_ref() {
2822 Some(_) => None,
2823 None => {
2824 let temp_dir = paths::temp_dir();
2825 let sub_temp_dir = tempfile::Builder::new()
2826 .tempdir_in(temp_dir)
2827 .context("Failed to create temporary directory")?;
2828 Some(sub_temp_dir)
2829 }
2830 };
2831 let dir_path = temp_dir.as_deref().unwrap_or_else(|| {
2832 temp_dir_backup
2833 .as_ref()
2834 .expect("created backup tempdir")
2835 .path()
2836 });
2837 let path = dir_path.join(file_name);
2838 fs.create_file(
2839 &path,
2840 fs::CreateOptions {
2841 ignore_if_exists: true,
2842 overwrite: true,
2843 },
2844 )
2845 .await
2846 .context("Failed to create temporary file")?;
2847 anyhow::Ok((path, temp_dir_backup))
2848 }
2849 }
2850 .await
2851 .context("Failed to create backing file")?;
2852
2853 project
2854 .update(cx, |project, cx| {
2855 project.open_local_buffer(temp_file_path, cx)
2856 })?
2857 .await
2858 .context("Failed to create buffer")
2859 .map(|buffer| (buffer, temp_dir))
2860 }
2861}
2862
2863impl Render for ActionArgumentsEditor {
2864 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2865 let background_color;
2866 let border_color;
2867 let text_style = {
2868 let colors = cx.theme().colors();
2869 let settings = theme::ThemeSettings::get_global(cx);
2870 background_color = colors.editor_background;
2871 border_color = if self.is_loading {
2872 colors.border_disabled
2873 } else {
2874 colors.border_variant
2875 };
2876 TextStyleRefinement {
2877 font_size: Some(rems(0.875).into()),
2878 font_weight: Some(settings.buffer_font.weight),
2879 line_height: Some(relative(1.2)),
2880 font_style: Some(gpui::FontStyle::Normal),
2881 color: self.is_loading.then_some(colors.text_disabled),
2882 ..Default::default()
2883 }
2884 };
2885
2886 self.editor
2887 .update(cx, |editor, _| editor.set_text_style_refinement(text_style));
2888
2889 v_flex().w_full().child(
2890 h_flex()
2891 .min_h_8()
2892 .min_w_48()
2893 .px_2()
2894 .py_1p5()
2895 .flex_grow()
2896 .rounded_lg()
2897 .bg(background_color)
2898 .border_1()
2899 .border_color(border_color)
2900 .track_focus(&self.focus_handle)
2901 .child(self.editor.clone()),
2902 )
2903 }
2904}
2905
2906struct KeyContextCompletionProvider {
2907 contexts: Vec<SharedString>,
2908}
2909
2910impl CompletionProvider for KeyContextCompletionProvider {
2911 fn completions(
2912 &self,
2913 _excerpt_id: editor::ExcerptId,
2914 buffer: &Entity<language::Buffer>,
2915 buffer_position: language::Anchor,
2916 _trigger: editor::CompletionContext,
2917 _window: &mut Window,
2918 cx: &mut Context<Editor>,
2919 ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2920 let buffer = buffer.read(cx);
2921 let mut count_back = 0;
2922 for char in buffer.reversed_chars_at(buffer_position) {
2923 if char.is_ascii_alphanumeric() || char == '_' {
2924 count_back += 1;
2925 } else {
2926 break;
2927 }
2928 }
2929 let start_anchor =
2930 buffer.anchor_before(buffer_position.to_offset(buffer).saturating_sub(count_back));
2931 let replace_range = start_anchor..buffer_position;
2932 gpui::Task::ready(Ok(vec![project::CompletionResponse {
2933 completions: self
2934 .contexts
2935 .iter()
2936 .map(|context| project::Completion {
2937 replace_range: replace_range.clone(),
2938 label: language::CodeLabel::plain(context.to_string(), None),
2939 new_text: context.to_string(),
2940 documentation: None,
2941 source: project::CompletionSource::Custom,
2942 icon_path: None,
2943 insert_text_mode: None,
2944 confirm: None,
2945 })
2946 .collect(),
2947 display_options: CompletionDisplayOptions::default(),
2948 is_incomplete: false,
2949 }]))
2950 }
2951
2952 fn is_completion_trigger(
2953 &self,
2954 _buffer: &Entity<language::Buffer>,
2955 _position: language::Anchor,
2956 text: &str,
2957 _trigger_in_words: bool,
2958 _menu_is_open: bool,
2959 _cx: &mut Context<Editor>,
2960 ) -> bool {
2961 text.chars()
2962 .last()
2963 .is_some_and(|last_char| last_char.is_ascii_alphanumeric() || last_char == '_')
2964 }
2965}
2966
2967async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
2968 let json_language_task = workspace
2969 .read_with(cx, |workspace, cx| {
2970 workspace
2971 .project()
2972 .read(cx)
2973 .languages()
2974 .language_for_name("JSON")
2975 })
2976 .context("Failed to load JSON language")
2977 .log_err();
2978 let json_language = match json_language_task {
2979 Some(task) => task.await.context("Failed to load JSON language").log_err(),
2980 None => None,
2981 };
2982 json_language.unwrap_or_else(|| {
2983 Arc::new(Language::new(
2984 LanguageConfig {
2985 name: "JSON".into(),
2986 ..Default::default()
2987 },
2988 Some(tree_sitter_json::LANGUAGE.into()),
2989 ))
2990 })
2991}
2992
2993async fn load_keybind_context_language(
2994 workspace: WeakEntity<Workspace>,
2995 cx: &mut AsyncApp,
2996) -> Arc<Language> {
2997 let language_task = workspace
2998 .read_with(cx, |workspace, cx| {
2999 workspace
3000 .project()
3001 .read(cx)
3002 .languages()
3003 .language_for_name("Zed Keybind Context")
3004 })
3005 .context("Failed to load Zed Keybind Context language")
3006 .log_err();
3007 let language = match language_task {
3008 Some(task) => task
3009 .await
3010 .context("Failed to load Zed Keybind Context language")
3011 .log_err(),
3012 None => None,
3013 };
3014 language.unwrap_or_else(|| {
3015 Arc::new(Language::new(
3016 LanguageConfig {
3017 name: "Zed Keybind Context".into(),
3018 ..Default::default()
3019 },
3020 Some(tree_sitter_rust::LANGUAGE.into()),
3021 ))
3022 })
3023}
3024
3025async fn save_keybinding_update(
3026 create: bool,
3027 existing: ProcessedBinding,
3028 action_mapping: &ActionMapping,
3029 new_args: Option<&str>,
3030 fs: &Arc<dyn Fs>,
3031 tab_size: usize,
3032 keyboard_mapper: &dyn PlatformKeyboardMapper,
3033) -> anyhow::Result<()> {
3034 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3035 .await
3036 .context("Failed to load keymap file")?;
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 tab_size: usize,
3102 keyboard_mapper: &dyn PlatformKeyboardMapper,
3103) -> anyhow::Result<()> {
3104 let Some(keystrokes) = existing.keystrokes() else {
3105 anyhow::bail!("Cannot remove a keybinding that does not exist");
3106 };
3107 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3108 .await
3109 .context("Failed to load keymap file")?;
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}