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