keymap_editor.rs

   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 open_keymap_editor(
  85        filter: Option<String>,
  86        workspace: &mut Workspace,
  87        window: &mut Window,
  88        cx: &mut Context<Workspace>,
  89    ) {
  90        workspace
  91            .with_local_workspace(window, cx, |workspace, window, cx| {
  92                let existing = workspace
  93                    .active_pane()
  94                    .read(cx)
  95                    .items()
  96                    .find_map(|item| item.downcast::<KeymapEditor>());
  97
  98                let keymap_editor = if let Some(existing) = existing {
  99                    workspace.activate_item(&existing, true, true, window, cx);
 100                    existing
 101                } else {
 102                    let keymap_editor =
 103                        cx.new(|cx| KeymapEditor::new(workspace.weak_handle(), window, cx));
 104                    workspace.add_item_to_active_pane(
 105                        Box::new(keymap_editor.clone()),
 106                        None,
 107                        true,
 108                        window,
 109                        cx,
 110                    );
 111                    keymap_editor
 112                };
 113
 114                if let Some(filter) = filter {
 115                    keymap_editor.update(cx, |editor, cx| {
 116                        editor.filter_editor.update(cx, |editor, cx| {
 117                            editor.clear(window, cx);
 118                            editor.insert(&filter, window, cx);
 119                        });
 120                        if !editor.has_binding_for(&filter) {
 121                            open_binding_modal_after_loading(cx)
 122                        }
 123                    })
 124                }
 125            })
 126            .detach_and_log_err(cx);
 127    }
 128
 129    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 130        workspace
 131            .register_action(|workspace, _: &OpenKeymap, window, cx| {
 132                open_keymap_editor(None, workspace, window, cx);
 133            })
 134            .register_action(|workspace, action: &ChangeKeybinding, window, cx| {
 135                open_keymap_editor(Some(action.action.clone()), workspace, window, cx);
 136            });
 137    })
 138    .detach();
 139
 140    register_serializable_item::<KeymapEditor>(cx);
 141}
 142
 143fn open_binding_modal_after_loading(cx: &mut Context<KeymapEditor>) {
 144    let started_at = Instant::now();
 145    let observer = Rc::new(RefCell::new(None));
 146    let handle = {
 147        let observer = Rc::clone(&observer);
 148        cx.observe(&cx.entity(), move |editor, _, cx| {
 149            let subscription = observer.borrow_mut().take();
 150
 151            if started_at.elapsed().as_secs() > 10 {
 152                return;
 153            }
 154            if !editor.matches.is_empty() {
 155                editor.selected_index = Some(0);
 156                cx.dispatch_action(&CreateBinding);
 157                return;
 158            }
 159
 160            *observer.borrow_mut() = subscription;
 161        })
 162    };
 163    *observer.borrow_mut() = Some(handle);
 164}
 165
 166pub struct KeymapEventChannel {}
 167
 168impl Global for KeymapEventChannel {}
 169
 170impl KeymapEventChannel {
 171    fn new() -> Self {
 172        Self {}
 173    }
 174
 175    pub fn trigger_keymap_changed(cx: &mut App) {
 176        let Some(_event_channel) = cx.try_global::<Self>() else {
 177            // don't panic if no global defined. This usually happens in tests
 178            return;
 179        };
 180        cx.update_global(|_event_channel: &mut Self, _| {
 181            /* triggers observers in KeymapEditors */
 182        });
 183    }
 184}
 185
 186#[derive(Default, PartialEq)]
 187enum SearchMode {
 188    #[default]
 189    Normal,
 190    KeyStroke {
 191        exact_match: bool,
 192    },
 193}
 194
 195impl SearchMode {
 196    fn invert(&self) -> Self {
 197        match self {
 198            SearchMode::Normal => SearchMode::KeyStroke { exact_match: true },
 199            SearchMode::KeyStroke { .. } => SearchMode::Normal,
 200        }
 201    }
 202
 203    fn exact_match(&self) -> bool {
 204        match self {
 205            SearchMode::Normal => false,
 206            SearchMode::KeyStroke { exact_match } => *exact_match,
 207        }
 208    }
 209}
 210
 211#[derive(Default, PartialEq, Copy, Clone)]
 212enum FilterState {
 213    #[default]
 214    All,
 215    Conflicts,
 216}
 217
 218impl FilterState {
 219    fn invert(&self) -> Self {
 220        match self {
 221            FilterState::All => FilterState::Conflicts,
 222            FilterState::Conflicts => FilterState::All,
 223        }
 224    }
 225}
 226
 227#[derive(Debug, Default, PartialEq, Eq, Clone, Hash)]
 228struct ActionMapping {
 229    keystrokes: Rc<[KeybindingKeystroke]>,
 230    context: Option<SharedString>,
 231}
 232
 233#[derive(Debug)]
 234struct KeybindConflict {
 235    first_conflict_index: usize,
 236    remaining_conflict_amount: usize,
 237}
 238
 239#[derive(Clone, Copy, PartialEq)]
 240struct ConflictOrigin {
 241    override_source: KeybindSource,
 242    overridden_source: Option<KeybindSource>,
 243    index: usize,
 244}
 245
 246impl ConflictOrigin {
 247    fn new(source: KeybindSource, index: usize) -> Self {
 248        Self {
 249            override_source: source,
 250            index,
 251            overridden_source: None,
 252        }
 253    }
 254
 255    fn with_overridden_source(self, source: KeybindSource) -> Self {
 256        Self {
 257            overridden_source: Some(source),
 258            ..self
 259        }
 260    }
 261
 262    fn get_conflict_with(&self, other: &Self) -> Option<Self> {
 263        if self.override_source == KeybindSource::User
 264            && other.override_source == KeybindSource::User
 265        {
 266            Some(
 267                Self::new(KeybindSource::User, other.index)
 268                    .with_overridden_source(self.override_source),
 269            )
 270        } else if self.override_source > other.override_source {
 271            Some(other.with_overridden_source(self.override_source))
 272        } else {
 273            None
 274        }
 275    }
 276
 277    fn is_user_keybind_conflict(&self) -> bool {
 278        self.override_source == KeybindSource::User
 279            && self.overridden_source == Some(KeybindSource::User)
 280    }
 281}
 282
 283#[derive(Default)]
 284struct ConflictState {
 285    conflicts: Vec<Option<ConflictOrigin>>,
 286    keybind_mapping: ConflictKeybindMapping,
 287    has_user_conflicts: bool,
 288}
 289
 290type ConflictKeybindMapping = HashMap<
 291    Rc<[KeybindingKeystroke]>,
 292    Vec<(
 293        Option<gpui::KeyBindingContextPredicate>,
 294        Vec<ConflictOrigin>,
 295    )>,
 296>;
 297
 298impl ConflictState {
 299    fn new(key_bindings: &[ProcessedBinding]) -> Self {
 300        let mut action_keybind_mapping = ConflictKeybindMapping::default();
 301
 302        let mut largest_index = 0;
 303        for (index, binding) in key_bindings
 304            .iter()
 305            .enumerate()
 306            .flat_map(|(index, binding)| Some(index).zip(binding.keybind_information()))
 307        {
 308            let mapping = binding.get_action_mapping();
 309            let predicate = mapping
 310                .context
 311                .and_then(|ctx| gpui::KeyBindingContextPredicate::parse(&ctx).ok());
 312            let entry = action_keybind_mapping
 313                .entry(mapping.keystrokes.clone())
 314                .or_default();
 315            let origin = ConflictOrigin::new(binding.source, index);
 316            if let Some((_, origins)) =
 317                entry
 318                    .iter_mut()
 319                    .find(|(other_predicate, _)| match (&predicate, other_predicate) {
 320                        (None, None) => true,
 321                        (Some(a), Some(b)) => normalized_ctx_eq(a, b),
 322                        _ => false,
 323                    })
 324            {
 325                origins.push(origin);
 326            } else {
 327                entry.push((predicate, vec![origin]));
 328            }
 329            largest_index = index;
 330        }
 331
 332        let mut conflicts = vec![None; largest_index + 1];
 333        let mut has_user_conflicts = false;
 334
 335        for entries in action_keybind_mapping.values_mut() {
 336            for (_, indices) in entries.iter_mut() {
 337                indices.sort_unstable_by_key(|origin| origin.override_source);
 338                let Some((fst, snd)) = indices.get(0).zip(indices.get(1)) else {
 339                    continue;
 340                };
 341
 342                for origin in indices.iter() {
 343                    conflicts[origin.index] =
 344                        origin.get_conflict_with(if origin == fst { snd } else { fst })
 345                }
 346
 347                has_user_conflicts |= fst.override_source == KeybindSource::User
 348                    && snd.override_source == KeybindSource::User;
 349            }
 350        }
 351
 352        Self {
 353            conflicts,
 354            keybind_mapping: action_keybind_mapping,
 355            has_user_conflicts,
 356        }
 357    }
 358
 359    fn conflicting_indices_for_mapping(
 360        &self,
 361        action_mapping: &ActionMapping,
 362        keybind_idx: Option<usize>,
 363    ) -> Option<KeybindConflict> {
 364        let ActionMapping {
 365            keystrokes,
 366            context,
 367        } = action_mapping;
 368        let predicate = context
 369            .as_deref()
 370            .and_then(|ctx| gpui::KeyBindingContextPredicate::parse(&ctx).ok());
 371        self.keybind_mapping.get(keystrokes).and_then(|entries| {
 372            entries
 373                .iter()
 374                .find_map(|(other_predicate, indices)| {
 375                    match (&predicate, other_predicate) {
 376                        (None, None) => true,
 377                        (Some(pred), Some(other)) => normalized_ctx_eq(pred, other),
 378                        _ => false,
 379                    }
 380                    .then_some(indices)
 381                })
 382                .and_then(|indices| {
 383                    let mut indices = indices
 384                        .iter()
 385                        .filter(|&conflict| Some(conflict.index) != keybind_idx);
 386                    indices.next().map(|origin| KeybindConflict {
 387                        first_conflict_index: origin.index,
 388                        remaining_conflict_amount: indices.count(),
 389                    })
 390                })
 391        })
 392    }
 393
 394    fn conflict_for_idx(&self, idx: usize) -> Option<ConflictOrigin> {
 395        self.conflicts.get(idx).copied().flatten()
 396    }
 397
 398    fn has_user_conflict(&self, candidate_idx: usize) -> bool {
 399        self.conflict_for_idx(candidate_idx)
 400            .is_some_and(|conflict| conflict.is_user_keybind_conflict())
 401    }
 402
 403    fn any_user_binding_conflicts(&self) -> bool {
 404        self.has_user_conflicts
 405    }
 406}
 407
 408struct KeymapEditor {
 409    workspace: WeakEntity<Workspace>,
 410    focus_handle: FocusHandle,
 411    _keymap_subscription: Subscription,
 412    keybindings: Vec<ProcessedBinding>,
 413    keybinding_conflict_state: ConflictState,
 414    filter_state: FilterState,
 415    search_mode: SearchMode,
 416    search_query_debounce: Option<Task<()>>,
 417    // corresponds 1 to 1 with keybindings
 418    string_match_candidates: Arc<Vec<StringMatchCandidate>>,
 419    matches: Vec<StringMatch>,
 420    table_interaction_state: Entity<TableInteractionState>,
 421    filter_editor: Entity<Editor>,
 422    keystroke_editor: Entity<KeystrokeInput>,
 423    selected_index: Option<usize>,
 424    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 425    previous_edit: Option<PreviousEdit>,
 426    humanized_action_names: HumanizedActionNameCache,
 427    current_widths: Entity<TableColumnWidths<6>>,
 428    show_hover_menus: bool,
 429    /// In order for the JSON LSP to run in the actions arguments editor, we
 430    /// require a backing file In order to avoid issues (primarily log spam)
 431    /// with drop order between the buffer, file, worktree, etc, we create a
 432    /// temporary directory for these backing files in the keymap editor struct
 433    /// instead of here. This has the added benefit of only having to create a
 434    /// worktree and directory once, although the perf improvement is negligible.
 435    action_args_temp_dir_worktree: Option<Entity<project::Worktree>>,
 436    action_args_temp_dir: Option<tempfile::TempDir>,
 437}
 438
 439enum PreviousEdit {
 440    /// When deleting, we want to maintain the same scroll position
 441    ScrollBarOffset(Point<Pixels>),
 442    /// When editing or creating, because the new keybinding could be in a different position in the sort order
 443    /// we store metadata about the new binding (either the modified version or newly created one)
 444    /// and upon reload, we search for this binding in the list of keybindings, and if we find the one that matches
 445    /// this metadata, we set the selected index to it and scroll to it,
 446    /// and if we don't find it, we scroll to 0 and don't set a selected index
 447    Keybinding {
 448        action_mapping: ActionMapping,
 449        action_name: &'static str,
 450        /// The scrollbar position to fallback to if we don't find the keybinding during a refresh
 451        /// this can happen if there's a filter applied to the search and the keybinding modification
 452        /// filters the binding from the search results
 453        fallback: Point<Pixels>,
 454    },
 455}
 456
 457impl EventEmitter<()> for KeymapEditor {}
 458
 459impl Focusable for KeymapEditor {
 460    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 461        if self.selected_index.is_some() {
 462            self.focus_handle.clone()
 463        } else {
 464            self.filter_editor.focus_handle(cx)
 465        }
 466    }
 467}
 468/// Helper function to check if two keystroke sequences match exactly
 469fn keystrokes_match_exactly(
 470    keystrokes1: &[KeybindingKeystroke],
 471    keystrokes2: &[KeybindingKeystroke],
 472) -> bool {
 473    keystrokes1.len() == keystrokes2.len()
 474        && keystrokes1.iter().zip(keystrokes2).all(|(k1, k2)| {
 475            k1.inner().key == k2.inner().key && k1.inner().modifiers == k2.inner().modifiers
 476        })
 477}
 478
 479impl KeymapEditor {
 480    fn new(workspace: WeakEntity<Workspace>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 481        let _keymap_subscription =
 482            cx.observe_global_in::<KeymapEventChannel>(window, Self::on_keymap_changed);
 483        let table_interaction_state = cx.new(|cx| {
 484            TableInteractionState::new(cx)
 485                .with_custom_scrollbar(ui::Scrollbars::for_settings::<editor::EditorSettings>())
 486        });
 487
 488        let keystroke_editor = cx.new(|cx| {
 489            let mut keystroke_editor = KeystrokeInput::new(None, window, cx);
 490            keystroke_editor.set_search(true);
 491            keystroke_editor
 492        });
 493
 494        let filter_editor = cx.new(|cx| {
 495            let mut editor = Editor::single_line(window, cx);
 496            editor.set_placeholder_text("Filter action names…", window, cx);
 497            editor
 498        });
 499
 500        cx.subscribe(&filter_editor, |this, _, e: &EditorEvent, cx| {
 501            if !matches!(e, EditorEvent::BufferEdited) {
 502                return;
 503            }
 504
 505            this.on_query_changed(cx);
 506        })
 507        .detach();
 508
 509        cx.subscribe(&keystroke_editor, |this, _, _, cx| {
 510            if matches!(this.search_mode, SearchMode::Normal) {
 511                return;
 512            }
 513
 514            this.on_query_changed(cx);
 515        })
 516        .detach();
 517
 518        cx.spawn({
 519            let workspace = workspace.clone();
 520            async move |this, cx| {
 521                let temp_dir = tempfile::tempdir_in(paths::temp_dir())?;
 522                let worktree = workspace
 523                    .update(cx, |ws, cx| {
 524                        ws.project()
 525                            .update(cx, |p, cx| p.create_worktree(temp_dir.path(), false, cx))
 526                    })?
 527                    .await?;
 528                this.update(cx, |this, _| {
 529                    this.action_args_temp_dir = Some(temp_dir);
 530                    this.action_args_temp_dir_worktree = Some(worktree);
 531                })
 532            }
 533        })
 534        .detach();
 535
 536        let mut this = Self {
 537            workspace,
 538            keybindings: vec![],
 539            keybinding_conflict_state: ConflictState::default(),
 540            filter_state: FilterState::default(),
 541            search_mode: SearchMode::default(),
 542            string_match_candidates: Arc::new(vec![]),
 543            matches: vec![],
 544            focus_handle: cx.focus_handle(),
 545            _keymap_subscription,
 546            table_interaction_state,
 547            filter_editor,
 548            keystroke_editor,
 549            selected_index: None,
 550            context_menu: None,
 551            previous_edit: None,
 552            search_query_debounce: None,
 553            humanized_action_names: HumanizedActionNameCache::new(cx),
 554            show_hover_menus: true,
 555            action_args_temp_dir: None,
 556            action_args_temp_dir_worktree: None,
 557            current_widths: cx.new(|cx| TableColumnWidths::new(cx)),
 558        };
 559
 560        this.on_keymap_changed(window, cx);
 561
 562        this
 563    }
 564
 565    fn current_action_query(&self, cx: &App) -> String {
 566        self.filter_editor.read(cx).text(cx)
 567    }
 568
 569    fn current_keystroke_query(&self, cx: &App) -> Vec<KeybindingKeystroke> {
 570        match self.search_mode {
 571            SearchMode::KeyStroke { .. } => self.keystroke_editor.read(cx).keystrokes().to_vec(),
 572            SearchMode::Normal => Default::default(),
 573        }
 574    }
 575
 576    fn clear_action_query(&self, window: &mut Window, cx: &mut Context<Self>) {
 577        self.filter_editor
 578            .update(cx, |editor, cx| editor.clear(window, cx))
 579    }
 580
 581    fn on_query_changed(&mut self, cx: &mut Context<Self>) {
 582        let action_query = self.current_action_query(cx);
 583        let keystroke_query = self.current_keystroke_query(cx);
 584        let exact_match = self.search_mode.exact_match();
 585
 586        let timer = cx.background_executor().timer(Duration::from_secs(1));
 587        self.search_query_debounce = Some(cx.background_spawn({
 588            let action_query = action_query.clone();
 589            let keystroke_query = keystroke_query.clone();
 590            async move {
 591                timer.await;
 592
 593                let keystroke_query = keystroke_query
 594                    .into_iter()
 595                    .map(|keystroke| keystroke.inner().unparse())
 596                    .collect::<Vec<String>>()
 597                    .join(" ");
 598
 599                telemetry::event!(
 600                    "Keystroke Search Completed",
 601                    action_query = action_query,
 602                    keystroke_query = keystroke_query,
 603                    keystroke_exact_match = exact_match
 604                )
 605            }
 606        }));
 607        cx.spawn(async move |this, cx| {
 608            Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
 609            this.update(cx, |this, cx| {
 610                this.scroll_to_item(0, ScrollStrategy::Top, cx)
 611            })
 612        })
 613        .detach();
 614    }
 615
 616    async fn update_matches(
 617        this: WeakEntity<Self>,
 618        action_query: String,
 619        keystroke_query: Vec<KeybindingKeystroke>,
 620        cx: &mut AsyncApp,
 621    ) -> anyhow::Result<()> {
 622        let action_query = command_palette::normalize_action_query(&action_query);
 623        let (string_match_candidates, keybind_count) = this.read_with(cx, |this, _| {
 624            (this.string_match_candidates.clone(), this.keybindings.len())
 625        })?;
 626        let executor = cx.background_executor().clone();
 627        let mut matches = fuzzy::match_strings(
 628            &string_match_candidates,
 629            &action_query,
 630            true,
 631            true,
 632            keybind_count,
 633            &Default::default(),
 634            executor,
 635        )
 636        .await;
 637        this.update(cx, |this, cx| {
 638            match this.filter_state {
 639                FilterState::Conflicts => {
 640                    matches.retain(|candidate| {
 641                        this.keybinding_conflict_state
 642                            .has_user_conflict(candidate.candidate_id)
 643                    });
 644                }
 645                FilterState::All => {}
 646            }
 647
 648            match this.search_mode {
 649                SearchMode::KeyStroke { exact_match } => {
 650                    matches.retain(|item| {
 651                        this.keybindings[item.candidate_id]
 652                            .keystrokes()
 653                            .is_some_and(|keystrokes| {
 654                                if exact_match {
 655                                    keystrokes_match_exactly(&keystroke_query, keystrokes)
 656                                } else if keystroke_query.len() > keystrokes.len() {
 657                                    false
 658                                } else {
 659                                    for keystroke_offset in 0..keystrokes.len() {
 660                                        let mut found_count = 0;
 661                                        let mut query_cursor = 0;
 662                                        let mut keystroke_cursor = keystroke_offset;
 663                                        while query_cursor < keystroke_query.len()
 664                                            && keystroke_cursor < keystrokes.len()
 665                                        {
 666                                            let query = &keystroke_query[query_cursor];
 667                                            let keystroke = &keystrokes[keystroke_cursor];
 668                                            let matches = query
 669                                                .inner()
 670                                                .modifiers
 671                                                .is_subset_of(&keystroke.inner().modifiers)
 672                                                && ((query.inner().key.is_empty()
 673                                                    || query.inner().key == keystroke.inner().key)
 674                                                    && query.inner().key_char.as_ref().is_none_or(
 675                                                        |q_kc| q_kc == &keystroke.inner().key,
 676                                                    ));
 677                                            if matches {
 678                                                found_count += 1;
 679                                                query_cursor += 1;
 680                                            }
 681                                            keystroke_cursor += 1;
 682                                        }
 683
 684                                        if found_count == keystroke_query.len() {
 685                                            return true;
 686                                        }
 687                                    }
 688                                    false
 689                                }
 690                            })
 691                    });
 692                }
 693                SearchMode::Normal => {}
 694            }
 695
 696            if action_query.is_empty() {
 697                matches.sort_by(|item1, item2| {
 698                    let binding1 = &this.keybindings[item1.candidate_id];
 699                    let binding2 = &this.keybindings[item2.candidate_id];
 700
 701                    binding1.cmp(binding2)
 702                });
 703            }
 704            this.selected_index.take();
 705            this.matches = matches;
 706
 707            cx.notify();
 708        })
 709    }
 710
 711    fn get_conflict(&self, row_index: usize) -> Option<ConflictOrigin> {
 712        self.matches.get(row_index).and_then(|candidate| {
 713            self.keybinding_conflict_state
 714                .conflict_for_idx(candidate.candidate_id)
 715        })
 716    }
 717
 718    fn process_bindings(
 719        json_language: Arc<Language>,
 720        zed_keybind_context_language: Arc<Language>,
 721        humanized_action_names: &HumanizedActionNameCache,
 722        cx: &mut App,
 723    ) -> (Vec<ProcessedBinding>, Vec<StringMatchCandidate>) {
 724        let key_bindings_ptr = cx.key_bindings();
 725        let lock = key_bindings_ptr.borrow();
 726        let key_bindings = lock.bindings();
 727        let mut unmapped_action_names = HashSet::from_iter(cx.all_action_names().iter().copied());
 728        let action_documentation = cx.action_documentation();
 729        let mut generator = KeymapFile::action_schema_generator();
 730        let actions_with_schemas = HashSet::from_iter(
 731            cx.action_schemas(&mut generator)
 732                .into_iter()
 733                .filter_map(|(name, schema)| schema.is_some().then_some(name)),
 734        );
 735
 736        let mut processed_bindings = Vec::new();
 737        let mut string_match_candidates = Vec::new();
 738
 739        for key_binding in key_bindings {
 740            let source = key_binding
 741                .meta()
 742                .map(KeybindSource::from_meta)
 743                .unwrap_or(KeybindSource::Unknown);
 744
 745            let keystroke_text = ui::text_for_keybinding_keystrokes(key_binding.keystrokes(), cx);
 746            let binding = KeyBinding::new(key_binding, source);
 747
 748            let context = key_binding
 749                .predicate()
 750                .map(|predicate| {
 751                    KeybindContextString::Local(
 752                        predicate.to_string().into(),
 753                        zed_keybind_context_language.clone(),
 754                    )
 755                })
 756                .unwrap_or(KeybindContextString::Global);
 757
 758            let action_name = key_binding.action().name();
 759            unmapped_action_names.remove(&action_name);
 760
 761            let action_arguments = key_binding
 762                .action_input()
 763                .map(|arguments| SyntaxHighlightedText::new(arguments, json_language.clone()));
 764            let action_information = ActionInformation::new(
 765                action_name,
 766                action_arguments,
 767                &actions_with_schemas,
 768                action_documentation,
 769                humanized_action_names,
 770            );
 771
 772            let index = processed_bindings.len();
 773            let string_match_candidate =
 774                StringMatchCandidate::new(index, &action_information.humanized_name);
 775            processed_bindings.push(ProcessedBinding::new_mapped(
 776                keystroke_text,
 777                binding,
 778                context,
 779                source,
 780                action_information,
 781            ));
 782            string_match_candidates.push(string_match_candidate);
 783        }
 784
 785        for action_name in unmapped_action_names.into_iter() {
 786            let index = processed_bindings.len();
 787            let action_information = ActionInformation::new(
 788                action_name,
 789                None,
 790                &actions_with_schemas,
 791                action_documentation,
 792                humanized_action_names,
 793            );
 794            let string_match_candidate =
 795                StringMatchCandidate::new(index, &action_information.humanized_name);
 796
 797            processed_bindings.push(ProcessedBinding::Unmapped(action_information));
 798            string_match_candidates.push(string_match_candidate);
 799        }
 800
 801        (processed_bindings, string_match_candidates)
 802    }
 803
 804    fn on_keymap_changed(&mut self, window: &mut Window, cx: &mut Context<KeymapEditor>) {
 805        let workspace = self.workspace.clone();
 806        cx.spawn_in(window, async move |this, cx| {
 807            let json_language = load_json_language(workspace.clone(), cx).await;
 808            let zed_keybind_context_language =
 809                load_keybind_context_language(workspace.clone(), cx).await;
 810
 811            let (action_query, keystroke_query) = this.update(cx, |this, cx| {
 812                let (key_bindings, string_match_candidates) = Self::process_bindings(
 813                    json_language,
 814                    zed_keybind_context_language,
 815                    &this.humanized_action_names,
 816                    cx,
 817                );
 818
 819                this.keybinding_conflict_state = ConflictState::new(&key_bindings);
 820
 821                this.keybindings = key_bindings;
 822                this.string_match_candidates = Arc::new(string_match_candidates);
 823                this.matches = this
 824                    .string_match_candidates
 825                    .iter()
 826                    .enumerate()
 827                    .map(|(ix, candidate)| StringMatch {
 828                        candidate_id: ix,
 829                        score: 0.0,
 830                        positions: vec![],
 831                        string: candidate.string.clone(),
 832                    })
 833                    .collect();
 834                (
 835                    this.current_action_query(cx),
 836                    this.current_keystroke_query(cx),
 837                )
 838            })?;
 839            // calls cx.notify
 840            Self::update_matches(this.clone(), action_query, keystroke_query, cx).await?;
 841            this.update_in(cx, |this, window, cx| {
 842                if let Some(previous_edit) = this.previous_edit.take() {
 843                    match previous_edit {
 844                        // should remove scroll from process_query
 845                        PreviousEdit::ScrollBarOffset(offset) => {
 846                            this.table_interaction_state
 847                                .update(cx, |table, _| table.set_scroll_offset(offset))
 848                            // set selected index and scroll
 849                        }
 850                        PreviousEdit::Keybinding {
 851                            action_mapping,
 852                            action_name,
 853                            fallback,
 854                        } => {
 855                            let scroll_position =
 856                                this.matches.iter().enumerate().find_map(|(index, item)| {
 857                                    let binding = &this.keybindings[item.candidate_id];
 858                                    if binding.get_action_mapping().is_some_and(|binding_mapping| {
 859                                        binding_mapping == action_mapping
 860                                    }) && binding.action().name == action_name
 861                                    {
 862                                        Some(index)
 863                                    } else {
 864                                        None
 865                                    }
 866                                });
 867
 868                            if let Some(scroll_position) = scroll_position {
 869                                this.select_index(
 870                                    scroll_position,
 871                                    Some(ScrollStrategy::Top),
 872                                    window,
 873                                    cx,
 874                                );
 875                            } else {
 876                                this.table_interaction_state
 877                                    .update(cx, |table, _| table.set_scroll_offset(fallback));
 878                            }
 879                            cx.notify();
 880                        }
 881                    }
 882                }
 883            })
 884        })
 885        .detach_and_log_err(cx);
 886    }
 887
 888    fn key_context(&self) -> KeyContext {
 889        let mut dispatch_context = KeyContext::new_with_defaults();
 890        dispatch_context.add("KeymapEditor");
 891        dispatch_context.add("menu");
 892
 893        dispatch_context
 894    }
 895
 896    fn scroll_to_item(&self, index: usize, strategy: ScrollStrategy, cx: &mut App) {
 897        let index = usize::min(index, self.matches.len().saturating_sub(1));
 898        self.table_interaction_state.update(cx, |this, _cx| {
 899            this.scroll_handle.scroll_to_item(index, strategy);
 900        });
 901    }
 902
 903    fn focus_search(
 904        &mut self,
 905        _: &search::FocusSearch,
 906        window: &mut Window,
 907        cx: &mut Context<Self>,
 908    ) {
 909        if !self
 910            .filter_editor
 911            .focus_handle(cx)
 912            .contains_focused(window, cx)
 913        {
 914            window.focus(&self.filter_editor.focus_handle(cx));
 915        } else {
 916            self.filter_editor.update(cx, |editor, cx| {
 917                editor.select_all(&Default::default(), window, cx);
 918            });
 919        }
 920        self.selected_index.take();
 921    }
 922
 923    fn selected_keybind_index(&self) -> Option<usize> {
 924        self.selected_index
 925            .and_then(|match_index| self.matches.get(match_index))
 926            .map(|r#match| r#match.candidate_id)
 927    }
 928
 929    fn selected_keybind_and_index(&self) -> Option<(&ProcessedBinding, usize)> {
 930        self.selected_keybind_index()
 931            .map(|keybind_index| (&self.keybindings[keybind_index], keybind_index))
 932    }
 933
 934    fn selected_binding(&self) -> Option<&ProcessedBinding> {
 935        self.selected_keybind_index()
 936            .and_then(|keybind_index| self.keybindings.get(keybind_index))
 937    }
 938
 939    fn select_index(
 940        &mut self,
 941        index: usize,
 942        scroll: Option<ScrollStrategy>,
 943        window: &mut Window,
 944        cx: &mut Context<Self>,
 945    ) {
 946        if self.selected_index != Some(index) {
 947            self.selected_index = Some(index);
 948            if let Some(scroll_strategy) = scroll {
 949                self.scroll_to_item(index, scroll_strategy, cx);
 950            }
 951            window.focus(&self.focus_handle);
 952            cx.notify();
 953        }
 954    }
 955
 956    fn create_context_menu(
 957        &mut self,
 958        position: Point<Pixels>,
 959        window: &mut Window,
 960        cx: &mut Context<Self>,
 961    ) {
 962        self.context_menu = self.selected_binding().map(|selected_binding| {
 963            let selected_binding_has_no_context = selected_binding
 964                .context()
 965                .and_then(KeybindContextString::local)
 966                .is_none();
 967
 968            let selected_binding_is_unbound = selected_binding.is_unbound();
 969
 970            let context_menu = ContextMenu::build(window, cx, |menu, _window, _cx| {
 971                menu.context(self.focus_handle.clone())
 972                    .when(selected_binding_is_unbound, |this| {
 973                        this.action("Create", Box::new(CreateBinding))
 974                    })
 975                    .action_disabled_when(
 976                        selected_binding_is_unbound,
 977                        "Edit",
 978                        Box::new(EditBinding),
 979                    )
 980                    .action_disabled_when(
 981                        selected_binding_is_unbound,
 982                        "Delete",
 983                        Box::new(DeleteBinding),
 984                    )
 985                    .separator()
 986                    .action("Copy Action", Box::new(CopyAction))
 987                    .action_disabled_when(
 988                        selected_binding_has_no_context,
 989                        "Copy Context",
 990                        Box::new(CopyContext),
 991                    )
 992                    .separator()
 993                    .action_disabled_when(
 994                        selected_binding_has_no_context,
 995                        "Show Matching Keybindings",
 996                        Box::new(ShowMatchingKeybinds),
 997                    )
 998            });
 999
1000            let context_menu_handle = context_menu.focus_handle(cx);
1001            window.defer(cx, move |window, _cx| window.focus(&context_menu_handle));
1002            let subscription = cx.subscribe_in(
1003                &context_menu,
1004                window,
1005                |this, _, _: &DismissEvent, window, cx| {
1006                    this.dismiss_context_menu(window, cx);
1007                },
1008            );
1009            (context_menu, position, subscription)
1010        });
1011
1012        cx.notify();
1013    }
1014
1015    fn dismiss_context_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1016        self.context_menu.take();
1017        window.focus(&self.focus_handle);
1018        cx.notify();
1019    }
1020
1021    fn context_menu_deployed(&self) -> bool {
1022        self.context_menu.is_some()
1023    }
1024
1025    fn create_row_button(
1026        &self,
1027        index: usize,
1028        conflict: Option<ConflictOrigin>,
1029        cx: &mut Context<Self>,
1030    ) -> IconButton {
1031        if self.filter_state != FilterState::Conflicts
1032            && let Some(conflict) = conflict
1033        {
1034            if conflict.is_user_keybind_conflict() {
1035                base_button_style(index, IconName::Warning)
1036                    .icon_color(Color::Warning)
1037                    .tooltip(|_window, cx| {
1038                        Tooltip::with_meta(
1039                            "View conflicts",
1040                            Some(&ToggleConflictFilter),
1041                            "Use alt+click to show all conflicts",
1042                            cx,
1043                        )
1044                    })
1045                    .on_click(cx.listener(move |this, click: &ClickEvent, window, cx| {
1046                        if click.modifiers().alt {
1047                            this.set_filter_state(FilterState::Conflicts, cx);
1048                        } else {
1049                            this.select_index(index, None, window, cx);
1050                            this.open_edit_keybinding_modal(false, window, cx);
1051                            cx.stop_propagation();
1052                        }
1053                    }))
1054            } else if self.search_mode.exact_match() {
1055                base_button_style(index, IconName::Info)
1056                    .tooltip(|_window, cx| {
1057                        Tooltip::with_meta(
1058                            "Edit this binding",
1059                            Some(&ShowMatchingKeybinds),
1060                            "This binding is overridden by other bindings.",
1061                            cx,
1062                        )
1063                    })
1064                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
1065                        this.select_index(index, None, window, cx);
1066                        this.open_edit_keybinding_modal(false, window, cx);
1067                        cx.stop_propagation();
1068                    }))
1069            } else {
1070                base_button_style(index, IconName::Info)
1071                    .tooltip(|_window, cx|  {
1072                        Tooltip::with_meta(
1073                            "Show matching keybinds",
1074                            Some(&ShowMatchingKeybinds),
1075                            "This binding is overridden by other bindings.\nUse alt+click to edit this binding",
1076                            cx,
1077                        )
1078                    })
1079                    .on_click(cx.listener(move |this, click: &ClickEvent, window, cx| {
1080                        if click.modifiers().alt {
1081                            this.select_index(index, None, window, cx);
1082                            this.open_edit_keybinding_modal(false, window, cx);
1083                            cx.stop_propagation();
1084                        } else {
1085                            this.show_matching_keystrokes(&Default::default(), window, cx);
1086                        }
1087                    }))
1088            }
1089        } else {
1090            base_button_style(index, IconName::Pencil)
1091                .visible_on_hover(if self.selected_index == Some(index) {
1092                    "".into()
1093                } else if self.show_hover_menus {
1094                    row_group_id(index)
1095                } else {
1096                    "never-show".into()
1097                })
1098                .when(
1099                    self.show_hover_menus && !self.context_menu_deployed(),
1100                    |this| this.tooltip(Tooltip::for_action_title("Edit Keybinding", &EditBinding)),
1101                )
1102                .on_click(cx.listener(move |this, _, window, cx| {
1103                    this.select_index(index, None, window, cx);
1104                    this.open_edit_keybinding_modal(false, window, cx);
1105                    cx.stop_propagation();
1106                }))
1107        }
1108    }
1109
1110    fn render_no_matches_hint(&self, _window: &mut Window, _cx: &App) -> AnyElement {
1111        let hint = match (self.filter_state, &self.search_mode) {
1112            (FilterState::Conflicts, _) => {
1113                if self.keybinding_conflict_state.any_user_binding_conflicts() {
1114                    "No conflicting keybinds found that match the provided query"
1115                } else {
1116                    "No conflicting keybinds found"
1117                }
1118            }
1119            (FilterState::All, SearchMode::KeyStroke { .. }) => {
1120                "No keybinds found matching the entered keystrokes"
1121            }
1122            (FilterState::All, SearchMode::Normal) => "No matches found for the provided query",
1123        };
1124
1125        Label::new(hint).color(Color::Muted).into_any_element()
1126    }
1127
1128    fn select_next(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1129        self.show_hover_menus = false;
1130        if let Some(selected) = self.selected_index {
1131            let selected = selected + 1;
1132            if selected >= self.matches.len() {
1133                self.select_last(&Default::default(), window, cx);
1134            } else {
1135                self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
1136            }
1137        } else {
1138            self.select_first(&Default::default(), window, cx);
1139        }
1140    }
1141
1142    fn select_previous(
1143        &mut self,
1144        _: &menu::SelectPrevious,
1145        window: &mut Window,
1146        cx: &mut Context<Self>,
1147    ) {
1148        self.show_hover_menus = false;
1149        if let Some(selected) = self.selected_index {
1150            if selected == 0 {
1151                return;
1152            }
1153
1154            let selected = selected - 1;
1155
1156            if selected >= self.matches.len() {
1157                self.select_last(&Default::default(), window, cx);
1158            } else {
1159                self.select_index(selected, Some(ScrollStrategy::Center), window, cx);
1160            }
1161        } else {
1162            self.select_last(&Default::default(), window, cx);
1163        }
1164    }
1165
1166    fn select_first(&mut self, _: &menu::SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
1167        self.show_hover_menus = false;
1168        if self.matches.get(0).is_some() {
1169            self.select_index(0, Some(ScrollStrategy::Center), window, cx);
1170        }
1171    }
1172
1173    fn select_last(&mut self, _: &menu::SelectLast, window: &mut Window, cx: &mut Context<Self>) {
1174        self.show_hover_menus = false;
1175        if self.matches.last().is_some() {
1176            let index = self.matches.len() - 1;
1177            self.select_index(index, Some(ScrollStrategy::Center), window, cx);
1178        }
1179    }
1180
1181    fn open_edit_keybinding_modal(
1182        &mut self,
1183        create: bool,
1184        window: &mut Window,
1185        cx: &mut Context<Self>,
1186    ) {
1187        self.show_hover_menus = false;
1188        let Some((keybind, keybind_index)) = self.selected_keybind_and_index() else {
1189            return;
1190        };
1191        let keybind = keybind.clone();
1192        let keymap_editor = cx.entity();
1193
1194        let keystroke = keybind.keystroke_text().cloned().unwrap_or_default();
1195        let arguments = keybind
1196            .action()
1197            .arguments
1198            .as_ref()
1199            .map(|arguments| arguments.text.clone());
1200        let context = keybind
1201            .context()
1202            .map(|context| context.local_str().unwrap_or("global"));
1203        let action = keybind.action().name;
1204        let source = keybind.keybind_source().map(|source| source.name());
1205
1206        telemetry::event!(
1207            "Edit Keybinding Modal Opened",
1208            keystroke = keystroke,
1209            action = action,
1210            source = source,
1211            context = context,
1212            arguments = arguments,
1213        );
1214
1215        let temp_dir = self.action_args_temp_dir.as_ref().map(|dir| dir.path());
1216
1217        self.workspace
1218            .update(cx, |workspace, cx| {
1219                let fs = workspace.app_state().fs.clone();
1220                let workspace_weak = cx.weak_entity();
1221                workspace.toggle_modal(window, cx, |window, cx| {
1222                    let modal = KeybindingEditorModal::new(
1223                        create,
1224                        keybind,
1225                        keybind_index,
1226                        keymap_editor,
1227                        temp_dir,
1228                        workspace_weak,
1229                        fs,
1230                        window,
1231                        cx,
1232                    );
1233                    window.focus(&modal.focus_handle(cx));
1234                    modal
1235                });
1236            })
1237            .log_err();
1238    }
1239
1240    fn edit_binding(&mut self, _: &EditBinding, window: &mut Window, cx: &mut Context<Self>) {
1241        self.open_edit_keybinding_modal(false, window, cx);
1242    }
1243
1244    fn create_binding(&mut self, _: &CreateBinding, window: &mut Window, cx: &mut Context<Self>) {
1245        self.open_edit_keybinding_modal(true, window, cx);
1246    }
1247
1248    fn delete_binding(&mut self, _: &DeleteBinding, window: &mut Window, cx: &mut Context<Self>) {
1249        let Some(to_remove) = self.selected_binding().cloned() else {
1250            return;
1251        };
1252
1253        let std::result::Result::Ok(fs) = self
1254            .workspace
1255            .read_with(cx, |workspace, _| workspace.app_state().fs.clone())
1256        else {
1257            return;
1258        };
1259        self.previous_edit = Some(PreviousEdit::ScrollBarOffset(
1260            self.table_interaction_state.read(cx).scroll_offset(),
1261        ));
1262        let keyboard_mapper = cx.keyboard_mapper().clone();
1263        cx.spawn(async move |_, _| {
1264            remove_keybinding(to_remove, &fs, keyboard_mapper.as_ref()).await
1265        })
1266        .detach_and_notify_err(window, cx);
1267    }
1268
1269    fn copy_context_to_clipboard(
1270        &mut self,
1271        _: &CopyContext,
1272        _window: &mut Window,
1273        cx: &mut Context<Self>,
1274    ) {
1275        let context = self
1276            .selected_binding()
1277            .and_then(|binding| binding.context())
1278            .and_then(KeybindContextString::local_str)
1279            .map(|context| context.to_string());
1280        let Some(context) = context else {
1281            return;
1282        };
1283
1284        telemetry::event!("Keybinding Context Copied", context = context);
1285        cx.write_to_clipboard(gpui::ClipboardItem::new_string(context));
1286    }
1287
1288    fn copy_action_to_clipboard(
1289        &mut self,
1290        _: &CopyAction,
1291        _window: &mut Window,
1292        cx: &mut Context<Self>,
1293    ) {
1294        let action = self
1295            .selected_binding()
1296            .map(|binding| binding.action().name.to_string());
1297        let Some(action) = action else {
1298            return;
1299        };
1300
1301        telemetry::event!("Keybinding Action Copied", action = action);
1302        cx.write_to_clipboard(gpui::ClipboardItem::new_string(action));
1303    }
1304
1305    fn toggle_conflict_filter(
1306        &mut self,
1307        _: &ToggleConflictFilter,
1308        _: &mut Window,
1309        cx: &mut Context<Self>,
1310    ) {
1311        self.set_filter_state(self.filter_state.invert(), cx);
1312    }
1313
1314    fn set_filter_state(&mut self, filter_state: FilterState, cx: &mut Context<Self>) {
1315        if self.filter_state != filter_state {
1316            self.filter_state = filter_state;
1317            self.on_query_changed(cx);
1318        }
1319    }
1320
1321    fn toggle_keystroke_search(
1322        &mut self,
1323        _: &ToggleKeystrokeSearch,
1324        window: &mut Window,
1325        cx: &mut Context<Self>,
1326    ) {
1327        self.search_mode = self.search_mode.invert();
1328        self.on_query_changed(cx);
1329
1330        match self.search_mode {
1331            SearchMode::KeyStroke { .. } => {
1332                self.keystroke_editor.update(cx, |editor, cx| {
1333                    editor.start_recording(&StartRecording, window, cx);
1334                });
1335            }
1336            SearchMode::Normal => {
1337                self.keystroke_editor.update(cx, |editor, cx| {
1338                    editor.stop_recording(&StopRecording, window, cx);
1339                    editor.clear_keystrokes(&ClearKeystrokes, window, cx);
1340                });
1341                window.focus(&self.filter_editor.focus_handle(cx));
1342            }
1343        }
1344    }
1345
1346    fn toggle_exact_keystroke_matching(
1347        &mut self,
1348        _: &ToggleExactKeystrokeMatching,
1349        _: &mut Window,
1350        cx: &mut Context<Self>,
1351    ) {
1352        let SearchMode::KeyStroke { exact_match } = &mut self.search_mode else {
1353            return;
1354        };
1355
1356        *exact_match = !(*exact_match);
1357        self.on_query_changed(cx);
1358    }
1359
1360    fn show_matching_keystrokes(
1361        &mut self,
1362        _: &ShowMatchingKeybinds,
1363        _: &mut Window,
1364        cx: &mut Context<Self>,
1365    ) {
1366        let Some(selected_binding) = self.selected_binding() else {
1367            return;
1368        };
1369
1370        let keystrokes = selected_binding
1371            .keystrokes()
1372            .map(Vec::from)
1373            .unwrap_or_default();
1374
1375        self.filter_state = FilterState::All;
1376        self.search_mode = SearchMode::KeyStroke { exact_match: true };
1377
1378        self.keystroke_editor.update(cx, |editor, cx| {
1379            editor.set_keystrokes(keystrokes, cx);
1380        });
1381    }
1382
1383    fn has_binding_for(&self, action_name: &str) -> bool {
1384        self.keybindings
1385            .iter()
1386            .filter(|kb| kb.keystrokes().is_some())
1387            .any(|kb| kb.action().name == action_name)
1388    }
1389}
1390
1391struct HumanizedActionNameCache {
1392    cache: HashMap<&'static str, SharedString>,
1393}
1394
1395impl HumanizedActionNameCache {
1396    fn new(cx: &App) -> Self {
1397        let cache = HashMap::from_iter(cx.all_action_names().iter().map(|&action_name| {
1398            (
1399                action_name,
1400                command_palette::humanize_action_name(action_name).into(),
1401            )
1402        }));
1403        Self { cache }
1404    }
1405
1406    fn get(&self, action_name: &'static str) -> SharedString {
1407        match self.cache.get(action_name) {
1408            Some(name) => name.clone(),
1409            None => action_name.into(),
1410        }
1411    }
1412}
1413
1414#[derive(Clone)]
1415struct KeyBinding {
1416    keystrokes: Rc<[KeybindingKeystroke]>,
1417    source: KeybindSource,
1418}
1419
1420impl KeyBinding {
1421    fn new(binding: &gpui::KeyBinding, source: KeybindSource) -> Self {
1422        Self {
1423            keystrokes: Rc::from(binding.keystrokes()),
1424            source,
1425        }
1426    }
1427}
1428
1429#[derive(Clone)]
1430struct KeybindInformation {
1431    keystroke_text: SharedString,
1432    binding: KeyBinding,
1433    context: KeybindContextString,
1434    source: KeybindSource,
1435}
1436
1437impl KeybindInformation {
1438    fn get_action_mapping(&self) -> ActionMapping {
1439        ActionMapping {
1440            keystrokes: self.binding.keystrokes.clone(),
1441            context: self.context.local().cloned(),
1442        }
1443    }
1444}
1445
1446#[derive(Clone)]
1447struct ActionInformation {
1448    name: &'static str,
1449    humanized_name: SharedString,
1450    arguments: Option<SyntaxHighlightedText>,
1451    documentation: Option<&'static str>,
1452    has_schema: bool,
1453}
1454
1455impl ActionInformation {
1456    fn new(
1457        action_name: &'static str,
1458        action_arguments: Option<SyntaxHighlightedText>,
1459        actions_with_schemas: &HashSet<&'static str>,
1460        action_documentation: &HashMap<&'static str, &'static str>,
1461        action_name_cache: &HumanizedActionNameCache,
1462    ) -> Self {
1463        Self {
1464            humanized_name: action_name_cache.get(action_name),
1465            has_schema: actions_with_schemas.contains(action_name),
1466            arguments: action_arguments,
1467            documentation: action_documentation.get(action_name).copied(),
1468            name: action_name,
1469        }
1470    }
1471}
1472
1473#[derive(Clone)]
1474enum ProcessedBinding {
1475    Mapped(KeybindInformation, ActionInformation),
1476    Unmapped(ActionInformation),
1477}
1478
1479impl ProcessedBinding {
1480    fn new_mapped(
1481        keystroke_text: impl Into<SharedString>,
1482        binding: KeyBinding,
1483        context: KeybindContextString,
1484        source: KeybindSource,
1485        action_information: ActionInformation,
1486    ) -> Self {
1487        Self::Mapped(
1488            KeybindInformation {
1489                keystroke_text: keystroke_text.into(),
1490                binding,
1491                context,
1492                source,
1493            },
1494            action_information,
1495        )
1496    }
1497
1498    fn is_unbound(&self) -> bool {
1499        matches!(self, Self::Unmapped(_))
1500    }
1501
1502    fn get_action_mapping(&self) -> Option<ActionMapping> {
1503        self.keybind_information()
1504            .map(|keybind| keybind.get_action_mapping())
1505    }
1506
1507    fn keystrokes(&self) -> Option<&[KeybindingKeystroke]> {
1508        self.key_binding()
1509            .map(|binding| binding.keystrokes.as_ref())
1510    }
1511
1512    fn keybind_information(&self) -> Option<&KeybindInformation> {
1513        match self {
1514            Self::Mapped(keybind_information, _) => Some(keybind_information),
1515            Self::Unmapped(_) => None,
1516        }
1517    }
1518
1519    fn keybind_source(&self) -> Option<KeybindSource> {
1520        self.keybind_information().map(|keybind| keybind.source)
1521    }
1522
1523    fn context(&self) -> Option<&KeybindContextString> {
1524        self.keybind_information().map(|keybind| &keybind.context)
1525    }
1526
1527    fn key_binding(&self) -> Option<&KeyBinding> {
1528        self.keybind_information().map(|keybind| &keybind.binding)
1529    }
1530
1531    fn keystroke_text(&self) -> Option<&SharedString> {
1532        self.keybind_information()
1533            .map(|binding| &binding.keystroke_text)
1534    }
1535
1536    fn action(&self) -> &ActionInformation {
1537        match self {
1538            Self::Mapped(_, action) | Self::Unmapped(action) => action,
1539        }
1540    }
1541
1542    fn cmp(&self, other: &Self) -> cmp::Ordering {
1543        match (self, other) {
1544            (Self::Mapped(keybind1, action1), Self::Mapped(keybind2, action2)) => {
1545                match keybind1.source.cmp(&keybind2.source) {
1546                    cmp::Ordering::Equal => action1.humanized_name.cmp(&action2.humanized_name),
1547                    ordering => ordering,
1548                }
1549            }
1550            (Self::Mapped(_, _), Self::Unmapped(_)) => cmp::Ordering::Less,
1551            (Self::Unmapped(_), Self::Mapped(_, _)) => cmp::Ordering::Greater,
1552            (Self::Unmapped(action1), Self::Unmapped(action2)) => {
1553                action1.humanized_name.cmp(&action2.humanized_name)
1554            }
1555        }
1556    }
1557}
1558
1559#[derive(Clone, Debug, IntoElement, PartialEq, Eq, Hash)]
1560enum KeybindContextString {
1561    Global,
1562    Local(SharedString, Arc<Language>),
1563}
1564
1565impl KeybindContextString {
1566    const GLOBAL: SharedString = SharedString::new_static("<global>");
1567
1568    pub fn local(&self) -> Option<&SharedString> {
1569        match self {
1570            KeybindContextString::Global => None,
1571            KeybindContextString::Local(name, _) => Some(name),
1572        }
1573    }
1574
1575    pub fn local_str(&self) -> Option<&str> {
1576        match self {
1577            KeybindContextString::Global => None,
1578            KeybindContextString::Local(name, _) => Some(name),
1579        }
1580    }
1581}
1582
1583impl RenderOnce for KeybindContextString {
1584    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
1585        match self {
1586            KeybindContextString::Global => {
1587                muted_styled_text(KeybindContextString::GLOBAL, cx).into_any_element()
1588            }
1589            KeybindContextString::Local(name, language) => {
1590                SyntaxHighlightedText::new(name, language).into_any_element()
1591            }
1592        }
1593    }
1594}
1595
1596fn muted_styled_text(text: SharedString, cx: &App) -> StyledText {
1597    let len = text.len();
1598    StyledText::new(text).with_highlights([(
1599        0..len,
1600        gpui::HighlightStyle::color(cx.theme().colors().text_muted),
1601    )])
1602}
1603
1604impl Item for KeymapEditor {
1605    type Event = ();
1606
1607    fn tab_content_text(&self, _detail: usize, _cx: &App) -> ui::SharedString {
1608        "Keymap Editor".into()
1609    }
1610}
1611
1612impl Render for KeymapEditor {
1613    fn render(&mut self, _window: &mut Window, cx: &mut ui::Context<Self>) -> impl ui::IntoElement {
1614        if let SearchMode::KeyStroke { exact_match } = self.search_mode {
1615            let button = IconButton::new("keystrokes-exact-match", IconName::CaseSensitive)
1616                .tooltip(move |_window, cx| {
1617                    Tooltip::for_action(
1618                        "Toggle Exact Match Mode",
1619                        &ToggleExactKeystrokeMatching,
1620                        cx,
1621                    )
1622                })
1623                .shape(IconButtonShape::Square)
1624                .toggle_state(exact_match)
1625                .on_click(cx.listener(|_, _, window, cx| {
1626                    window.dispatch_action(ToggleExactKeystrokeMatching.boxed_clone(), cx);
1627                }));
1628
1629            self.keystroke_editor.update(cx, |editor, _| {
1630                editor.actions_slot = Some(button.into_any_element());
1631            });
1632        } else {
1633            self.keystroke_editor.update(cx, |editor, _| {
1634                editor.actions_slot = None;
1635            });
1636        }
1637
1638        let row_count = self.matches.len();
1639        let focus_handle = &self.focus_handle;
1640        let theme = cx.theme();
1641
1642        v_flex()
1643            .id("keymap-editor")
1644            .track_focus(focus_handle)
1645            .key_context(self.key_context())
1646            .on_action(cx.listener(Self::select_next))
1647            .on_action(cx.listener(Self::select_previous))
1648            .on_action(cx.listener(Self::select_first))
1649            .on_action(cx.listener(Self::select_last))
1650            .on_action(cx.listener(Self::focus_search))
1651            .on_action(cx.listener(Self::edit_binding))
1652            .on_action(cx.listener(Self::create_binding))
1653            .on_action(cx.listener(Self::delete_binding))
1654            .on_action(cx.listener(Self::copy_action_to_clipboard))
1655            .on_action(cx.listener(Self::copy_context_to_clipboard))
1656            .on_action(cx.listener(Self::toggle_conflict_filter))
1657            .on_action(cx.listener(Self::toggle_keystroke_search))
1658            .on_action(cx.listener(Self::toggle_exact_keystroke_matching))
1659            .on_action(cx.listener(Self::show_matching_keystrokes))
1660            .on_mouse_move(cx.listener(|this, _, _window, _cx| {
1661                this.show_hover_menus = true;
1662            }))
1663            .size_full()
1664            .p_2()
1665            .gap_1()
1666            .bg(theme.colors().editor_background)
1667            .child(
1668                v_flex()
1669                    .gap_2()
1670                    .child(
1671                        h_flex()
1672                            .gap_2()
1673                            .child(
1674                                h_flex()
1675                                    .key_context({
1676                                        let mut context = KeyContext::new_with_defaults();
1677                                        context.add("BufferSearchBar");
1678                                        context
1679                                    })
1680                                    .size_full()
1681                                    .h_8()
1682                                    .pl_2()
1683                                    .pr_1()
1684                                    .py_1()
1685                                    .border_1()
1686                                    .border_color(theme.colors().border)
1687                                    .rounded_md()
1688                                    .child(self.filter_editor.clone()),
1689                            )
1690                            .child(
1691                                h_flex()
1692                                    .gap_1()
1693                                    .min_w_64()
1694                                    .child(
1695                                        IconButton::new(
1696                                            "KeymapEditorToggleFiltersIcon",
1697                                            IconName::Keyboard,
1698                                        )
1699                                        .icon_size(IconSize::Small)
1700                                        .tooltip({
1701                                            let focus_handle = focus_handle.clone();
1702
1703                                            move |_window, cx| {
1704                                                Tooltip::for_action_in(
1705                                                    "Search by Keystroke",
1706                                                    &ToggleKeystrokeSearch,
1707                                                    &focus_handle.clone(),
1708                                                    cx,
1709                                                )
1710                                            }
1711                                        })
1712                                        .toggle_state(matches!(
1713                                            self.search_mode,
1714                                            SearchMode::KeyStroke { .. }
1715                                        ))
1716                                        .on_click(|_, window, cx| {
1717                                            window.dispatch_action(
1718                                                ToggleKeystrokeSearch.boxed_clone(),
1719                                                cx,
1720                                            );
1721                                        }),
1722                                    )
1723                                    .child(
1724                                        IconButton::new("KeymapEditorConflictIcon", IconName::Warning)
1725                                            .icon_size(IconSize::Small)
1726                                            .when(
1727                                                self.keybinding_conflict_state
1728                                                    .any_user_binding_conflicts(),
1729                                                |this| {
1730                                                    this.indicator(
1731                                                        Indicator::dot().color(Color::Warning),
1732                                                    )
1733                                                },
1734                                            )
1735                                            .tooltip({
1736                                                let filter_state = self.filter_state;
1737                                                let focus_handle = focus_handle.clone();
1738
1739                                                move |_window, cx| {
1740                                                    Tooltip::for_action_in(
1741                                                        match filter_state {
1742                                                            FilterState::All => "Show Conflicts",
1743                                                            FilterState::Conflicts => {
1744                                                                "Hide Conflicts"
1745                                                            }
1746                                                        },
1747                                                        &ToggleConflictFilter,
1748                                                        &focus_handle.clone(),
1749                                                        cx,
1750                                                    )
1751                                                }
1752                                            })
1753                                            .selected_icon_color(Color::Warning)
1754                                            .toggle_state(matches!(
1755                                                self.filter_state,
1756                                                FilterState::Conflicts
1757                                            ))
1758                                            .on_click(|_, window, cx| {
1759                                                window.dispatch_action(
1760                                                    ToggleConflictFilter.boxed_clone(),
1761                                                    cx,
1762                                                );
1763                                            }),
1764                                    )
1765                                    .child(
1766                                        h_flex()
1767                                            .w_full()
1768                                            .pl_2()
1769                                            .gap_1()
1770                                            .justify_end()
1771                                            .child(
1772                                                PopoverMenu::new("open-keymap-menu")
1773                                                    .menu(move |window, cx| {
1774                                                        Some(ContextMenu::build(window, cx, |menu, _, _| {
1775                                                            menu.header("View Default...")
1776                                                                .action(
1777                                                                    "Zed Key Bindings",
1778                                                                    zed_actions::OpenDefaultKeymap
1779                                                                        .boxed_clone(),
1780                                                                )
1781                                                                .action(
1782                                                                    "Vim Bindings",
1783                                                                    zed_actions::vim::OpenDefaultKeymap.boxed_clone(),
1784                                                                )
1785                                                        }))
1786                                                    })
1787                                                    .anchor(gpui::Corner::TopRight)
1788                                                    .offset(gpui::Point {
1789                                                        x: px(0.0),
1790                                                        y: px(2.0),
1791                                                    })
1792                                                    .trigger_with_tooltip(
1793                                                        IconButton::new(
1794                                                            "OpenKeymapJsonButton",
1795                                                            IconName::Ellipsis,
1796                                                        )
1797                                                        .icon_size(IconSize::Small),
1798                                                        {
1799                                                            let focus_handle = focus_handle.clone();
1800                                                            move |_window, cx| {
1801                                                                Tooltip::for_action_in(
1802                                                                    "View Default...",
1803                                                                    &zed_actions::OpenKeymapFile,
1804                                                                    &focus_handle,
1805                                                                    cx,
1806                                                                )
1807                                                            }
1808                                                        },
1809                                                    ),
1810                                            )
1811                                            .child(
1812                                                Button::new("edit-in-json", "Edit in keymap.json")
1813                                                    .style(ButtonStyle::Outlined)
1814                                                    .on_click(|_, window, cx| {
1815                                                        window.dispatch_action(
1816                                                            zed_actions::OpenKeymapFile.boxed_clone(),
1817                                                            cx,
1818                                                        );
1819                                                    })
1820                                            ),
1821                                    )
1822                            ),
1823                    )
1824                    .when(
1825                        matches!(self.search_mode, SearchMode::KeyStroke { .. }),
1826                        |this| {
1827                            this.child(
1828                                h_flex()
1829                                    .gap_2()
1830                                    .child(self.keystroke_editor.clone())
1831                                    .child(div().min_w_64()), // Spacer div to align with the search input
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        _cx: &mut Context<Editor>,
3016    ) -> bool {
3017        text.chars()
3018            .last()
3019            .is_some_and(|last_char| last_char.is_ascii_alphanumeric() || last_char == '_')
3020    }
3021}
3022
3023async fn load_json_language(workspace: WeakEntity<Workspace>, cx: &mut AsyncApp) -> Arc<Language> {
3024    let json_language_task = workspace
3025        .read_with(cx, |workspace, cx| {
3026            workspace
3027                .project()
3028                .read(cx)
3029                .languages()
3030                .language_for_name("JSON")
3031        })
3032        .context("Failed to load JSON language")
3033        .log_err();
3034    let json_language = match json_language_task {
3035        Some(task) => task.await.context("Failed to load JSON language").log_err(),
3036        None => None,
3037    };
3038    json_language.unwrap_or_else(|| {
3039        Arc::new(Language::new(
3040            LanguageConfig {
3041                name: "JSON".into(),
3042                ..Default::default()
3043            },
3044            Some(tree_sitter_json::LANGUAGE.into()),
3045        ))
3046    })
3047}
3048
3049async fn load_keybind_context_language(
3050    workspace: WeakEntity<Workspace>,
3051    cx: &mut AsyncApp,
3052) -> Arc<Language> {
3053    let language_task = workspace
3054        .read_with(cx, |workspace, cx| {
3055            workspace
3056                .project()
3057                .read(cx)
3058                .languages()
3059                .language_for_name("Zed Keybind Context")
3060        })
3061        .context("Failed to load Zed Keybind Context language")
3062        .log_err();
3063    let language = match language_task {
3064        Some(task) => task
3065            .await
3066            .context("Failed to load Zed Keybind Context language")
3067            .log_err(),
3068        None => None,
3069    };
3070    language.unwrap_or_else(|| {
3071        Arc::new(Language::new(
3072            LanguageConfig {
3073                name: "Zed Keybind Context".into(),
3074                ..Default::default()
3075            },
3076            Some(tree_sitter_rust::LANGUAGE.into()),
3077        ))
3078    })
3079}
3080
3081async fn save_keybinding_update(
3082    create: bool,
3083    existing: ProcessedBinding,
3084    action_mapping: &ActionMapping,
3085    new_args: Option<&str>,
3086    fs: &Arc<dyn Fs>,
3087    keyboard_mapper: &dyn PlatformKeyboardMapper,
3088) -> anyhow::Result<()> {
3089    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3090        .await
3091        .context("Failed to load keymap file")?;
3092
3093    let tab_size = infer_json_indent_size(&keymap_contents);
3094
3095    let existing_keystrokes = existing.keystrokes().unwrap_or_default();
3096    let existing_context = existing.context().and_then(KeybindContextString::local_str);
3097    let existing_args = existing
3098        .action()
3099        .arguments
3100        .as_ref()
3101        .map(|args| args.text.as_ref());
3102
3103    let target = settings::KeybindUpdateTarget {
3104        context: existing_context,
3105        keystrokes: existing_keystrokes,
3106        action_name: existing.action().name,
3107        action_arguments: existing_args,
3108    };
3109
3110    let source = settings::KeybindUpdateTarget {
3111        context: action_mapping.context.as_ref().map(|a| &***a),
3112        keystrokes: &action_mapping.keystrokes,
3113        action_name: existing.action().name,
3114        action_arguments: new_args,
3115    };
3116
3117    let operation = if !create {
3118        settings::KeybindUpdateOperation::Replace {
3119            target,
3120            target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
3121            source,
3122        }
3123    } else {
3124        settings::KeybindUpdateOperation::Add {
3125            source,
3126            from: Some(target),
3127        }
3128    };
3129
3130    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
3131
3132    let updated_keymap_contents = settings::KeymapFile::update_keybinding(
3133        operation,
3134        keymap_contents,
3135        tab_size,
3136        keyboard_mapper,
3137    )
3138    .map_err(|err| anyhow::anyhow!("Could not save updated keybinding: {}", err))?;
3139    fs.write(
3140        paths::keymap_file().as_path(),
3141        updated_keymap_contents.as_bytes(),
3142    )
3143    .await
3144    .context("Failed to write keymap file")?;
3145
3146    telemetry::event!(
3147        "Keybinding Updated",
3148        new_keybinding = new_keybinding,
3149        removed_keybinding = removed_keybinding,
3150        source = source
3151    );
3152    Ok(())
3153}
3154
3155async fn remove_keybinding(
3156    existing: ProcessedBinding,
3157    fs: &Arc<dyn Fs>,
3158    keyboard_mapper: &dyn PlatformKeyboardMapper,
3159) -> anyhow::Result<()> {
3160    let Some(keystrokes) = existing.keystrokes() else {
3161        anyhow::bail!("Cannot remove a keybinding that does not exist");
3162    };
3163    let keymap_contents = settings::KeymapFile::load_keymap_file(fs)
3164        .await
3165        .context("Failed to load keymap file")?;
3166    let tab_size = infer_json_indent_size(&keymap_contents);
3167
3168    let operation = settings::KeybindUpdateOperation::Remove {
3169        target: settings::KeybindUpdateTarget {
3170            context: existing.context().and_then(KeybindContextString::local_str),
3171            keystrokes,
3172            action_name: existing.action().name,
3173            action_arguments: existing
3174                .action()
3175                .arguments
3176                .as_ref()
3177                .map(|arguments| arguments.text.as_ref()),
3178        },
3179        target_keybind_source: existing.keybind_source().unwrap_or(KeybindSource::User),
3180    };
3181
3182    let (new_keybinding, removed_keybinding, source) = operation.generate_telemetry();
3183    let updated_keymap_contents = settings::KeymapFile::update_keybinding(
3184        operation,
3185        keymap_contents,
3186        tab_size,
3187        keyboard_mapper,
3188    )
3189    .context("Failed to update keybinding")?;
3190    fs.write(
3191        paths::keymap_file().as_path(),
3192        updated_keymap_contents.as_bytes(),
3193    )
3194    .await
3195    .context("Failed to write keymap file")?;
3196
3197    telemetry::event!(
3198        "Keybinding Removed",
3199        new_keybinding = new_keybinding,
3200        removed_keybinding = removed_keybinding,
3201        source = source
3202    );
3203    Ok(())
3204}
3205
3206fn collect_contexts_from_assets() -> Vec<SharedString> {
3207    let mut keymap_assets = vec![
3208        util::asset_str::<SettingsAssets>(settings::DEFAULT_KEYMAP_PATH),
3209        util::asset_str::<SettingsAssets>(settings::VIM_KEYMAP_PATH),
3210    ];
3211    keymap_assets.extend(
3212        BaseKeymap::OPTIONS
3213            .iter()
3214            .filter_map(|(_, base_keymap)| base_keymap.asset_path())
3215            .map(util::asset_str::<SettingsAssets>),
3216    );
3217
3218    let mut contexts = HashSet::default();
3219
3220    for keymap_asset in keymap_assets {
3221        let Ok(keymap) = KeymapFile::parse(&keymap_asset) else {
3222            continue;
3223        };
3224
3225        for section in keymap.sections() {
3226            let context_expr = &section.context;
3227            let mut queue = Vec::new();
3228            let Ok(root_context) = gpui::KeyBindingContextPredicate::parse(context_expr) else {
3229                continue;
3230            };
3231
3232            queue.push(root_context);
3233            while let Some(context) = queue.pop() {
3234                match context {
3235                    Identifier(ident) => {
3236                        contexts.insert(ident);
3237                    }
3238                    Equal(ident_a, ident_b) => {
3239                        contexts.insert(ident_a);
3240                        contexts.insert(ident_b);
3241                    }
3242                    NotEqual(ident_a, ident_b) => {
3243                        contexts.insert(ident_a);
3244                        contexts.insert(ident_b);
3245                    }
3246                    Descendant(ctx_a, ctx_b) => {
3247                        queue.push(*ctx_a);
3248                        queue.push(*ctx_b);
3249                    }
3250                    Not(ctx) => {
3251                        queue.push(*ctx);
3252                    }
3253                    And(ctx_a, ctx_b) => {
3254                        queue.push(*ctx_a);
3255                        queue.push(*ctx_b);
3256                    }
3257                    Or(ctx_a, ctx_b) => {
3258                        queue.push(*ctx_a);
3259                        queue.push(*ctx_b);
3260                    }
3261                }
3262            }
3263        }
3264    }
3265
3266    let mut contexts = contexts.into_iter().collect::<Vec<_>>();
3267    contexts.sort();
3268
3269    contexts
3270}
3271
3272fn normalized_ctx_eq(
3273    a: &gpui::KeyBindingContextPredicate,
3274    b: &gpui::KeyBindingContextPredicate,
3275) -> bool {
3276    use gpui::KeyBindingContextPredicate::*;
3277    return match (a, b) {
3278        (Identifier(_), Identifier(_)) => a == b,
3279        (Equal(a_left, a_right), Equal(b_left, b_right)) => {
3280            (a_left == b_left && a_right == b_right) || (a_left == b_right && a_right == b_left)
3281        }
3282        (NotEqual(a_left, a_right), NotEqual(b_left, b_right)) => {
3283            (a_left == b_left && a_right == b_right) || (a_left == b_right && a_right == b_left)
3284        }
3285        (Descendant(a_parent, a_child), Descendant(b_parent, b_child)) => {
3286            normalized_ctx_eq(a_parent, b_parent) && normalized_ctx_eq(a_child, b_child)
3287        }
3288        (Not(a_expr), Not(b_expr)) => normalized_ctx_eq(a_expr, b_expr),
3289        // Handle double negation: !(!a) == a
3290        (Not(a_expr), b) if matches!(a_expr.as_ref(), Not(_)) => {
3291            let Not(a_inner) = a_expr.as_ref() else {
3292                unreachable!();
3293            };
3294            normalized_ctx_eq(b, a_inner)
3295        }
3296        (a, Not(b_expr)) if matches!(b_expr.as_ref(), Not(_)) => {
3297            let Not(b_inner) = b_expr.as_ref() else {
3298                unreachable!();
3299            };
3300            normalized_ctx_eq(a, b_inner)
3301        }
3302        (And(a_left, a_right), And(b_left, b_right))
3303            if matches!(a_left.as_ref(), And(_, _))
3304                || matches!(a_right.as_ref(), And(_, _))
3305                || matches!(b_left.as_ref(), And(_, _))
3306                || matches!(b_right.as_ref(), And(_, _)) =>
3307        {
3308            let mut a_operands = Vec::new();
3309            flatten_and(a, &mut a_operands);
3310            let mut b_operands = Vec::new();
3311            flatten_and(b, &mut b_operands);
3312            compare_operand_sets(&a_operands, &b_operands)
3313        }
3314        (And(a_left, a_right), And(b_left, b_right)) => {
3315            (normalized_ctx_eq(a_left, b_left) && normalized_ctx_eq(a_right, b_right))
3316                || (normalized_ctx_eq(a_left, b_right) && normalized_ctx_eq(a_right, b_left))
3317        }
3318        (Or(a_left, a_right), Or(b_left, b_right))
3319            if matches!(a_left.as_ref(), Or(_, _))
3320                || matches!(a_right.as_ref(), Or(_, _))
3321                || matches!(b_left.as_ref(), Or(_, _))
3322                || matches!(b_right.as_ref(), Or(_, _)) =>
3323        {
3324            let mut a_operands = Vec::new();
3325            flatten_or(a, &mut a_operands);
3326            let mut b_operands = Vec::new();
3327            flatten_or(b, &mut b_operands);
3328            compare_operand_sets(&a_operands, &b_operands)
3329        }
3330        (Or(a_left, a_right), Or(b_left, b_right)) => {
3331            (normalized_ctx_eq(a_left, b_left) && normalized_ctx_eq(a_right, b_right))
3332                || (normalized_ctx_eq(a_left, b_right) && normalized_ctx_eq(a_right, b_left))
3333        }
3334        _ => false,
3335    };
3336
3337    fn flatten_and<'a>(
3338        pred: &'a gpui::KeyBindingContextPredicate,
3339        operands: &mut Vec<&'a gpui::KeyBindingContextPredicate>,
3340    ) {
3341        use gpui::KeyBindingContextPredicate::*;
3342        match pred {
3343            And(left, right) => {
3344                flatten_and(left, operands);
3345                flatten_and(right, operands);
3346            }
3347            _ => operands.push(pred),
3348        }
3349    }
3350
3351    fn flatten_or<'a>(
3352        pred: &'a gpui::KeyBindingContextPredicate,
3353        operands: &mut Vec<&'a gpui::KeyBindingContextPredicate>,
3354    ) {
3355        use gpui::KeyBindingContextPredicate::*;
3356        match pred {
3357            Or(left, right) => {
3358                flatten_or(left, operands);
3359                flatten_or(right, operands);
3360            }
3361            _ => operands.push(pred),
3362        }
3363    }
3364
3365    fn compare_operand_sets(
3366        a: &[&gpui::KeyBindingContextPredicate],
3367        b: &[&gpui::KeyBindingContextPredicate],
3368    ) -> bool {
3369        if a.len() != b.len() {
3370            return false;
3371        }
3372
3373        // For each operand in a, find a matching operand in b
3374        let mut b_matched = vec![false; b.len()];
3375        for a_operand in a {
3376            let mut found = false;
3377            for (b_idx, b_operand) in b.iter().enumerate() {
3378                if !b_matched[b_idx] && normalized_ctx_eq(a_operand, b_operand) {
3379                    b_matched[b_idx] = true;
3380                    found = true;
3381                    break;
3382                }
3383            }
3384            if !found {
3385                return false;
3386            }
3387        }
3388
3389        true
3390    }
3391}
3392
3393impl SerializableItem for KeymapEditor {
3394    fn serialized_item_kind() -> &'static str {
3395        "KeymapEditor"
3396    }
3397
3398    fn cleanup(
3399        workspace_id: workspace::WorkspaceId,
3400        alive_items: Vec<workspace::ItemId>,
3401        _window: &mut Window,
3402        cx: &mut App,
3403    ) -> gpui::Task<gpui::Result<()>> {
3404        workspace::delete_unloaded_items(
3405            alive_items,
3406            workspace_id,
3407            "keybinding_editors",
3408            &KEYBINDING_EDITORS,
3409            cx,
3410        )
3411    }
3412
3413    fn deserialize(
3414        _project: Entity<project::Project>,
3415        workspace: WeakEntity<Workspace>,
3416        workspace_id: workspace::WorkspaceId,
3417        item_id: workspace::ItemId,
3418        window: &mut Window,
3419        cx: &mut App,
3420    ) -> gpui::Task<gpui::Result<Entity<Self>>> {
3421        window.spawn(cx, async move |cx| {
3422            if KEYBINDING_EDITORS
3423                .get_keybinding_editor(item_id, workspace_id)?
3424                .is_some()
3425            {
3426                cx.update(|window, cx| cx.new(|cx| KeymapEditor::new(workspace, window, cx)))
3427            } else {
3428                Err(anyhow!("No keybinding editor to deserialize"))
3429            }
3430        })
3431    }
3432
3433    fn serialize(
3434        &mut self,
3435        workspace: &mut Workspace,
3436        item_id: workspace::ItemId,
3437        _closing: bool,
3438        _window: &mut Window,
3439        cx: &mut ui::Context<Self>,
3440    ) -> Option<gpui::Task<gpui::Result<()>>> {
3441        let workspace_id = workspace.database_id()?;
3442        Some(cx.background_spawn(async move {
3443            KEYBINDING_EDITORS
3444                .save_keybinding_editor(item_id, workspace_id)
3445                .await
3446        }))
3447    }
3448
3449    fn should_serialize(&self, _event: &Self::Event) -> bool {
3450        false
3451    }
3452}
3453
3454mod persistence {
3455    use db::{query, sqlez::domain::Domain, sqlez_macros::sql};
3456    use workspace::WorkspaceDb;
3457
3458    pub struct KeybindingEditorDb(db::sqlez::thread_safe_connection::ThreadSafeConnection);
3459
3460    impl Domain for KeybindingEditorDb {
3461        const NAME: &str = stringify!(KeybindingEditorDb);
3462
3463        const MIGRATIONS: &[&str] = &[sql!(
3464                CREATE TABLE keybinding_editors (
3465                    workspace_id INTEGER,
3466                    item_id INTEGER UNIQUE,
3467
3468                    PRIMARY KEY(workspace_id, item_id),
3469                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
3470                    ON DELETE CASCADE
3471                ) STRICT;
3472        )];
3473    }
3474
3475    db::static_connection!(KEYBINDING_EDITORS, KeybindingEditorDb, [WorkspaceDb]);
3476
3477    impl KeybindingEditorDb {
3478        query! {
3479            pub async fn save_keybinding_editor(
3480                item_id: workspace::ItemId,
3481                workspace_id: workspace::WorkspaceId
3482            ) -> Result<()> {
3483                INSERT OR REPLACE INTO keybinding_editors(item_id, workspace_id)
3484                VALUES (?, ?)
3485            }
3486        }
3487
3488        query! {
3489            pub fn get_keybinding_editor(
3490                item_id: workspace::ItemId,
3491                workspace_id: workspace::WorkspaceId
3492            ) -> Result<Option<workspace::ItemId>> {
3493                SELECT item_id
3494                FROM keybinding_editors
3495                WHERE item_id = ? AND workspace_id = ?
3496            }
3497        }
3498    }
3499}
3500
3501#[cfg(test)]
3502mod tests {
3503    use super::*;
3504
3505    #[test]
3506    fn normalized_ctx_cmp() {
3507        #[track_caller]
3508        fn cmp(a: &str, b: &str) -> bool {
3509            let a = gpui::KeyBindingContextPredicate::parse(a)
3510                .expect("Failed to parse keybinding context a");
3511            let b = gpui::KeyBindingContextPredicate::parse(b)
3512                .expect("Failed to parse keybinding context b");
3513            normalized_ctx_eq(&a, &b)
3514        }
3515
3516        // Basic equality - identical expressions
3517        assert!(cmp("a && b", "a && b"));
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", "!a"));
3523
3524        // AND operator - associative/commutative
3525        assert!(cmp("a && b", "b && a"));
3526        assert!(cmp("a && b && c", "c && b && a"));
3527        assert!(cmp("a && b && c", "b && a && c"));
3528        assert!(cmp("a && b && c && d", "d && c && b && a"));
3529
3530        // OR operator - associative/commutative
3531        assert!(cmp("a || b", "b || a"));
3532        assert!(cmp("a || b || c", "c || b || a"));
3533        assert!(cmp("a || b || c", "b || a || c"));
3534        assert!(cmp("a || b || c || d", "d || c || b || a"));
3535
3536        // Equality operator - associative/commutative
3537        assert!(cmp("a == b", "b == a"));
3538        assert!(cmp("x == y", "y == x"));
3539
3540        // Inequality operator - associative/commutative
3541        assert!(cmp("a != b", "b != a"));
3542        assert!(cmp("x != y", "y != x"));
3543
3544        // Complex nested expressions with associative operators
3545        assert!(cmp("(a && b) || c", "c || (a && b)"));
3546        assert!(cmp("(a && b) || c", "c || (b && a)"));
3547        assert!(cmp("(a || b) && c", "c && (a || b)"));
3548        assert!(cmp("(a || b) && c", "c && (b || a)"));
3549        assert!(cmp("(a && b) || (c && d)", "(c && d) || (a && b)"));
3550        assert!(cmp("(a && b) || (c && d)", "(d && c) || (b && a)"));
3551
3552        // Multiple levels of nesting
3553        assert!(cmp("((a && b) || c) && d", "d && ((a && b) || c)"));
3554        assert!(cmp("((a && b) || c) && d", "d && (c || (b && a))"));
3555        assert!(cmp("a && (b || (c && d))", "(b || (c && d)) && a"));
3556        assert!(cmp("a && (b || (c && d))", "(b || (d && c)) && a"));
3557
3558        // Negation with associative operators
3559        assert!(cmp("!a && b", "b && !a"));
3560        assert!(cmp("!a || b", "b || !a"));
3561        assert!(cmp("!(a && b) || c", "c || !(a && b)"));
3562        assert!(cmp("!(a && b) || c", "c || !(b && a)"));
3563
3564        // Descendant operator (>) - NOT associative/commutative
3565        assert!(cmp("a > b", "a > b"));
3566        assert!(!cmp("a > b", "b > a"));
3567        assert!(!cmp("a > b > c", "c > b > a"));
3568        assert!(!cmp("a > b > c", "a > c > b"));
3569
3570        // Mixed operators with descendant
3571        assert!(cmp("(a > b) && c", "c && (a > b)"));
3572        assert!(!cmp("(a > b) && c", "c && (b > a)"));
3573        assert!(cmp("(a > b) || (c > d)", "(c > d) || (a > b)"));
3574        assert!(!cmp("(a > b) || (c > d)", "(b > a) || (d > c)"));
3575
3576        // Negative cases - different operators
3577        assert!(!cmp("a && b", "a || b"));
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
3584        // Negative cases - different operands
3585        assert!(!cmp("a && b", "a && c"));
3586        assert!(!cmp("a && b", "c && d"));
3587        assert!(!cmp("a || b", "a || c"));
3588        assert!(!cmp("a || b", "c || d"));
3589        assert!(!cmp("a == b", "a == c"));
3590        assert!(!cmp("a != b", "a != c"));
3591        assert!(!cmp("a > b", "a > c"));
3592        assert!(!cmp("a > b", "c > b"));
3593
3594        // Negative cases - with negation
3595        assert!(!cmp("!a", "a"));
3596        assert!(!cmp("!a && b", "a && b"));
3597        assert!(!cmp("!(a && b)", "a && b"));
3598        assert!(!cmp("!a || b", "a || b"));
3599        assert!(!cmp("!(a || b)", "a || b"));
3600
3601        // Negative cases - complex expressions
3602        assert!(!cmp("(a && b) || c", "(a || b) && c"));
3603        assert!(!cmp("a && (b || c)", "a || (b && c)"));
3604        assert!(!cmp("(a && b) || (c && d)", "(a || b) && (c || d)"));
3605        assert!(!cmp("a > b && c", "a && b > c"));
3606
3607        // Edge cases - multiple same operands
3608        assert!(cmp("a && a", "a && a"));
3609        assert!(cmp("a || a", "a || a"));
3610        assert!(cmp("a && a && b", "b && a && a"));
3611        assert!(cmp("a || a || b", "b || a || a"));
3612
3613        // Edge cases - deeply nested
3614        assert!(cmp(
3615            "((a && b) || (c && d)) && ((e || f) && g)",
3616            "((e || f) && g) && ((c && d) || (a && b))"
3617        ));
3618        assert!(cmp(
3619            "((a && b) || (c && d)) && ((e || f) && g)",
3620            "(g && (f || e)) && ((d && c) || (b && a))"
3621        ));
3622
3623        // Edge cases - repeated patterns
3624        assert!(cmp("(a && b) || (a && b)", "(b && a) || (b && a)"));
3625        assert!(cmp("(a || b) && (a || b)", "(b || a) && (b || a)"));
3626
3627        // Negative cases - subtle differences
3628        assert!(!cmp("a && b && c", "a && b"));
3629        assert!(!cmp("a || b || c", "a || b"));
3630        assert!(!cmp("(a && b) || c", "a && (b || c)"));
3631
3632        // a > b > c is not the same as a > c, should not be equal
3633        assert!(!cmp("a > b > c", "a > c"));
3634
3635        // Double negation with complex expressions
3636        assert!(cmp("!(!(a && b))", "a && b"));
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)) || c", "(a && b) || c"));
3642        assert!(cmp("!(!(a && b)) || c", "(b && a) || c"));
3643        assert!(cmp("!(!a)", "a"));
3644        assert!(cmp("a", "!(!a)"));
3645        assert!(cmp("!(!(!a))", "!a"));
3646        assert!(cmp("!(!(!(!a)))", "a"));
3647    }
3648}