keymap_editor.rs

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