keymap_editor.rs

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