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: false },
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 let row_count = self.matches.len();
1604 let theme = cx.theme();
1605 let focus_handle = &self.focus_handle;
1606
1607 v_flex()
1608 .id("keymap-editor")
1609 .track_focus(focus_handle)
1610 .key_context(self.key_context())
1611 .on_action(cx.listener(Self::select_next))
1612 .on_action(cx.listener(Self::select_previous))
1613 .on_action(cx.listener(Self::select_first))
1614 .on_action(cx.listener(Self::select_last))
1615 .on_action(cx.listener(Self::focus_search))
1616 .on_action(cx.listener(Self::edit_binding))
1617 .on_action(cx.listener(Self::create_binding))
1618 .on_action(cx.listener(Self::delete_binding))
1619 .on_action(cx.listener(Self::copy_action_to_clipboard))
1620 .on_action(cx.listener(Self::copy_context_to_clipboard))
1621 .on_action(cx.listener(Self::toggle_conflict_filter))
1622 .on_action(cx.listener(Self::toggle_keystroke_search))
1623 .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1624 .on_action(cx.listener(Self::show_matching_keystrokes))
1625 .on_mouse_move(cx.listener(|this, _, _window, _cx| {
1626 this.show_hover_menus = true;
1627 }))
1628 .size_full()
1629 .p_2()
1630 .gap_1()
1631 .bg(theme.colors().editor_background)
1632 .child(
1633 v_flex()
1634 .gap_2()
1635 .child(
1636 h_flex()
1637 .gap_2()
1638 .child(
1639 h_flex()
1640 .key_context({
1641 let mut context = KeyContext::new_with_defaults();
1642 context.add("BufferSearchBar");
1643 context
1644 })
1645 .size_full()
1646 .h_8()
1647 .pl_2()
1648 .pr_1()
1649 .py_1()
1650 .border_1()
1651 .border_color(theme.colors().border)
1652 .rounded_md()
1653 .child(self.filter_editor.clone()),
1654 )
1655 .child(
1656 h_flex()
1657 .gap_1()
1658 .min_w_64()
1659 .child(
1660 IconButton::new(
1661 "KeymapEditorToggleFiltersIcon",
1662 IconName::Keyboard,
1663 )
1664 .icon_size(IconSize::Small)
1665 .tooltip({
1666 let focus_handle = focus_handle.clone();
1667
1668 move |_window, cx| {
1669 Tooltip::for_action_in(
1670 "Search by Keystroke",
1671 &ToggleKeystrokeSearch,
1672 &focus_handle.clone(),
1673 cx,
1674 )
1675 }
1676 })
1677 .toggle_state(matches!(
1678 self.search_mode,
1679 SearchMode::KeyStroke { .. }
1680 ))
1681 .on_click(|_, window, cx| {
1682 window.dispatch_action(
1683 ToggleKeystrokeSearch.boxed_clone(),
1684 cx,
1685 );
1686 }),
1687 )
1688 .child(
1689 IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1690 .icon_size(IconSize::Small)
1691 .when(
1692 self.keybinding_conflict_state
1693 .any_user_binding_conflicts(),
1694 |this| {
1695 this.indicator(
1696 Indicator::dot().color(Color::Warning),
1697 )
1698 },
1699 )
1700 .tooltip({
1701 let filter_state = self.filter_state;
1702 let focus_handle = focus_handle.clone();
1703
1704 move |_window, cx| {
1705 Tooltip::for_action_in(
1706 match filter_state {
1707 FilterState::All => "Show Conflicts",
1708 FilterState::Conflicts => {
1709 "Hide Conflicts"
1710 }
1711 },
1712 &ToggleConflictFilter,
1713 &focus_handle.clone(),
1714 cx,
1715 )
1716 }
1717 })
1718 .selected_icon_color(Color::Warning)
1719 .toggle_state(matches!(
1720 self.filter_state,
1721 FilterState::Conflicts
1722 ))
1723 .on_click(|_, window, cx| {
1724 window.dispatch_action(
1725 ToggleConflictFilter.boxed_clone(),
1726 cx,
1727 );
1728 }),
1729 )
1730 .child(
1731 h_flex()
1732 .w_full()
1733 .pl_2()
1734 .gap_1()
1735 .justify_end()
1736 .child(
1737 PopoverMenu::new("open-keymap-menu")
1738 .menu(move |window, cx| {
1739 Some(ContextMenu::build(window, cx, |menu, _, _| {
1740 menu.header("View Default...")
1741 .action(
1742 "Zed Key Bindings",
1743 zed_actions::OpenDefaultKeymap
1744 .boxed_clone(),
1745 )
1746 .action(
1747 "Vim Bindings",
1748 vim::OpenDefaultKeymap.boxed_clone(),
1749 )
1750 }))
1751 })
1752 .anchor(gpui::Corner::TopRight)
1753 .offset(gpui::Point {
1754 x: px(0.0),
1755 y: px(2.0),
1756 })
1757 .trigger_with_tooltip(
1758 IconButton::new(
1759 "OpenKeymapJsonButton",
1760 IconName::Ellipsis,
1761 )
1762 .icon_size(IconSize::Small),
1763 {
1764 let focus_handle = focus_handle.clone();
1765 move |_window, cx| {
1766 Tooltip::for_action_in(
1767 "View Default...",
1768 &zed_actions::OpenKeymapFile,
1769 &focus_handle,
1770 cx,
1771 )
1772 }
1773 },
1774 ),
1775 )
1776 .child(
1777 Button::new("edit-in-json", "Edit in keymap.json")
1778 .style(ButtonStyle::Outlined)
1779 .on_click(|_, window, cx| {
1780 window.dispatch_action(
1781 zed_actions::OpenKeymapFile.boxed_clone(),
1782 cx,
1783 );
1784 })
1785 ),
1786 )
1787 ),
1788 )
1789 .when_some(
1790 match self.search_mode {
1791 SearchMode::Normal => None,
1792 SearchMode::KeyStroke { exact_match } => Some(exact_match),
1793 },
1794 |this, exact_match| {
1795 this.child(
1796 h_flex()
1797 .gap_2()
1798 .child(self.keystroke_editor.clone())
1799 .child(
1800 h_flex()
1801 .min_w_64()
1802 .child(
1803 IconButton::new(
1804 "keystrokes-exact-match",
1805 IconName::CaseSensitive,
1806 )
1807 .tooltip({
1808 let keystroke_focus_handle =
1809 self.keystroke_editor.read(cx).focus_handle(cx);
1810
1811 move |_window, cx| {
1812 Tooltip::for_action_in(
1813 "Toggle Exact Match Mode",
1814 &ToggleExactKeystrokeMatching,
1815 &keystroke_focus_handle,
1816 cx,
1817 )
1818 }
1819 })
1820 .shape(IconButtonShape::Square)
1821 .toggle_state(exact_match)
1822 .on_click(
1823 cx.listener(|_, _, window, cx| {
1824 window.dispatch_action(
1825 ToggleExactKeystrokeMatching.boxed_clone(),
1826 cx,
1827 );
1828 }),
1829 ),
1830 ),
1831 )
1832 )
1833 },
1834 ),
1835 )
1836 .child(
1837 Table::new()
1838 .interactable(&self.table_interaction_state)
1839 .striped()
1840 .empty_table_callback({
1841 let this = cx.entity();
1842 move |window, cx| this.read(cx).render_no_matches_hint(window, cx)
1843 })
1844 .column_widths([
1845 DefiniteLength::Absolute(AbsoluteLength::Pixels(px(36.))),
1846 DefiniteLength::Fraction(0.25),
1847 DefiniteLength::Fraction(0.20),
1848 DefiniteLength::Fraction(0.14),
1849 DefiniteLength::Fraction(0.45),
1850 DefiniteLength::Fraction(0.08),
1851 ])
1852 .resizable_columns(
1853 [
1854 TableResizeBehavior::None,
1855 TableResizeBehavior::Resizable,
1856 TableResizeBehavior::Resizable,
1857 TableResizeBehavior::Resizable,
1858 TableResizeBehavior::Resizable,
1859 TableResizeBehavior::Resizable, // this column doesn't matter
1860 ],
1861 &self.current_widths,
1862 cx,
1863 )
1864 .header(["", "Action", "Arguments", "Keystrokes", "Context", "Source"])
1865 .uniform_list(
1866 "keymap-editor-table",
1867 row_count,
1868 cx.processor(move |this, range: Range<usize>, _window, cx| {
1869 let context_menu_deployed = this.context_menu_deployed();
1870 range
1871 .filter_map(|index| {
1872 let candidate_id = this.matches.get(index)?.candidate_id;
1873 let binding = &this.keybindings[candidate_id];
1874 let action_name = binding.action().name;
1875 let conflict = this.get_conflict(index);
1876 let is_overridden = conflict.is_some_and(|conflict| {
1877 !conflict.is_user_keybind_conflict()
1878 });
1879
1880 let icon = this.create_row_button(index, conflict, cx);
1881
1882 let action = div()
1883 .id(("keymap action", index))
1884 .child({
1885 if action_name != gpui::NoAction.name() {
1886 binding
1887 .action()
1888 .humanized_name
1889 .clone()
1890 .into_any_element()
1891 } else {
1892 const NULL: SharedString =
1893 SharedString::new_static("<null>");
1894 muted_styled_text(NULL, cx)
1895 .into_any_element()
1896 }
1897 })
1898 .when(
1899 !context_menu_deployed
1900 && this.show_hover_menus
1901 && !is_overridden,
1902 |this| {
1903 this.tooltip({
1904 let action_name = binding.action().name;
1905 let action_docs =
1906 binding.action().documentation;
1907 move |_, cx| {
1908 let action_tooltip =
1909 Tooltip::new(action_name);
1910 let action_tooltip = match action_docs {
1911 Some(docs) => action_tooltip.meta(docs),
1912 None => action_tooltip,
1913 };
1914 cx.new(|_| action_tooltip).into()
1915 }
1916 })
1917 },
1918 )
1919 .into_any_element();
1920
1921 let keystrokes = binding.key_binding().map_or(
1922 binding
1923 .keystroke_text()
1924 .cloned()
1925 .unwrap_or_default()
1926 .into_any_element(),
1927 |binding| ui::KeyBinding::from_keystrokes(binding.keystrokes.clone(), binding.source).into_any_element()
1928 );
1929
1930 let action_arguments = match binding.action().arguments.clone()
1931 {
1932 Some(arguments) => arguments.into_any_element(),
1933 None => {
1934 if binding.action().has_schema {
1935 muted_styled_text(NO_ACTION_ARGUMENTS_TEXT, cx)
1936 .into_any_element()
1937 } else {
1938 gpui::Empty.into_any_element()
1939 }
1940 }
1941 };
1942
1943 let context = binding.context().cloned().map_or(
1944 gpui::Empty.into_any_element(),
1945 |context| {
1946 let is_local = context.local().is_some();
1947
1948 div()
1949 .id(("keymap context", index))
1950 .child(context.clone())
1951 .when(
1952 is_local
1953 && !context_menu_deployed
1954 && !is_overridden
1955 && this.show_hover_menus,
1956 |this| {
1957 this.tooltip(Tooltip::element({
1958 move |_, _| {
1959 context.clone().into_any_element()
1960 }
1961 }))
1962 },
1963 )
1964 .into_any_element()
1965 },
1966 );
1967
1968 let source = binding
1969 .keybind_source()
1970 .map(|source| source.name())
1971 .unwrap_or_default()
1972 .into_any_element();
1973
1974 Some([
1975 icon.into_any_element(),
1976 action,
1977 action_arguments,
1978 keystrokes,
1979 context,
1980 source,
1981 ])
1982 })
1983 .collect()
1984 }),
1985 )
1986 .map_row(cx.processor(
1987 |this, (row_index, row): (usize, Stateful<Div>), _window, cx| {
1988 let conflict = this.get_conflict(row_index);
1989 let is_selected = this.selected_index == Some(row_index);
1990
1991 let row_id = row_group_id(row_index);
1992
1993 div()
1994 .id(("keymap-row-wrapper", row_index))
1995 .child(
1996 row.id(row_id.clone())
1997 .on_any_mouse_down(cx.listener(
1998 move |this,
1999 mouse_down_event: &gpui::MouseDownEvent,
2000 window,
2001 cx| {
2002 if mouse_down_event.button == MouseButton::Right {
2003 this.select_index(
2004 row_index, None, window, cx,
2005 );
2006 this.create_context_menu(
2007 mouse_down_event.position,
2008 window,
2009 cx,
2010 );
2011 }
2012 },
2013 ))
2014 .on_click(cx.listener(
2015 move |this, event: &ClickEvent, window, cx| {
2016 this.select_index(row_index, None, window, cx);
2017 if event.click_count() == 2 {
2018 this.open_edit_keybinding_modal(
2019 false, window, cx,
2020 );
2021 }
2022 },
2023 ))
2024 .group(row_id)
2025 .when(
2026 conflict.is_some_and(|conflict| {
2027 !conflict.is_user_keybind_conflict()
2028 }),
2029 |row| {
2030 const OVERRIDDEN_OPACITY: f32 = 0.5;
2031 row.opacity(OVERRIDDEN_OPACITY)
2032 },
2033 )
2034 .when_some(
2035 conflict.filter(|conflict| {
2036 !this.context_menu_deployed() &&
2037 !conflict.is_user_keybind_conflict()
2038 }),
2039 |row, conflict| {
2040 let overriding_binding = this.keybindings.get(conflict.index);
2041 let context = overriding_binding.and_then(|binding| {
2042 match conflict.override_source {
2043 KeybindSource::User => Some("your keymap"),
2044 KeybindSource::Vim => Some("the vim keymap"),
2045 KeybindSource::Base => Some("your base keymap"),
2046 _ => {
2047 log::error!("Unexpected override from the {} keymap", conflict.override_source.name());
2048 None
2049 }
2050 }.map(|source| format!("This keybinding is overridden by the '{}' binding from {}.", binding.action().humanized_name, source))
2051 }).unwrap_or_else(|| "This binding is overridden.".to_string());
2052
2053 row.tooltip(Tooltip::text(context))},
2054 ),
2055 )
2056 .border_2()
2057 .when(
2058 conflict.is_some_and(|conflict| {
2059 conflict.is_user_keybind_conflict()
2060 }),
2061 |row| row.bg(cx.theme().status().error_background),
2062 )
2063 .when(is_selected, |row| {
2064 row.border_color(cx.theme().colors().panel_focused_border)
2065 })
2066 .into_any_element()
2067 }),
2068 ),
2069 )
2070 .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| {
2071 // This ensures that the menu is not dismissed in cases where scroll events
2072 // with a delta of zero are emitted
2073 if !event.delta.pixel_delta(px(1.)).y.is_zero() {
2074 this.context_menu.take();
2075 cx.notify();
2076 }
2077 }))
2078 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2079 deferred(
2080 anchored()
2081 .position(*position)
2082 .anchor(gpui::Corner::TopLeft)
2083 .child(menu.clone()),
2084 )
2085 .with_priority(1)
2086 }))
2087 }
2088}
2089
2090fn row_group_id(row_index: usize) -> SharedString {
2091 SharedString::new(format!("keymap-table-row-{}", row_index))
2092}
2093
2094fn base_button_style(row_index: usize, icon: IconName) -> IconButton {
2095 IconButton::new(("keymap-icon", row_index), icon)
2096 .shape(IconButtonShape::Square)
2097 .size(ButtonSize::Compact)
2098}
2099
2100#[derive(Debug, Clone, IntoElement)]
2101struct SyntaxHighlightedText {
2102 text: SharedString,
2103 language: Arc<Language>,
2104}
2105
2106impl SyntaxHighlightedText {
2107 pub fn new(text: impl Into<SharedString>, language: Arc<Language>) -> Self {
2108 Self {
2109 text: text.into(),
2110 language,
2111 }
2112 }
2113}
2114
2115impl RenderOnce for SyntaxHighlightedText {
2116 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
2117 let text_style = window.text_style();
2118 let syntax_theme = cx.theme().syntax();
2119
2120 let text = self.text.clone();
2121
2122 let highlights = self
2123 .language
2124 .highlight_text(&text.as_ref().into(), 0..text.len());
2125 let mut runs = Vec::with_capacity(highlights.len());
2126 let mut offset = 0;
2127
2128 for (highlight_range, highlight_id) in highlights {
2129 // Add un-highlighted text before the current highlight
2130 if highlight_range.start > offset {
2131 runs.push(text_style.to_run(highlight_range.start - offset));
2132 }
2133
2134 let mut run_style = text_style.clone();
2135 if let Some(highlight_style) = highlight_id.style(syntax_theme) {
2136 run_style = run_style.highlight(highlight_style);
2137 }
2138 // add the highlighted range
2139 runs.push(run_style.to_run(highlight_range.len()));
2140 offset = highlight_range.end;
2141 }
2142
2143 // Add any remaining un-highlighted text
2144 if offset < text.len() {
2145 runs.push(text_style.to_run(text.len() - offset));
2146 }
2147
2148 StyledText::new(text).with_runs(runs)
2149 }
2150}
2151
2152#[derive(PartialEq)]
2153struct InputError {
2154 severity: Severity,
2155 content: SharedString,
2156}
2157
2158impl InputError {
2159 fn warning(message: impl Into<SharedString>) -> Self {
2160 Self {
2161 severity: Severity::Warning,
2162 content: message.into(),
2163 }
2164 }
2165
2166 fn error(message: anyhow::Error) -> Self {
2167 Self {
2168 severity: Severity::Error,
2169 content: message.to_string().into(),
2170 }
2171 }
2172}
2173
2174struct KeybindingEditorModal {
2175 creating: bool,
2176 editing_keybind: ProcessedBinding,
2177 editing_keybind_idx: usize,
2178 keybind_editor: Entity<KeystrokeInput>,
2179 context_editor: Entity<InputField>,
2180 action_arguments_editor: Option<Entity<ActionArgumentsEditor>>,
2181 fs: Arc<dyn Fs>,
2182 error: Option<InputError>,
2183 keymap_editor: Entity<KeymapEditor>,
2184 workspace: WeakEntity<Workspace>,
2185 focus_state: KeybindingEditorModalFocusState,
2186}
2187
2188impl ModalView for KeybindingEditorModal {}
2189
2190impl EventEmitter<DismissEvent> for KeybindingEditorModal {}
2191
2192impl Focusable for KeybindingEditorModal {
2193 fn focus_handle(&self, cx: &App) -> FocusHandle {
2194 self.keybind_editor.focus_handle(cx)
2195 }
2196}
2197
2198impl KeybindingEditorModal {
2199 pub fn new(
2200 create: bool,
2201 editing_keybind: ProcessedBinding,
2202 editing_keybind_idx: usize,
2203 keymap_editor: Entity<KeymapEditor>,
2204 action_args_temp_dir: Option<&std::path::Path>,
2205 workspace: WeakEntity<Workspace>,
2206 fs: Arc<dyn Fs>,
2207 window: &mut Window,
2208 cx: &mut App,
2209 ) -> Self {
2210 let keybind_editor = cx
2211 .new(|cx| KeystrokeInput::new(editing_keybind.keystrokes().map(Vec::from), window, cx));
2212
2213 let context_editor: Entity<InputField> = cx.new(|cx| {
2214 let input = InputField::new(window, cx, "Keybinding Context")
2215 .label("Edit Context")
2216 .label_size(LabelSize::Default);
2217
2218 if let Some(context) = editing_keybind
2219 .context()
2220 .and_then(KeybindContextString::local)
2221 {
2222 input.editor().update(cx, |editor, cx| {
2223 editor.set_text(context.clone(), window, cx);
2224 });
2225 }
2226
2227 let editor_entity = input.editor().clone();
2228 let workspace = workspace.clone();
2229 cx.spawn(async move |_input_handle, cx| {
2230 let contexts = cx
2231 .background_spawn(async { collect_contexts_from_assets() })
2232 .await;
2233
2234 let language = load_keybind_context_language(workspace, cx).await;
2235 editor_entity
2236 .update(cx, |editor, cx| {
2237 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2238 buffer.update(cx, |buffer, cx| {
2239 buffer.set_language(Some(language), cx);
2240 });
2241 }
2242 editor.set_completion_provider(Some(std::rc::Rc::new(
2243 KeyContextCompletionProvider { contexts },
2244 )));
2245 })
2246 .context("Failed to load completions for keybinding context")
2247 })
2248 .detach_and_log_err(cx);
2249
2250 input
2251 });
2252
2253 let action_arguments_editor = editing_keybind.action().has_schema.then(|| {
2254 let arguments = editing_keybind
2255 .action()
2256 .arguments
2257 .as_ref()
2258 .map(|args| args.text.clone());
2259 cx.new(|cx| {
2260 ActionArgumentsEditor::new(
2261 editing_keybind.action().name,
2262 arguments,
2263 action_args_temp_dir,
2264 workspace.clone(),
2265 window,
2266 cx,
2267 )
2268 })
2269 });
2270
2271 let focus_state = KeybindingEditorModalFocusState::new(
2272 keybind_editor.focus_handle(cx),
2273 action_arguments_editor
2274 .as_ref()
2275 .map(|args_editor| args_editor.focus_handle(cx)),
2276 context_editor.focus_handle(cx),
2277 );
2278
2279 Self {
2280 creating: create,
2281 editing_keybind,
2282 editing_keybind_idx,
2283 fs,
2284 keybind_editor,
2285 context_editor,
2286 action_arguments_editor,
2287 error: None,
2288 keymap_editor,
2289 workspace,
2290 focus_state,
2291 }
2292 }
2293
2294 fn set_error(&mut self, error: InputError, cx: &mut Context<Self>) -> bool {
2295 if self
2296 .error
2297 .as_ref()
2298 .is_some_and(|old_error| old_error.severity == Severity::Warning && *old_error == error)
2299 {
2300 false
2301 } else {
2302 self.error = Some(error);
2303 cx.notify();
2304 true
2305 }
2306 }
2307
2308 fn validate_action_arguments(&self, cx: &App) -> anyhow::Result<Option<String>> {
2309 let action_arguments = self
2310 .action_arguments_editor
2311 .as_ref()
2312 .map(|arguments_editor| arguments_editor.read(cx).editor.read(cx).text(cx))
2313 .filter(|args| !args.is_empty());
2314
2315 let value = action_arguments
2316 .as_ref()
2317 .map(|args| {
2318 serde_json::from_str(args).context("Failed to parse action arguments as JSON")
2319 })
2320 .transpose()?;
2321
2322 cx.build_action(self.editing_keybind.action().name, value)
2323 .context("Failed to validate action arguments")?;
2324 Ok(action_arguments)
2325 }
2326
2327 fn validate_keystrokes(&self, cx: &App) -> anyhow::Result<Vec<KeybindingKeystroke>> {
2328 let new_keystrokes = self
2329 .keybind_editor
2330 .read_with(cx, |editor, _| editor.keystrokes().to_vec());
2331 anyhow::ensure!(!new_keystrokes.is_empty(), "Keystrokes cannot be empty");
2332 Ok(new_keystrokes)
2333 }
2334
2335 fn validate_context(&self, cx: &App) -> anyhow::Result<Option<String>> {
2336 let new_context = self
2337 .context_editor
2338 .read_with(cx, |input, cx| input.editor().read(cx).text(cx));
2339 let Some(context) = new_context.is_empty().not().then_some(new_context) else {
2340 return Ok(None);
2341 };
2342 gpui::KeyBindingContextPredicate::parse(&context).context("Failed to parse key context")?;
2343
2344 Ok(Some(context))
2345 }
2346
2347 fn save_or_display_error(&mut self, cx: &mut Context<Self>) {
2348 self.save(cx).map_err(|err| self.set_error(err, cx)).ok();
2349 }
2350
2351 fn save(&mut self, cx: &mut Context<Self>) -> Result<(), InputError> {
2352 let existing_keybind = self.editing_keybind.clone();
2353 let fs = self.fs.clone();
2354
2355 let mut new_keystrokes = self.validate_keystrokes(cx).map_err(InputError::error)?;
2356 new_keystrokes
2357 .iter_mut()
2358 .for_each(|ks| ks.remove_key_char());
2359
2360 let new_context = self.validate_context(cx).map_err(InputError::error)?;
2361 let new_action_args = self
2362 .validate_action_arguments(cx)
2363 .map_err(InputError::error)?;
2364
2365 let action_mapping = ActionMapping {
2366 keystrokes: Rc::from(new_keystrokes.as_slice()),
2367 context: new_context.map(SharedString::from),
2368 };
2369
2370 let conflicting_indices = self
2371 .keymap_editor
2372 .read(cx)
2373 .keybinding_conflict_state
2374 .conflicting_indices_for_mapping(
2375 &action_mapping,
2376 self.creating.not().then_some(self.editing_keybind_idx),
2377 );
2378
2379 conflicting_indices.map(|KeybindConflict {
2380 first_conflict_index,
2381 remaining_conflict_amount,
2382 }|
2383 {
2384 let conflicting_action_name = self
2385 .keymap_editor
2386 .read(cx)
2387 .keybindings
2388 .get(first_conflict_index)
2389 .map(|keybind| keybind.action().name);
2390
2391 let warning_message = match conflicting_action_name {
2392 Some(name) => {
2393 if remaining_conflict_amount > 0 {
2394 format!(
2395 "Your keybind would conflict with the \"{}\" action and {} other bindings",
2396 name, remaining_conflict_amount
2397 )
2398 } else {
2399 format!("Your keybind would conflict with the \"{}\" action", name)
2400 }
2401 }
2402 None => {
2403 log::info!(
2404 "Could not find action in keybindings with index {}",
2405 first_conflict_index
2406 );
2407 "Your keybind would conflict with other actions".to_string()
2408 }
2409 };
2410
2411 let warning = InputError::warning(warning_message);
2412 if self.error.as_ref().is_some_and(|old_error| *old_error == warning) {
2413 Ok(())
2414 } else {
2415 Err(warning)
2416 }
2417 }).unwrap_or(Ok(()))?;
2418
2419 let create = self.creating;
2420 let keyboard_mapper = cx.keyboard_mapper().clone();
2421
2422 cx.spawn(async move |this, cx| {
2423 let action_name = existing_keybind.action().name;
2424 let humanized_action_name = existing_keybind.action().humanized_name.clone();
2425
2426 match save_keybinding_update(
2427 create,
2428 existing_keybind,
2429 &action_mapping,
2430 new_action_args.as_deref(),
2431 &fs,
2432 keyboard_mapper.as_ref(),
2433 )
2434 .await
2435 {
2436 Ok(_) => {
2437 this.update(cx, |this, cx| {
2438 this.keymap_editor.update(cx, |keymap, cx| {
2439 keymap.previous_edit = Some(PreviousEdit::Keybinding {
2440 action_mapping,
2441 action_name,
2442 fallback: keymap.table_interaction_state.read(cx).scroll_offset(),
2443 });
2444 let status_toast = StatusToast::new(
2445 format!("Saved edits to the {} action.", humanized_action_name),
2446 cx,
2447 move |this, _cx| {
2448 this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
2449 .dismiss_button(true)
2450 // .action("Undo", f) todo: wire the undo functionality
2451 },
2452 );
2453
2454 this.workspace
2455 .update(cx, |workspace, cx| {
2456 workspace.toggle_status_toast(status_toast, cx);
2457 })
2458 .log_err();
2459 });
2460 cx.emit(DismissEvent);
2461 })
2462 .ok();
2463 }
2464 Err(err) => {
2465 this.update(cx, |this, cx| {
2466 this.set_error(InputError::error(err), cx);
2467 })
2468 .log_err();
2469 }
2470 }
2471 })
2472 .detach();
2473
2474 Ok(())
2475 }
2476
2477 fn key_context(&self) -> KeyContext {
2478 let mut key_context = KeyContext::new_with_defaults();
2479 key_context.add("KeybindEditorModal");
2480 key_context
2481 }
2482
2483 fn focus_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
2484 self.focus_state.focus_next(window, cx);
2485 }
2486
2487 fn focus_prev(
2488 &mut self,
2489 _: &menu::SelectPrevious,
2490 window: &mut Window,
2491 cx: &mut Context<Self>,
2492 ) {
2493 self.focus_state.focus_previous(window, cx);
2494 }
2495
2496 fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2497 self.save_or_display_error(cx);
2498 }
2499
2500 fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
2501 cx.emit(DismissEvent);
2502 }
2503
2504 fn get_matching_bindings_count(&self, cx: &Context<Self>) -> usize {
2505 let current_keystrokes = self.keybind_editor.read(cx).keystrokes();
2506
2507 if current_keystrokes.is_empty() {
2508 return 0;
2509 }
2510
2511 self.keymap_editor
2512 .read(cx)
2513 .keybindings
2514 .iter()
2515 .enumerate()
2516 .filter(|(idx, binding)| {
2517 // Don't count the binding we're currently editing
2518 if !self.creating && *idx == self.editing_keybind_idx {
2519 return false;
2520 }
2521
2522 binding.keystrokes().is_some_and(|keystrokes| {
2523 keystrokes_match_exactly(keystrokes, current_keystrokes)
2524 })
2525 })
2526 .count()
2527 }
2528
2529 fn show_matching_bindings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2530 let keystrokes = self.keybind_editor.read(cx).keystrokes().to_vec();
2531
2532 self.keymap_editor.update(cx, |keymap_editor, cx| {
2533 keymap_editor.clear_action_query(window, cx)
2534 });
2535
2536 // Dismiss the modal
2537 cx.emit(DismissEvent);
2538
2539 // Update the keymap editor to show matching keystrokes
2540 self.keymap_editor.update(cx, |editor, cx| {
2541 editor.filter_state = FilterState::All;
2542 editor.search_mode = SearchMode::KeyStroke { exact_match: true };
2543 editor.keystroke_editor.update(cx, |keystroke_editor, cx| {
2544 keystroke_editor.set_keystrokes(keystrokes, cx);
2545 });
2546 });
2547 }
2548}
2549
2550impl Render for KeybindingEditorModal {
2551 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2552 let theme = cx.theme().colors();
2553 let matching_bindings_count = self.get_matching_bindings_count(cx);
2554
2555 v_flex()
2556 .w(rems(34.))
2557 .elevation_3(cx)
2558 .key_context(self.key_context())
2559 .on_action(cx.listener(Self::focus_next))
2560 .on_action(cx.listener(Self::focus_prev))
2561 .on_action(cx.listener(Self::confirm))
2562 .on_action(cx.listener(Self::cancel))
2563 .child(
2564 Modal::new("keybinding_editor_modal", None)
2565 .header(
2566 ModalHeader::new().child(
2567 v_flex()
2568 .w_full()
2569 .pb_1p5()
2570 .mb_1()
2571 .gap_0p5()
2572 .border_b_1()
2573 .border_color(theme.border_variant)
2574 .child(Label::new(
2575 self.editing_keybind.action().humanized_name.clone(),
2576 ))
2577 .when_some(
2578 self.editing_keybind.action().documentation,
2579 |this, docs| {
2580 this.child(
2581 Label::new(docs)
2582 .size(LabelSize::Small)
2583 .color(Color::Muted),
2584 )
2585 },
2586 ),
2587 ),
2588 )
2589 .section(
2590 Section::new().child(
2591 v_flex()
2592 .gap_2p5()
2593 .child(
2594 v_flex()
2595 .gap_1()
2596 .child(Label::new("Edit Keystroke"))
2597 .child(self.keybind_editor.clone())
2598 .child(h_flex().gap_px().when(
2599 matching_bindings_count > 0,
2600 |this| {
2601 let label = format!(
2602 "There {} {} {} with the same keystrokes.",
2603 if matching_bindings_count == 1 {
2604 "is"
2605 } else {
2606 "are"
2607 },
2608 matching_bindings_count,
2609 if matching_bindings_count == 1 {
2610 "binding"
2611 } else {
2612 "bindings"
2613 }
2614 );
2615
2616 this.child(
2617 Label::new(label)
2618 .size(LabelSize::Small)
2619 .color(Color::Muted),
2620 )
2621 .child(
2622 Button::new("show_matching", "View")
2623 .label_size(LabelSize::Small)
2624 .icon(IconName::ArrowUpRight)
2625 .icon_color(Color::Muted)
2626 .icon_size(IconSize::Small)
2627 .on_click(cx.listener(
2628 |this, _, window, cx| {
2629 this.show_matching_bindings(
2630 window, cx,
2631 );
2632 },
2633 )),
2634 )
2635 },
2636 )),
2637 )
2638 .when_some(self.action_arguments_editor.clone(), |this, editor| {
2639 this.child(
2640 v_flex()
2641 .gap_1()
2642 .child(Label::new("Edit Arguments"))
2643 .child(editor),
2644 )
2645 })
2646 .child(self.context_editor.clone())
2647 .when_some(self.error.as_ref(), |this, error| {
2648 this.child(
2649 Banner::new()
2650 .severity(error.severity)
2651 .child(Label::new(error.content.clone())),
2652 )
2653 }),
2654 ),
2655 )
2656 .footer(
2657 ModalFooter::new().end_slot(
2658 h_flex()
2659 .gap_1()
2660 .child(
2661 Button::new("cancel", "Cancel")
2662 .on_click(cx.listener(|_, _, _, cx| cx.emit(DismissEvent))),
2663 )
2664 .child(Button::new("save-btn", "Save").on_click(cx.listener(
2665 |this, _event, _window, cx| {
2666 this.save_or_display_error(cx);
2667 },
2668 ))),
2669 ),
2670 ),
2671 )
2672 }
2673}
2674
2675struct KeybindingEditorModalFocusState {
2676 handles: Vec<FocusHandle>,
2677}
2678
2679impl KeybindingEditorModalFocusState {
2680 fn new(
2681 keystrokes: FocusHandle,
2682 action_input: Option<FocusHandle>,
2683 context: FocusHandle,
2684 ) -> Self {
2685 Self {
2686 handles: Vec::from_iter(
2687 [Some(keystrokes), action_input, Some(context)]
2688 .into_iter()
2689 .flatten(),
2690 ),
2691 }
2692 }
2693
2694 fn focused_index(&self, window: &Window, cx: &App) -> Option<i32> {
2695 self.handles
2696 .iter()
2697 .position(|handle| handle.contains_focused(window, cx))
2698 .map(|i| i as i32)
2699 }
2700
2701 fn focus_index(&self, mut index: i32, window: &mut Window) {
2702 if index < 0 {
2703 index = self.handles.len() as i32 - 1;
2704 }
2705 if index >= self.handles.len() as i32 {
2706 index = 0;
2707 }
2708 window.focus(&self.handles[index as usize]);
2709 }
2710
2711 fn focus_next(&self, window: &mut Window, cx: &App) {
2712 let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2713 index + 1
2714 } else {
2715 0
2716 };
2717 self.focus_index(index_to_focus, window);
2718 }
2719
2720 fn focus_previous(&self, window: &mut Window, cx: &App) {
2721 let index_to_focus = if let Some(index) = self.focused_index(window, cx) {
2722 index - 1
2723 } else {
2724 self.handles.len() as i32 - 1
2725 };
2726 self.focus_index(index_to_focus, window);
2727 }
2728}
2729
2730struct ActionArgumentsEditor {
2731 editor: Entity<Editor>,
2732 focus_handle: FocusHandle,
2733 is_loading: bool,
2734 /// See documentation in `KeymapEditor` for why a temp dir is needed.
2735 /// This field exists because the keymap editor temp dir creation may fail,
2736 /// and rather than implement a complicated retry mechanism, we simply
2737 /// fallback to trying to create a temporary directory in this editor on
2738 /// demand. Of note is that the TempDir struct will remove the directory
2739 /// when dropped.
2740 backup_temp_dir: Option<tempfile::TempDir>,
2741}
2742
2743impl Focusable for ActionArgumentsEditor {
2744 fn focus_handle(&self, _cx: &App) -> FocusHandle {
2745 self.focus_handle.clone()
2746 }
2747}
2748
2749impl ActionArgumentsEditor {
2750 fn new(
2751 action_name: &'static str,
2752 arguments: Option<SharedString>,
2753 temp_dir: Option<&std::path::Path>,
2754 workspace: WeakEntity<Workspace>,
2755 window: &mut Window,
2756 cx: &mut Context<Self>,
2757 ) -> Self {
2758 let focus_handle = cx.focus_handle();
2759 cx.on_focus_in(&focus_handle, window, |this, window, cx| {
2760 this.editor.focus_handle(cx).focus(window);
2761 })
2762 .detach();
2763 let editor = cx.new(|cx| {
2764 let mut editor = Editor::auto_height_unbounded(1, window, cx);
2765 Self::set_editor_text(&mut editor, arguments.clone(), window, cx);
2766 editor.set_read_only(true);
2767 editor
2768 });
2769
2770 let temp_dir = temp_dir.map(|path| path.to_owned());
2771 cx.spawn_in(window, async move |this, cx| {
2772 let result = async {
2773 let (project, fs) = workspace.read_with(cx, |workspace, _cx| {
2774 (
2775 workspace.project().downgrade(),
2776 workspace.app_state().fs.clone(),
2777 )
2778 })?;
2779
2780 let file_name = json_schema_store::normalized_action_file_name(action_name);
2781
2782 let (buffer, backup_temp_dir) =
2783 Self::create_temp_buffer(temp_dir, file_name.clone(), project.clone(), fs, cx)
2784 .await
2785 .context(concat!(
2786 "Failed to create temporary buffer for action arguments. ",
2787 "Auto-complete will not work"
2788 ))?;
2789
2790 let editor = cx.new_window_entity(|window, cx| {
2791 let multi_buffer = cx.new(|cx| editor::MultiBuffer::singleton(buffer, cx));
2792 let mut editor = Editor::new(
2793 EditorMode::Full {
2794 scale_ui_elements_with_buffer_font_size: true,
2795 show_active_line_background: false,
2796 sizing_behavior: SizingBehavior::SizeByContent,
2797 },
2798 multi_buffer,
2799 project.upgrade(),
2800 window,
2801 cx,
2802 );
2803 editor.set_searchable(false);
2804 editor.disable_scrollbars_and_minimap(window, cx);
2805 editor.set_show_edit_predictions(Some(false), window, cx);
2806 editor.set_show_gutter(false, cx);
2807 Self::set_editor_text(&mut editor, arguments, window, cx);
2808 editor
2809 })?;
2810
2811 this.update_in(cx, |this, window, cx| {
2812 if this.editor.focus_handle(cx).is_focused(window) {
2813 editor.focus_handle(cx).focus(window);
2814 }
2815 this.editor = editor;
2816 this.backup_temp_dir = backup_temp_dir;
2817 this.is_loading = false;
2818 })?;
2819
2820 anyhow::Ok(())
2821 }
2822 .await;
2823 if result.is_err() {
2824 let json_language = load_json_language(workspace.clone(), cx).await;
2825 this.update(cx, |this, cx| {
2826 this.editor.update(cx, |editor, cx| {
2827 if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
2828 buffer.update(cx, |buffer, cx| {
2829 buffer.set_language(Some(json_language.clone()), cx)
2830 });
2831 }
2832 })
2833 // .context("Failed to load JSON language for editing keybinding action arguments input")
2834 })
2835 .ok();
2836 this.update(cx, |this, _cx| {
2837 this.is_loading = false;
2838 })
2839 .ok();
2840 }
2841 result
2842 })
2843 .detach_and_log_err(cx);
2844 Self {
2845 editor,
2846 focus_handle,
2847 is_loading: true,
2848 backup_temp_dir: None,
2849 }
2850 }
2851
2852 fn set_editor_text(
2853 editor: &mut Editor,
2854 arguments: Option<SharedString>,
2855 window: &mut Window,
2856 cx: &mut Context<Editor>,
2857 ) {
2858 if let Some(arguments) = arguments {
2859 editor.set_text(arguments, window, cx);
2860 } else {
2861 // TODO: default value from schema?
2862 editor.set_placeholder_text("Action Arguments", window, cx);
2863 }
2864 }
2865
2866 async fn create_temp_buffer(
2867 temp_dir: Option<std::path::PathBuf>,
2868 file_name: String,
2869 project: WeakEntity<Project>,
2870 fs: Arc<dyn Fs>,
2871 cx: &mut AsyncApp,
2872 ) -> anyhow::Result<(Entity<language::Buffer>, Option<tempfile::TempDir>)> {
2873 let (temp_file_path, temp_dir) = {
2874 let file_name = file_name.clone();
2875 async move {
2876 let temp_dir_backup = match temp_dir.as_ref() {
2877 Some(_) => None,
2878 None => {
2879 let temp_dir = paths::temp_dir();
2880 let sub_temp_dir = tempfile::Builder::new()
2881 .tempdir_in(temp_dir)
2882 .context("Failed to create temporary directory")?;
2883 Some(sub_temp_dir)
2884 }
2885 };
2886 let dir_path = temp_dir.as_deref().unwrap_or_else(|| {
2887 temp_dir_backup
2888 .as_ref()
2889 .expect("created backup tempdir")
2890 .path()
2891 });
2892 let path = dir_path.join(file_name);
2893 fs.create_file(
2894 &path,
2895 fs::CreateOptions {
2896 ignore_if_exists: true,
2897 overwrite: true,
2898 },
2899 )
2900 .await
2901 .context("Failed to create temporary file")?;
2902 anyhow::Ok((path, temp_dir_backup))
2903 }
2904 }
2905 .await
2906 .context("Failed to create backing file")?;
2907
2908 project
2909 .update(cx, |project, cx| {
2910 project.open_local_buffer(temp_file_path, cx)
2911 })?
2912 .await
2913 .context("Failed to create buffer")
2914 .map(|buffer| (buffer, temp_dir))
2915 }
2916}
2917
2918impl Render for ActionArgumentsEditor {
2919 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2920 let background_color;
2921 let border_color;
2922 let text_style = {
2923 let colors = cx.theme().colors();
2924 let settings = theme::ThemeSettings::get_global(cx);
2925 background_color = colors.editor_background;
2926 border_color = if self.is_loading {
2927 colors.border_disabled
2928 } else {
2929 colors.border_variant
2930 };
2931 TextStyleRefinement {
2932 font_size: Some(rems(0.875).into()),
2933 font_weight: Some(settings.buffer_font.weight),
2934 line_height: Some(relative(1.2)),
2935 font_style: Some(gpui::FontStyle::Normal),
2936 color: self.is_loading.then_some(colors.text_disabled),
2937 ..Default::default()
2938 }
2939 };
2940
2941 self.editor
2942 .update(cx, |editor, _| editor.set_text_style_refinement(text_style));
2943
2944 v_flex().w_full().child(
2945 h_flex()
2946 .min_h_8()
2947 .min_w_48()
2948 .px_2()
2949 .py_1p5()
2950 .flex_grow()
2951 .rounded_lg()
2952 .bg(background_color)
2953 .border_1()
2954 .border_color(border_color)
2955 .track_focus(&self.focus_handle)
2956 .child(self.editor.clone()),
2957 )
2958 }
2959}
2960
2961struct KeyContextCompletionProvider {
2962 contexts: Vec<SharedString>,
2963}
2964
2965impl CompletionProvider for KeyContextCompletionProvider {
2966 fn completions(
2967 &self,
2968 _excerpt_id: editor::ExcerptId,
2969 buffer: &Entity<language::Buffer>,
2970 buffer_position: language::Anchor,
2971 _trigger: editor::CompletionContext,
2972 _window: &mut Window,
2973 cx: &mut Context<Editor>,
2974 ) -> gpui::Task<anyhow::Result<Vec<project::CompletionResponse>>> {
2975 let buffer = buffer.read(cx);
2976 let mut count_back = 0;
2977 for char in buffer.reversed_chars_at(buffer_position) {
2978 if char.is_ascii_alphanumeric() || char == '_' {
2979 count_back += 1;
2980 } else {
2981 break;
2982 }
2983 }
2984 let start_anchor =
2985 buffer.anchor_before(buffer_position.to_offset(buffer).saturating_sub(count_back));
2986 let replace_range = start_anchor..buffer_position;
2987 gpui::Task::ready(Ok(vec![project::CompletionResponse {
2988 completions: self
2989 .contexts
2990 .iter()
2991 .map(|context| project::Completion {
2992 replace_range: replace_range.clone(),
2993 label: language::CodeLabel::plain(context.to_string(), None),
2994 new_text: context.to_string(),
2995 documentation: None,
2996 source: project::CompletionSource::Custom,
2997 icon_path: None,
2998 match_start: None,
2999 snippet_deduplication_key: None,
3000 insert_text_mode: None,
3001 confirm: None,
3002 })
3003 .collect(),
3004 display_options: CompletionDisplayOptions::default(),
3005 is_incomplete: false,
3006 }]))
3007 }
3008
3009 fn is_completion_trigger(
3010 &self,
3011 _buffer: &Entity<language::Buffer>,
3012 _position: language::Anchor,
3013 text: &str,
3014 _trigger_in_words: bool,
3015 _menu_is_open: bool,
3016 _cx: &mut Context<Editor>,
3017 ) -> bool {
3018 text.chars()
3019 .last()
3020 .is_some_and(|last_char| last_char.is_ascii_alphanumeric() || last_char == '_')
3021 }
3022}
3023
3024async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
3025 let json_language_task = workspace
3026 .read_with(cx, |workspace, cx| {
3027 workspace
3028 .project()
3029 .read(cx)
3030 .languages()
3031 .language_for_name("JSON")
3032 })
3033 .context("Failed to load JSON language")
3034 .log_err();
3035 let json_language = match json_language_task {
3036 Some(task) => task.await.context("Failed to load JSON language").log_err(),
3037 None => None,
3038 };
3039 json_language.unwrap_or_else(|| {
3040 Arc::new(Language::new(
3041 LanguageConfig {
3042 name: "JSON".into(),
3043 ..Default::default()
3044 },
3045 Some(tree_sitter_json::LANGUAGE.into()),
3046 ))
3047 })
3048}
3049
3050async fn load_keybind_context_language(
3051 workspace: WeakEntity<Workspace>,
3052 cx: &mut AsyncApp,
3053) -> Arc<Language> {
3054 let language_task = workspace
3055 .read_with(cx, |workspace, cx| {
3056 workspace
3057 .project()
3058 .read(cx)
3059 .languages()
3060 .language_for_name("Zed Keybind Context")
3061 })
3062 .context("Failed to load Zed Keybind Context language")
3063 .log_err();
3064 let language = match language_task {
3065 Some(task) => task
3066 .await
3067 .context("Failed to load Zed Keybind Context language")
3068 .log_err(),
3069 None => None,
3070 };
3071 language.unwrap_or_else(|| {
3072 Arc::new(Language::new(
3073 LanguageConfig {
3074 name: "Zed Keybind Context".into(),
3075 ..Default::default()
3076 },
3077 Some(tree_sitter_rust::LANGUAGE.into()),
3078 ))
3079 })
3080}
3081
3082async fn save_keybinding_update(
3083 create: bool,
3084 existing: ProcessedBinding,
3085 action_mapping: &ActionMapping,
3086 new_args: Option<&str>,
3087 fs: &Arc<dyn Fs>,
3088 keyboard_mapper: &dyn PlatformKeyboardMapper,
3089) -> anyhow::Result<()> {
3090 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3091 .await
3092 .context("Failed to load keymap file")?;
3093
3094 let tab_size = infer_json_indent_size(&keymap_contents);
3095
3096 let existing_keystrokes = existing.keystrokes().unwrap_or_default();
3097 let existing_context = existing.context().and_then(KeybindContextString::local_str);
3098 let existing_args = existing
3099 .action()
3100 .arguments
3101 .as_ref()
3102 .map(|args| args.text.as_ref());
3103
3104 let target = settings::KeybindUpdateTarget {
3105 context: existing_context,
3106 keystrokes: existing_keystrokes,
3107 action_name: existing.action().name,
3108 action_arguments: existing_args,
3109 };
3110
3111 let source = settings::KeybindUpdateTarget {
3112 context: action_mapping.context.as_ref().map(|a| &***a),
3113 keystrokes: &action_mapping.keystrokes,
3114 action_name: existing.action().name,
3115 action_arguments: new_args,
3116 };
3117
3118 let operation = if !create {
3119 settings::KeybindUpdateOperation::Replace {
3120 target,
3121 target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
3122 source,
3123 }
3124 } else {
3125 settings::KeybindUpdateOperation::Add {
3126 source,
3127 from: Some(target),
3128 }
3129 };
3130
3131 let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
3132
3133 let updated_keymap_contents = settings::KeymapFile::update_keybinding(
3134 operation,
3135 keymap_contents,
3136 tab_size,
3137 keyboard_mapper,
3138 )
3139 .map_err(|err| anyhow::anyhow!("Could not save updated keybinding: {}", err))?;
3140 fs.write(
3141 paths::keymap_file().as_path(),
3142 updated_keymap_contents.as_bytes(),
3143 )
3144 .await
3145 .context("Failed to write keymap file")?;
3146
3147 telemetry::event!(
3148 "Keybinding Updated",
3149 new_keybinding = new_keybinding,
3150 removed_keybinding = removed_keybinding,
3151 source = source
3152 );
3153 Ok(())
3154}
3155
3156async fn remove_keybinding(
3157 existing: ProcessedBinding,
3158 fs: &Arc<dyn Fs>,
3159 keyboard_mapper: &dyn PlatformKeyboardMapper,
3160) -> anyhow::Result<()> {
3161 let Some(keystrokes) = existing.keystrokes() else {
3162 anyhow::bail!("Cannot remove a keybinding that does not exist");
3163 };
3164 let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3165 .await
3166 .context("Failed to load keymap file")?;
3167 let tab_size = infer_json_indent_size(&keymap_contents);
3168
3169 let operation = settings::KeybindUpdateOperation::Remove {
3170 target: settings::KeybindUpdateTarget {
3171 context: existing.context().and_then(KeybindContextString::local_str),
3172 keystrokes,
3173 action_name: existing.action().name,
3174 action_arguments: existing
3175 .action()
3176 .arguments
3177 .as_ref()
3178 .map(|arguments| arguments.text.as_ref()),
3179 },
3180 target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
3181 };
3182
3183 let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
3184 let updated_keymap_contents = settings::KeymapFile::update_keybinding(
3185 operation,
3186 keymap_contents,
3187 tab_size,
3188 keyboard_mapper,
3189 )
3190 .context("Failed to update keybinding")?;
3191 fs.write(
3192 paths::keymap_file().as_path(),
3193 updated_keymap_contents.as_bytes(),
3194 )
3195 .await
3196 .context("Failed to write keymap file")?;
3197
3198 telemetry::event!(
3199 "Keybinding Removed",
3200 new_keybinding = new_keybinding,
3201 removed_keybinding = removed_keybinding,
3202 source = source
3203 );
3204 Ok(())
3205}
3206
3207fn collect_contexts_from_assets() -> Vec<SharedString> {
3208 let mut keymap_assets = vec![
3209 util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
3210 util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
3211 ];
3212 keymap_assets.extend(
3213 BaseKeymap::OPTIONS
3214 .iter()
3215 .filter_map(|(_, base_keymap)| base_keymap.asset_path())
3216 .map(util::asset_str::<SettingsAssets>),
3217 );
3218
3219 let mut contexts = HashSet::default();
3220
3221 for keymap_asset in keymap_assets {
3222 let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
3223 continue;
3224 };
3225
3226 for section in keymap.sections() {
3227 let context_expr = §ion.context;
3228 let mut queue = Vec::new();
3229 let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
3230 continue;
3231 };
3232
3233 queue.push(root_context);
3234 while let Some(context) = queue.pop() {
3235 match context {
3236 Identifier(ident) => {
3237 contexts.insert(ident);
3238 }
3239 Equal(ident_a, ident_b) => {
3240 contexts.insert(ident_a);
3241 contexts.insert(ident_b);
3242 }
3243 NotEqual(ident_a, ident_b) => {
3244 contexts.insert(ident_a);
3245 contexts.insert(ident_b);
3246 }
3247 Descendant(ctx_a, ctx_b) => {
3248 queue.push(*ctx_a);
3249 queue.push(*ctx_b);
3250 }
3251 Not(ctx) => {
3252 queue.push(*ctx);
3253 }
3254 And(ctx_a, ctx_b) => {
3255 queue.push(*ctx_a);
3256 queue.push(*ctx_b);
3257 }
3258 Or(ctx_a, ctx_b) => {
3259 queue.push(*ctx_a);
3260 queue.push(*ctx_b);
3261 }
3262 }
3263 }
3264 }
3265 }
3266
3267 let mut contexts = contexts.into_iter().collect::<Vec<_>>();
3268 contexts.sort();
3269
3270 contexts
3271}
3272
3273fn normalized_ctx_eq(
3274 a: &gpui::KeyBindingContextPredicate,
3275 b: &gpui::KeyBindingContextPredicate,
3276) -> bool {
3277 use gpui::KeyBindingContextPredicate::*;
3278 return match (a, b) {
3279 (Identifier(_), Identifier(_)) => a == b,
3280 (Equal(a_left, a_right), Equal(b_left, b_right)) => {
3281 (a_left == b_left && a_right == b_right) || (a_left == b_right && a_right == b_left)
3282 }
3283 (NotEqual(a_left, a_right), NotEqual(b_left, b_right)) => {
3284 (a_left == b_left && a_right == b_right) || (a_left == b_right && a_right == b_left)
3285 }
3286 (Descendant(a_parent, a_child), Descendant(b_parent, b_child)) => {
3287 normalized_ctx_eq(a_parent, b_parent) && normalized_ctx_eq(a_child, b_child)
3288 }
3289 (Not(a_expr), Not(b_expr)) => normalized_ctx_eq(a_expr, b_expr),
3290 // Handle double negation: !(!a) == a
3291 (Not(a_expr), b) if matches!(a_expr.as_ref(), Not(_)) => {
3292 let Not(a_inner) = a_expr.as_ref() else {
3293 unreachable!();
3294 };
3295 normalized_ctx_eq(b, a_inner)
3296 }
3297 (a, Not(b_expr)) if matches!(b_expr.as_ref(), Not(_)) => {
3298 let Not(b_inner) = b_expr.as_ref() else {
3299 unreachable!();
3300 };
3301 normalized_ctx_eq(a, b_inner)
3302 }
3303 (And(a_left, a_right), And(b_left, b_right))
3304 if matches!(a_left.as_ref(), And(_, _))
3305 || matches!(a_right.as_ref(), And(_, _))
3306 || matches!(b_left.as_ref(), And(_, _))
3307 || matches!(b_right.as_ref(), And(_, _)) =>
3308 {
3309 let mut a_operands = Vec::new();
3310 flatten_and(a, &mut a_operands);
3311 let mut b_operands = Vec::new();
3312 flatten_and(b, &mut b_operands);
3313 compare_operand_sets(&a_operands, &b_operands)
3314 }
3315 (And(a_left, a_right), And(b_left, b_right)) => {
3316 (normalized_ctx_eq(a_left, b_left) && normalized_ctx_eq(a_right, b_right))
3317 || (normalized_ctx_eq(a_left, b_right) && normalized_ctx_eq(a_right, b_left))
3318 }
3319 (Or(a_left, a_right), Or(b_left, b_right))
3320 if matches!(a_left.as_ref(), Or(_, _))
3321 || matches!(a_right.as_ref(), Or(_, _))
3322 || matches!(b_left.as_ref(), Or(_, _))
3323 || matches!(b_right.as_ref(), Or(_, _)) =>
3324 {
3325 let mut a_operands = Vec::new();
3326 flatten_or(a, &mut a_operands);
3327 let mut b_operands = Vec::new();
3328 flatten_or(b, &mut b_operands);
3329 compare_operand_sets(&a_operands, &b_operands)
3330 }
3331 (Or(a_left, a_right), Or(b_left, b_right)) => {
3332 (normalized_ctx_eq(a_left, b_left) && normalized_ctx_eq(a_right, b_right))
3333 || (normalized_ctx_eq(a_left, b_right) && normalized_ctx_eq(a_right, b_left))
3334 }
3335 _ => false,
3336 };
3337
3338 fn flatten_and<'a>(
3339 pred: &'a gpui::KeyBindingContextPredicate,
3340 operands: &mut Vec<&'a gpui::KeyBindingContextPredicate>,
3341 ) {
3342 use gpui::KeyBindingContextPredicate::*;
3343 match pred {
3344 And(left, right) => {
3345 flatten_and(left, operands);
3346 flatten_and(right, operands);
3347 }
3348 _ => operands.push(pred),
3349 }
3350 }
3351
3352 fn flatten_or<'a>(
3353 pred: &'a gpui::KeyBindingContextPredicate,
3354 operands: &mut Vec<&'a gpui::KeyBindingContextPredicate>,
3355 ) {
3356 use gpui::KeyBindingContextPredicate::*;
3357 match pred {
3358 Or(left, right) => {
3359 flatten_or(left, operands);
3360 flatten_or(right, operands);
3361 }
3362 _ => operands.push(pred),
3363 }
3364 }
3365
3366 fn compare_operand_sets(
3367 a: &[&gpui::KeyBindingContextPredicate],
3368 b: &[&gpui::KeyBindingContextPredicate],
3369 ) -> bool {
3370 if a.len() != b.len() {
3371 return false;
3372 }
3373
3374 // For each operand in a, find a matching operand in b
3375 let mut b_matched = vec![false; b.len()];
3376 for a_operand in a {
3377 let mut found = false;
3378 for (b_idx, b_operand) in b.iter().enumerate() {
3379 if !b_matched[b_idx] && normalized_ctx_eq(a_operand, b_operand) {
3380 b_matched[b_idx] = true;
3381 found = true;
3382 break;
3383 }
3384 }
3385 if !found {
3386 return false;
3387 }
3388 }
3389
3390 true
3391 }
3392}
3393
3394impl SerializableItem for KeymapEditor {
3395 fn serialized_item_kind() -> &'static str {
3396 "KeymapEditor"
3397 }
3398
3399 fn cleanup(
3400 workspace_id: workspace::WorkspaceId,
3401 alive_items: Vec<workspace::ItemId>,
3402 _window: &mut Window,
3403 cx: &mut App,
3404 ) -> gpui::Task<gpui::Result<()>> {
3405 workspace::delete_unloaded_items(
3406 alive_items,
3407 workspace_id,
3408 "keybinding_editors",
3409 &KEYBINDING_EDITORS,
3410 cx,
3411 )
3412 }
3413
3414 fn deserialize(
3415 _project: Entity<project::Project>,
3416 workspace: WeakEntity<Workspace>,
3417 workspace_id: workspace::WorkspaceId,
3418 item_id: workspace::ItemId,
3419 window: &mut Window,
3420 cx: &mut App,
3421 ) -> gpui::Task<gpui::Result<Entity<Self>>> {
3422 window.spawn(cx, async move |cx| {
3423 if KEYBINDING_EDITORS
3424 .get_keybinding_editor(item_id, workspace_id)?
3425 .is_some()
3426 {
3427 cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
3428 } else {
3429 Err(anyhow!("No keybinding editor to deserialize"))
3430 }
3431 })
3432 }
3433
3434 fn serialize(
3435 &mut self,
3436 workspace: &mut Workspace,
3437 item_id: workspace::ItemId,
3438 _closing: bool,
3439 _window: &mut Window,
3440 cx: &mut ui::Context<Self>,
3441 ) -> Option<gpui::Task<gpui::Result<()>>> {
3442 let workspace_id = workspace.database_id()?;
3443 Some(cx.background_spawn(async move {
3444 KEYBINDING_EDITORS
3445 .save_keybinding_editor(item_id, workspace_id)
3446 .await
3447 }))
3448 }
3449
3450 fn should_serialize(&self, _event: &Self::Event) -> bool {
3451 false
3452 }
3453}
3454
3455mod persistence {
3456 use db::{query, sqlez::domain::Domain, sqlez_macros::sql};
3457 use workspace::WorkspaceDb;
3458
3459 pub struct KeybindingEditorDb(db::sqlez::thread_safe_connection::ThreadSafeConnection);
3460
3461 impl Domain for KeybindingEditorDb {
3462 const NAME: &str = stringify!(KeybindingEditorDb);
3463
3464 const MIGRATIONS: &[&str] = &[sql!(
3465 CREATE TABLE keybinding_editors (
3466 workspace_id INTEGER,
3467 item_id INTEGER UNIQUE,
3468
3469 PRIMARY KEY(workspace_id, item_id),
3470 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
3471 ON DELETE CASCADE
3472 ) STRICT;
3473 )];
3474 }
3475
3476 db::static_connection!(KEYBINDING_EDITORS, KeybindingEditorDb, [WorkspaceDb]);
3477
3478 impl KeybindingEditorDb {
3479 query! {
3480 pub async fn save_keybinding_editor(
3481 item_id: workspace::ItemId,
3482 workspace_id: workspace::WorkspaceId
3483 ) -> Result<()> {
3484 INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3485 VALUES (?, ?)
3486 }
3487 }
3488
3489 query! {
3490 pub fn get_keybinding_editor(
3491 item_id: workspace::ItemId,
3492 workspace_id: workspace::WorkspaceId
3493 ) -> Result<Option<workspace::ItemId>> {
3494 SELECT item_id
3495 FROM keybinding_editors
3496 WHERE item_id = ? AND workspace_id = ?
3497 }
3498 }
3499 }
3500}
3501
3502#[cfg(test)]
3503mod tests {
3504 use super::*;
3505
3506 #[test]
3507 fn normalized_ctx_cmp() {
3508 #[track_caller]
3509 fn cmp(a: &str, b: &str) -> bool {
3510 let a = gpui::KeyBindingContextPredicate::parse(a)
3511 .expect("Failed to parse keybinding context a");
3512 let b = gpui::KeyBindingContextPredicate::parse(b)
3513 .expect("Failed to parse keybinding context b");
3514 normalized_ctx_eq(&a, &b)
3515 }
3516
3517 // Basic equality - identical expressions
3518 assert!(cmp("a && b", "a && b"));
3519 assert!(cmp("a || b", "a || b"));
3520 assert!(cmp("a == b", "a == b"));
3521 assert!(cmp("a != b", "a != b"));
3522 assert!(cmp("a > b", "a > b"));
3523 assert!(cmp("!a", "!a"));
3524
3525 // AND operator - associative/commutative
3526 assert!(cmp("a && b", "b && a"));
3527 assert!(cmp("a && b && c", "c && b && a"));
3528 assert!(cmp("a && b && c", "b && a && c"));
3529 assert!(cmp("a && b && c && d", "d && c && b && a"));
3530
3531 // OR operator - associative/commutative
3532 assert!(cmp("a || b", "b || a"));
3533 assert!(cmp("a || b || c", "c || b || a"));
3534 assert!(cmp("a || b || c", "b || a || c"));
3535 assert!(cmp("a || b || c || d", "d || c || b || a"));
3536
3537 // Equality operator - associative/commutative
3538 assert!(cmp("a == b", "b == a"));
3539 assert!(cmp("x == y", "y == x"));
3540
3541 // Inequality operator - associative/commutative
3542 assert!(cmp("a != b", "b != a"));
3543 assert!(cmp("x != y", "y != x"));
3544
3545 // Complex nested expressions with associative operators
3546 assert!(cmp("(a && b) || c", "c || (a && b)"));
3547 assert!(cmp("(a && b) || c", "c || (b && a)"));
3548 assert!(cmp("(a || b) && c", "c && (a || b)"));
3549 assert!(cmp("(a || b) && c", "c && (b || a)"));
3550 assert!(cmp("(a && b) || (c && d)", "(c && d) || (a && b)"));
3551 assert!(cmp("(a && b) || (c && d)", "(d && c) || (b && a)"));
3552
3553 // Multiple levels of nesting
3554 assert!(cmp("((a && b) || c) && d", "d && ((a && b) || c)"));
3555 assert!(cmp("((a && b) || c) && d", "d && (c || (b && a))"));
3556 assert!(cmp("a && (b || (c && d))", "(b || (c && d)) && a"));
3557 assert!(cmp("a && (b || (c && d))", "(b || (d && c)) && a"));
3558
3559 // Negation with associative operators
3560 assert!(cmp("!a && b", "b && !a"));
3561 assert!(cmp("!a || b", "b || !a"));
3562 assert!(cmp("!(a && b) || c", "c || !(a && b)"));
3563 assert!(cmp("!(a && b) || c", "c || !(b && a)"));
3564
3565 // Descendant operator (>) - NOT associative/commutative
3566 assert!(cmp("a > b", "a > b"));
3567 assert!(!cmp("a > b", "b > a"));
3568 assert!(!cmp("a > b > c", "c > b > a"));
3569 assert!(!cmp("a > b > c", "a > c > b"));
3570
3571 // Mixed operators with descendant
3572 assert!(cmp("(a > b) && c", "c && (a > b)"));
3573 assert!(!cmp("(a > b) && c", "c && (b > a)"));
3574 assert!(cmp("(a > b) || (c > d)", "(c > d) || (a > b)"));
3575 assert!(!cmp("(a > b) || (c > d)", "(b > a) || (d > c)"));
3576
3577 // Negative cases - different operators
3578 assert!(!cmp("a && b", "a || b"));
3579 assert!(!cmp("a == b", "a != b"));
3580 assert!(!cmp("a && b", "a > b"));
3581 assert!(!cmp("a || b", "a > b"));
3582 assert!(!cmp("a == b", "a && b"));
3583 assert!(!cmp("a != b", "a || b"));
3584
3585 // Negative cases - different operands
3586 assert!(!cmp("a && b", "a && c"));
3587 assert!(!cmp("a && b", "c && d"));
3588 assert!(!cmp("a || b", "a || c"));
3589 assert!(!cmp("a || b", "c || d"));
3590 assert!(!cmp("a == b", "a == c"));
3591 assert!(!cmp("a != b", "a != c"));
3592 assert!(!cmp("a > b", "a > c"));
3593 assert!(!cmp("a > b", "c > b"));
3594
3595 // Negative cases - with negation
3596 assert!(!cmp("!a", "a"));
3597 assert!(!cmp("!a && b", "a && b"));
3598 assert!(!cmp("!(a && b)", "a && b"));
3599 assert!(!cmp("!a || b", "a || b"));
3600 assert!(!cmp("!(a || b)", "a || b"));
3601
3602 // Negative cases - complex expressions
3603 assert!(!cmp("(a && b) || c", "(a || b) && c"));
3604 assert!(!cmp("a && (b || c)", "a || (b && c)"));
3605 assert!(!cmp("(a && b) || (c && d)", "(a || b) && (c || d)"));
3606 assert!(!cmp("a > b && c", "a && b > c"));
3607
3608 // Edge cases - multiple same operands
3609 assert!(cmp("a && a", "a && a"));
3610 assert!(cmp("a || a", "a || a"));
3611 assert!(cmp("a && a && b", "b && a && a"));
3612 assert!(cmp("a || a || b", "b || a || a"));
3613
3614 // Edge cases - deeply nested
3615 assert!(cmp(
3616 "((a && b) || (c && d)) && ((e || f) && g)",
3617 "((e || f) && g) && ((c && d) || (a && b))"
3618 ));
3619 assert!(cmp(
3620 "((a && b) || (c && d)) && ((e || f) && g)",
3621 "(g && (f || e)) && ((d && c) || (b && a))"
3622 ));
3623
3624 // Edge cases - repeated patterns
3625 assert!(cmp("(a && b) || (a && b)", "(b && a) || (b && a)"));
3626 assert!(cmp("(a || b) && (a || b)", "(b || a) && (b || a)"));
3627
3628 // Negative cases - subtle differences
3629 assert!(!cmp("a && b && c", "a && b"));
3630 assert!(!cmp("a || b || c", "a || b"));
3631 assert!(!cmp("(a && b) || c", "a && (b || c)"));
3632
3633 // a > b > c is not the same as a > c, should not be equal
3634 assert!(!cmp("a > b > c", "a > c"));
3635
3636 // Double negation with complex expressions
3637 assert!(cmp("!(!(a && b))", "a && b"));
3638 assert!(cmp("!(!(a || b))", "a || b"));
3639 assert!(cmp("!(!(a > b))", "a > b"));
3640 assert!(cmp("!(!a) && b", "a && b"));
3641 assert!(cmp("!(!a) || b", "a || b"));
3642 assert!(cmp("!(!(a && b)) || c", "(a && b) || c"));
3643 assert!(cmp("!(!(a && b)) || c", "(b && a) || c"));
3644 assert!(cmp("!(!a)", "a"));
3645 assert!(cmp("a", "!(!a)"));
3646 assert!(cmp("!(!(!a))", "!a"));
3647 assert!(cmp("!(!(!(!a)))", "a"));
3648 }
3649}