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