command_palette.rs

   1mod persistence;
   2
   3use std::{
   4    cmp::{self, Reverse},
   5    collections::{HashMap, VecDeque},
   6    sync::Arc,
   7    time::Duration,
   8};
   9
  10use client::parse_zed_link;
  11use command_palette_hooks::{
  12    CommandInterceptItem, CommandInterceptResult, CommandPaletteFilter,
  13    GlobalCommandPaletteInterceptor,
  14};
  15
  16use fuzzy::{StringMatch, StringMatchCandidate};
  17use gpui::{
  18    Action, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
  19    ParentElement, Render, Styled, Task, WeakEntity, Window,
  20};
  21use persistence::COMMAND_PALETTE_HISTORY;
  22use picker::Direction;
  23use picker::{Picker, PickerDelegate};
  24use postage::{sink::Sink, stream::Stream};
  25use settings::Settings;
  26use ui::{HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, prelude::*};
  27use util::ResultExt;
  28use workspace::{ModalView, Workspace, WorkspaceSettings};
  29use zed_actions::{OpenZedUrl, command_palette::Toggle};
  30
  31pub fn init(cx: &mut App) {
  32    command_palette_hooks::init(cx);
  33    cx.observe_new(CommandPalette::register).detach();
  34}
  35
  36impl ModalView for CommandPalette {}
  37
  38pub struct CommandPalette {
  39    picker: Entity<Picker<CommandPaletteDelegate>>,
  40}
  41
  42/// Removes subsequent whitespace characters and double colons from the query.
  43///
  44/// This improves the likelihood of a match by either humanized name or keymap-style name.
  45pub fn normalize_action_query(input: &str) -> String {
  46    let mut result = String::with_capacity(input.len());
  47    let mut last_char = None;
  48
  49    for char in input.trim().chars() {
  50        match (last_char, char) {
  51            (Some(':'), ':') => continue,
  52            (Some(last_char), char) if last_char.is_whitespace() && char.is_whitespace() => {
  53                continue;
  54            }
  55            _ => {
  56                last_char = Some(char);
  57            }
  58        }
  59        result.push(char);
  60    }
  61
  62    result
  63}
  64
  65impl CommandPalette {
  66    fn register(
  67        workspace: &mut Workspace,
  68        _window: Option<&mut Window>,
  69        _: &mut Context<Workspace>,
  70    ) {
  71        workspace.register_action(|workspace, _: &Toggle, window, cx| {
  72            Self::toggle(workspace, "", window, cx)
  73        });
  74    }
  75
  76    pub fn toggle(
  77        workspace: &mut Workspace,
  78        query: &str,
  79        window: &mut Window,
  80        cx: &mut Context<Workspace>,
  81    ) {
  82        let Some(previous_focus_handle) = window.focused(cx) else {
  83            return;
  84        };
  85
  86        let entity = cx.weak_entity();
  87        workspace.toggle_modal(window, cx, move |window, cx| {
  88            CommandPalette::new(previous_focus_handle, query, entity, window, cx)
  89        });
  90    }
  91
  92    fn new(
  93        previous_focus_handle: FocusHandle,
  94        query: &str,
  95        entity: WeakEntity<Workspace>,
  96        window: &mut Window,
  97        cx: &mut Context<Self>,
  98    ) -> Self {
  99        let filter = CommandPaletteFilter::try_global(cx);
 100
 101        let commands = window
 102            .available_actions(cx)
 103            .into_iter()
 104            .filter_map(|action| {
 105                if filter.is_some_and(|filter| filter.is_hidden(&*action)) {
 106                    return None;
 107                }
 108
 109                Some(Command {
 110                    name: humanize_action_name(action.name()),
 111                    action,
 112                })
 113            })
 114            .collect();
 115
 116        let delegate = CommandPaletteDelegate::new(
 117            cx.entity().downgrade(),
 118            entity,
 119            commands,
 120            previous_focus_handle,
 121        );
 122
 123        let picker = cx.new(|cx| {
 124            let picker = Picker::uniform_list(delegate, window, cx);
 125            picker.set_query(query, window, cx);
 126            picker
 127        });
 128        Self { picker }
 129    }
 130
 131    pub fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
 132        self.picker
 133            .update(cx, |picker, cx| picker.set_query(query, window, cx))
 134    }
 135}
 136
 137impl EventEmitter<DismissEvent> for CommandPalette {}
 138
 139impl Focusable for CommandPalette {
 140    fn focus_handle(&self, cx: &App) -> FocusHandle {
 141        self.picker.focus_handle(cx)
 142    }
 143}
 144
 145impl Render for CommandPalette {
 146    fn render(&mut self, _window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
 147        v_flex()
 148            .key_context("CommandPalette")
 149            .w(rems(34.))
 150            .child(self.picker.clone())
 151    }
 152}
 153
 154pub struct CommandPaletteDelegate {
 155    latest_query: String,
 156    command_palette: WeakEntity<CommandPalette>,
 157    workspace: WeakEntity<Workspace>,
 158    all_commands: Vec<Command>,
 159    commands: Vec<Command>,
 160    matches: Vec<StringMatch>,
 161    selected_ix: usize,
 162    previous_focus_handle: FocusHandle,
 163    updating_matches: Option<(
 164        Task<()>,
 165        postage::dispatch::Receiver<(Vec<Command>, Vec<StringMatch>, CommandInterceptResult)>,
 166    )>,
 167    query_history: QueryHistory,
 168}
 169
 170struct Command {
 171    name: String,
 172    action: Box<dyn Action>,
 173}
 174
 175#[derive(Default)]
 176struct QueryHistory {
 177    history: Option<VecDeque<String>>,
 178    cursor: Option<usize>,
 179    prefix: Option<String>,
 180}
 181
 182impl QueryHistory {
 183    fn history(&mut self) -> &mut VecDeque<String> {
 184        self.history.get_or_insert_with(|| {
 185            COMMAND_PALETTE_HISTORY
 186                .list_recent_queries()
 187                .unwrap_or_default()
 188                .into_iter()
 189                .collect()
 190        })
 191    }
 192
 193    fn add(&mut self, query: String) {
 194        if let Some(pos) = self.history().iter().position(|h| h == &query) {
 195            self.history().remove(pos);
 196        }
 197        self.history().push_back(query);
 198        self.cursor = None;
 199        self.prefix = None;
 200    }
 201
 202    fn validate_cursor(&mut self, current_query: &str) -> Option<usize> {
 203        if let Some(pos) = self.cursor {
 204            if self.history().get(pos).map(|s| s.as_str()) != Some(current_query) {
 205                self.cursor = None;
 206                self.prefix = None;
 207            }
 208        }
 209        self.cursor
 210    }
 211
 212    fn previous(&mut self, current_query: &str) -> Option<&str> {
 213        if self.validate_cursor(current_query).is_none() {
 214            self.prefix = Some(current_query.to_string());
 215        }
 216
 217        let prefix = self.prefix.clone().unwrap_or_default();
 218        let start_index = self.cursor.unwrap_or(self.history().len());
 219
 220        for i in (0..start_index).rev() {
 221            if self
 222                .history()
 223                .get(i)
 224                .is_some_and(|e| e.starts_with(&prefix))
 225            {
 226                self.cursor = Some(i);
 227                return self.history().get(i).map(|s| s.as_str());
 228            }
 229        }
 230        None
 231    }
 232
 233    fn next(&mut self, current_query: &str) -> Option<&str> {
 234        let selected = self.validate_cursor(current_query)?;
 235        let prefix = self.prefix.clone().unwrap_or_default();
 236
 237        for i in (selected + 1)..self.history().len() {
 238            if self
 239                .history()
 240                .get(i)
 241                .is_some_and(|e| e.starts_with(&prefix))
 242            {
 243                self.cursor = Some(i);
 244                return self.history().get(i).map(|s| s.as_str());
 245            }
 246        }
 247        None
 248    }
 249
 250    fn reset_cursor(&mut self) {
 251        self.cursor = None;
 252        self.prefix = None;
 253    }
 254
 255    fn is_navigating(&self) -> bool {
 256        self.cursor.is_some()
 257    }
 258}
 259
 260impl Clone for Command {
 261    fn clone(&self) -> Self {
 262        Self {
 263            name: self.name.clone(),
 264            action: self.action.boxed_clone(),
 265        }
 266    }
 267}
 268
 269impl CommandPaletteDelegate {
 270    fn new(
 271        command_palette: WeakEntity<CommandPalette>,
 272        workspace: WeakEntity<Workspace>,
 273        commands: Vec<Command>,
 274        previous_focus_handle: FocusHandle,
 275    ) -> Self {
 276        Self {
 277            command_palette,
 278            workspace,
 279            all_commands: commands.clone(),
 280            matches: vec![],
 281            commands,
 282            selected_ix: 0,
 283            previous_focus_handle,
 284            latest_query: String::new(),
 285            updating_matches: None,
 286            query_history: Default::default(),
 287        }
 288    }
 289
 290    fn matches_updated(
 291        &mut self,
 292        query: String,
 293        mut commands: Vec<Command>,
 294        mut matches: Vec<StringMatch>,
 295        intercept_result: CommandInterceptResult,
 296        _: &mut Context<Picker<Self>>,
 297    ) {
 298        self.updating_matches.take();
 299        self.latest_query = query;
 300
 301        let mut new_matches = Vec::new();
 302
 303        for CommandInterceptItem {
 304            action,
 305            string,
 306            positions,
 307        } in intercept_result.results
 308        {
 309            if let Some(idx) = matches
 310                .iter()
 311                .position(|m| commands[m.candidate_id].action.partial_eq(&*action))
 312            {
 313                matches.remove(idx);
 314            }
 315            commands.push(Command {
 316                name: string.clone(),
 317                action,
 318            });
 319            new_matches.push(StringMatch {
 320                candidate_id: commands.len() - 1,
 321                string,
 322                positions,
 323                score: 0.0,
 324            })
 325        }
 326        if !intercept_result.exclusive {
 327            new_matches.append(&mut matches);
 328        }
 329        self.commands = commands;
 330        self.matches = new_matches;
 331        if self.matches.is_empty() {
 332            self.selected_ix = 0;
 333        } else {
 334            self.selected_ix = cmp::min(self.selected_ix, self.matches.len() - 1);
 335        }
 336    }
 337
 338    /// Hit count for each command in the palette.
 339    /// We only account for commands triggered directly via command palette and not by e.g. keystrokes because
 340    /// if a user already knows a keystroke for a command, they are unlikely to use a command palette to look for it.
 341    fn hit_counts(&self) -> HashMap<String, u16> {
 342        if let Ok(commands) = COMMAND_PALETTE_HISTORY.list_commands_used() {
 343            commands
 344                .into_iter()
 345                .map(|command| (command.command_name, command.invocations))
 346                .collect()
 347        } else {
 348            HashMap::new()
 349        }
 350    }
 351
 352    fn selected_command(&self) -> Option<&Command> {
 353        let action_ix = self
 354            .matches
 355            .get(self.selected_ix)
 356            .map(|m| m.candidate_id)
 357            .unwrap_or(self.selected_ix);
 358        // this gets called in headless tests where there are no commands loaded
 359        // so we need to return an Option here
 360        self.commands.get(action_ix)
 361    }
 362
 363    #[cfg(any(test, feature = "test-support"))]
 364    pub fn seed_history(&mut self, queries: &[&str]) {
 365        self.query_history.history = Some(queries.iter().map(|s| s.to_string()).collect());
 366    }
 367}
 368
 369impl PickerDelegate for CommandPaletteDelegate {
 370    type ListItem = ListItem;
 371
 372    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
 373        "Execute a command...".into()
 374    }
 375
 376    fn select_history(
 377        &mut self,
 378        direction: Direction,
 379        query: &str,
 380        _window: &mut Window,
 381        _cx: &mut App,
 382    ) -> Option<String> {
 383        match direction {
 384            Direction::Up => {
 385                let should_use_history =
 386                    self.selected_ix == 0 || self.query_history.is_navigating();
 387                if should_use_history {
 388                    if let Some(query) = self.query_history.previous(query).map(|s| s.to_string()) {
 389                        return Some(query);
 390                    }
 391                }
 392            }
 393            Direction::Down => {
 394                if self.query_history.is_navigating() {
 395                    if let Some(query) = self.query_history.next(query).map(|s| s.to_string()) {
 396                        return Some(query);
 397                    } else {
 398                        let prefix = self.query_history.prefix.take().unwrap_or_default();
 399                        self.query_history.reset_cursor();
 400                        return Some(prefix);
 401                    }
 402                }
 403            }
 404        }
 405        None
 406    }
 407
 408    fn match_count(&self) -> usize {
 409        self.matches.len()
 410    }
 411
 412    fn selected_index(&self) -> usize {
 413        self.selected_ix
 414    }
 415
 416    fn set_selected_index(
 417        &mut self,
 418        ix: usize,
 419        _window: &mut Window,
 420        _: &mut Context<Picker<Self>>,
 421    ) {
 422        self.selected_ix = ix;
 423    }
 424
 425    fn update_matches(
 426        &mut self,
 427        mut query: String,
 428        window: &mut Window,
 429        cx: &mut Context<Picker<Self>>,
 430    ) -> gpui::Task<()> {
 431        let settings = WorkspaceSettings::get_global(cx);
 432        if let Some(alias) = settings.command_aliases.get(&query) {
 433            query = alias.to_string();
 434        }
 435
 436        let workspace = self.workspace.clone();
 437
 438        let intercept_task = GlobalCommandPaletteInterceptor::intercept(&query, workspace, cx);
 439
 440        let (mut tx, mut rx) = postage::dispatch::channel(1);
 441
 442        let query_str = query.as_str();
 443        let is_zed_link = parse_zed_link(query_str, cx).is_some();
 444
 445        let task = cx.background_spawn({
 446            let mut commands = self.all_commands.clone();
 447            let hit_counts = self.hit_counts();
 448            let executor = cx.background_executor().clone();
 449            let query = normalize_action_query(query_str);
 450            let query_for_link = query_str.to_string();
 451            async move {
 452                commands.sort_by_key(|action| {
 453                    (
 454                        Reverse(hit_counts.get(&action.name).cloned()),
 455                        action.name.clone(),
 456                    )
 457                });
 458
 459                let candidates = commands
 460                    .iter()
 461                    .enumerate()
 462                    .map(|(ix, command)| StringMatchCandidate::new(ix, &command.name))
 463                    .collect::<Vec<_>>();
 464
 465                let matches = fuzzy::match_strings(
 466                    &candidates,
 467                    &query,
 468                    true,
 469                    true,
 470                    10000,
 471                    &Default::default(),
 472                    executor,
 473                )
 474                .await;
 475
 476                let intercept_result = if is_zed_link {
 477                    CommandInterceptResult {
 478                        results: vec![CommandInterceptItem {
 479                            action: OpenZedUrl {
 480                                url: query_for_link.clone(),
 481                            }
 482                            .boxed_clone(),
 483                            string: query_for_link,
 484                            positions: vec![],
 485                        }],
 486                        exclusive: false,
 487                    }
 488                } else if let Some(task) = intercept_task {
 489                    task.await
 490                } else {
 491                    CommandInterceptResult::default()
 492                };
 493
 494                tx.send((commands, matches, intercept_result))
 495                    .await
 496                    .log_err();
 497            }
 498        });
 499
 500        self.updating_matches = Some((task, rx.clone()));
 501
 502        cx.spawn_in(window, async move |picker, cx| {
 503            let Some((commands, matches, intercept_result)) = rx.recv().await else {
 504                return;
 505            };
 506
 507            picker
 508                .update(cx, |picker, cx| {
 509                    picker
 510                        .delegate
 511                        .matches_updated(query, commands, matches, intercept_result, cx)
 512                })
 513                .ok();
 514        })
 515    }
 516
 517    fn finalize_update_matches(
 518        &mut self,
 519        query: String,
 520        duration: Duration,
 521        _: &mut Window,
 522        cx: &mut Context<Picker<Self>>,
 523    ) -> bool {
 524        let Some((task, rx)) = self.updating_matches.take() else {
 525            return true;
 526        };
 527
 528        match cx
 529            .foreground_executor()
 530            .block_with_timeout(duration, rx.clone().recv())
 531        {
 532            Ok(Some((commands, matches, interceptor_result))) => {
 533                self.matches_updated(query, commands, matches, interceptor_result, cx);
 534                true
 535            }
 536            _ => {
 537                self.updating_matches = Some((task, rx));
 538                false
 539            }
 540        }
 541    }
 542
 543    fn dismissed(&mut self, _window: &mut Window, cx: &mut Context<Picker<Self>>) {
 544        self.command_palette
 545            .update(cx, |_, cx| cx.emit(DismissEvent))
 546            .ok();
 547    }
 548
 549    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
 550        if secondary {
 551            let Some(selected_command) = self.selected_command() else {
 552                return;
 553            };
 554            let action_name = selected_command.action.name();
 555            let open_keymap = Box::new(zed_actions::ChangeKeybinding {
 556                action: action_name.to_string(),
 557            });
 558            window.dispatch_action(open_keymap, cx);
 559            self.dismissed(window, cx);
 560            return;
 561        }
 562
 563        if self.matches.is_empty() {
 564            self.dismissed(window, cx);
 565            return;
 566        }
 567
 568        if !self.latest_query.is_empty() {
 569            self.query_history.add(self.latest_query.clone());
 570            self.query_history.reset_cursor();
 571        }
 572
 573        let action_ix = self.matches[self.selected_ix].candidate_id;
 574        let command = self.commands.swap_remove(action_ix);
 575        telemetry::event!(
 576            "Action Invoked",
 577            source = "command palette",
 578            action = command.name
 579        );
 580        self.matches.clear();
 581        self.commands.clear();
 582        let command_name = command.name.clone();
 583        let latest_query = self.latest_query.clone();
 584        cx.background_spawn(async move {
 585            COMMAND_PALETTE_HISTORY
 586                .write_command_invocation(command_name, latest_query)
 587                .await
 588        })
 589        .detach_and_log_err(cx);
 590        let action = command.action;
 591        window.focus(&self.previous_focus_handle, cx);
 592        self.dismissed(window, cx);
 593        window.dispatch_action(action, cx);
 594    }
 595
 596    fn render_match(
 597        &self,
 598        ix: usize,
 599        selected: bool,
 600        _: &mut Window,
 601        cx: &mut Context<Picker<Self>>,
 602    ) -> Option<Self::ListItem> {
 603        let matching_command = self.matches.get(ix)?;
 604        let command = self.commands.get(matching_command.candidate_id)?;
 605
 606        Some(
 607            ListItem::new(ix)
 608                .inset(true)
 609                .spacing(ListItemSpacing::Sparse)
 610                .toggle_state(selected)
 611                .child(
 612                    h_flex()
 613                        .w_full()
 614                        .py_px()
 615                        .justify_between()
 616                        .child(HighlightedLabel::new(
 617                            command.name.clone(),
 618                            matching_command.positions.clone(),
 619                        ))
 620                        .child(KeyBinding::for_action_in(
 621                            &*command.action,
 622                            &self.previous_focus_handle,
 623                            cx,
 624                        )),
 625                ),
 626        )
 627    }
 628
 629    fn render_footer(
 630        &self,
 631        window: &mut Window,
 632        cx: &mut Context<Picker<Self>>,
 633    ) -> Option<AnyElement> {
 634        let selected_command = self.selected_command()?;
 635        let keybind =
 636            KeyBinding::for_action_in(&*selected_command.action, &self.previous_focus_handle, cx);
 637
 638        let focus_handle = &self.previous_focus_handle;
 639        let keybinding_buttons = if keybind.has_binding(window) {
 640            Button::new("change", "Change Keybinding…")
 641                .key_binding(
 642                    KeyBinding::for_action_in(&menu::SecondaryConfirm, focus_handle, cx)
 643                        .map(|kb| kb.size(rems_from_px(12.))),
 644                )
 645                .on_click(move |_, window, cx| {
 646                    window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx);
 647                })
 648        } else {
 649            Button::new("add", "Add Keybinding…")
 650                .key_binding(
 651                    KeyBinding::for_action_in(&menu::SecondaryConfirm, focus_handle, cx)
 652                        .map(|kb| kb.size(rems_from_px(12.))),
 653                )
 654                .on_click(move |_, window, cx| {
 655                    window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx);
 656                })
 657        };
 658
 659        Some(
 660            h_flex()
 661                .w_full()
 662                .p_1p5()
 663                .gap_1()
 664                .justify_end()
 665                .border_t_1()
 666                .border_color(cx.theme().colors().border_variant)
 667                .child(keybinding_buttons)
 668                .child(
 669                    Button::new("run-action", "Run")
 670                        .key_binding(
 671                            KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
 672                                .map(|kb| kb.size(rems_from_px(12.))),
 673                        )
 674                        .on_click(|_, window, cx| {
 675                            window.dispatch_action(menu::Confirm.boxed_clone(), cx)
 676                        }),
 677                )
 678                .into_any(),
 679        )
 680    }
 681}
 682
 683/// Re-export for external callers that were using this from command_palette.
 684pub use gpui::humanize_action_name;
 685
 686impl std::fmt::Debug for Command {
 687    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 688        f.debug_struct("Command")
 689            .field("name", &self.name)
 690            .finish_non_exhaustive()
 691    }
 692}
 693
 694#[cfg(test)]
 695mod tests {
 696    use std::sync::Arc;
 697
 698    use super::*;
 699    use editor::Editor;
 700    use go_to_line::GoToLine;
 701    use gpui::{TestAppContext, VisualTestContext};
 702    use language::Point;
 703    use project::Project;
 704    use settings::KeymapFile;
 705    use workspace::{AppState, MultiWorkspace, Workspace};
 706
 707    #[test]
 708    fn test_humanize_action_name() {
 709        assert_eq!(
 710            humanize_action_name("editor::GoToDefinition"),
 711            "editor: go to definition"
 712        );
 713        assert_eq!(
 714            humanize_action_name("editor::Backspace"),
 715            "editor: backspace"
 716        );
 717        assert_eq!(
 718            humanize_action_name("go_to_line::Deploy"),
 719            "go to line: deploy"
 720        );
 721    }
 722
 723    #[test]
 724    fn test_normalize_query() {
 725        assert_eq!(
 726            normalize_action_query("editor: backspace"),
 727            "editor: backspace"
 728        );
 729        assert_eq!(
 730            normalize_action_query("editor:  backspace"),
 731            "editor: backspace"
 732        );
 733        assert_eq!(
 734            normalize_action_query("editor:    backspace"),
 735            "editor: backspace"
 736        );
 737        assert_eq!(
 738            normalize_action_query("editor::GoToDefinition"),
 739            "editor:GoToDefinition"
 740        );
 741        assert_eq!(
 742            normalize_action_query("editor::::GoToDefinition"),
 743            "editor:GoToDefinition"
 744        );
 745        assert_eq!(
 746            normalize_action_query("editor: :GoToDefinition"),
 747            "editor: :GoToDefinition"
 748        );
 749    }
 750
 751    #[gpui::test]
 752    async fn test_command_palette(cx: &mut TestAppContext) {
 753        persistence::COMMAND_PALETTE_HISTORY
 754            .clear_all()
 755            .await
 756            .unwrap();
 757        let app_state = init_test(cx);
 758        let project = Project::test(app_state.fs.clone(), [], cx).await;
 759        let (multi_workspace, cx) =
 760            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
 761        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
 762
 763        let editor = cx.new_window_entity(|window, cx| {
 764            let mut editor = Editor::single_line(window, cx);
 765            editor.set_text("abc", window, cx);
 766            editor
 767        });
 768
 769        workspace.update_in(cx, |workspace, window, cx| {
 770            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 771            editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
 772        });
 773
 774        cx.simulate_keystrokes("cmd-shift-p");
 775
 776        let palette = workspace.update(cx, |workspace, cx| {
 777            workspace
 778                .active_modal::<CommandPalette>(cx)
 779                .unwrap()
 780                .read(cx)
 781                .picker
 782                .clone()
 783        });
 784
 785        palette.read_with(cx, |palette, _| {
 786            assert!(palette.delegate.commands.len() > 5);
 787            let is_sorted =
 788                |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
 789            assert!(is_sorted(&palette.delegate.commands));
 790        });
 791
 792        cx.simulate_input("bcksp");
 793
 794        palette.read_with(cx, |palette, _| {
 795            assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
 796        });
 797
 798        cx.simulate_keystrokes("enter");
 799
 800        workspace.update(cx, |workspace, cx| {
 801            assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
 802            assert_eq!(editor.read(cx).text(cx), "ab")
 803        });
 804
 805        // Add namespace filter, and redeploy the palette
 806        cx.update(|_window, cx| {
 807            CommandPaletteFilter::update_global(cx, |filter, _| {
 808                filter.hide_namespace("editor");
 809            });
 810        });
 811
 812        cx.simulate_keystrokes("cmd-shift-p");
 813        cx.simulate_input("bcksp");
 814
 815        let palette = workspace.update(cx, |workspace, cx| {
 816            workspace
 817                .active_modal::<CommandPalette>(cx)
 818                .unwrap()
 819                .read(cx)
 820                .picker
 821                .clone()
 822        });
 823        palette.read_with(cx, |palette, _| {
 824            assert!(palette.delegate.matches.is_empty())
 825        });
 826    }
 827    #[gpui::test]
 828    async fn test_normalized_matches(cx: &mut TestAppContext) {
 829        let app_state = init_test(cx);
 830        let project = Project::test(app_state.fs.clone(), [], cx).await;
 831        let (multi_workspace, cx) =
 832            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
 833        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
 834
 835        let editor = cx.new_window_entity(|window, cx| {
 836            let mut editor = Editor::single_line(window, cx);
 837            editor.set_text("abc", window, cx);
 838            editor
 839        });
 840
 841        workspace.update_in(cx, |workspace, window, cx| {
 842            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 843            editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
 844        });
 845
 846        // Test normalize (trimming whitespace and double colons)
 847        cx.simulate_keystrokes("cmd-shift-p");
 848
 849        let palette = workspace.update(cx, |workspace, cx| {
 850            workspace
 851                .active_modal::<CommandPalette>(cx)
 852                .unwrap()
 853                .read(cx)
 854                .picker
 855                .clone()
 856        });
 857
 858        cx.simulate_input("Editor::    Backspace");
 859        palette.read_with(cx, |palette, _| {
 860            assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
 861        });
 862    }
 863
 864    #[gpui::test]
 865    async fn test_go_to_line(cx: &mut TestAppContext) {
 866        let app_state = init_test(cx);
 867        let project = Project::test(app_state.fs.clone(), [], cx).await;
 868        let (multi_workspace, cx) =
 869            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
 870        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
 871
 872        cx.simulate_keystrokes("cmd-n");
 873
 874        let editor = workspace.update(cx, |workspace, cx| {
 875            workspace.active_item_as::<Editor>(cx).unwrap()
 876        });
 877        editor.update_in(cx, |editor, window, cx| {
 878            editor.set_text("1\n2\n3\n4\n5\n6\n", window, cx)
 879        });
 880
 881        cx.simulate_keystrokes("cmd-shift-p");
 882        cx.simulate_input("go to line: Toggle");
 883        cx.simulate_keystrokes("enter");
 884
 885        workspace.update(cx, |workspace, cx| {
 886            assert!(workspace.active_modal::<GoToLine>(cx).is_some())
 887        });
 888
 889        cx.simulate_keystrokes("3 enter");
 890
 891        editor.update_in(cx, |editor, window, cx| {
 892            assert!(editor.focus_handle(cx).is_focused(window));
 893            assert_eq!(
 894                editor
 895                    .selections
 896                    .last::<Point>(&editor.display_snapshot(cx))
 897                    .range()
 898                    .start,
 899                Point::new(2, 0)
 900            );
 901        });
 902    }
 903
 904    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
 905        cx.update(|cx| {
 906            let app_state = AppState::test(cx);
 907            theme::init(theme::LoadThemes::JustBase, cx);
 908            editor::init(cx);
 909            menu::init();
 910            go_to_line::init(cx);
 911            workspace::init(app_state.clone(), cx);
 912            init(cx);
 913            cx.bind_keys(KeymapFile::load_panic_on_failure(
 914                r#"[
 915                    {
 916                        "bindings": {
 917                            "cmd-n": "workspace::NewFile",
 918                            "enter": "menu::Confirm",
 919                            "cmd-shift-p": "command_palette::Toggle",
 920                            "up": "menu::SelectPrevious",
 921                            "down": "menu::SelectNext"
 922                        }
 923                    }
 924                ]"#,
 925                cx,
 926            ));
 927            app_state
 928        })
 929    }
 930
 931    fn open_palette_with_history(
 932        workspace: &Entity<Workspace>,
 933        history: &[&str],
 934        cx: &mut VisualTestContext,
 935    ) -> Entity<Picker<CommandPaletteDelegate>> {
 936        cx.simulate_keystrokes("cmd-shift-p");
 937        cx.run_until_parked();
 938
 939        let palette = workspace.update(cx, |workspace, cx| {
 940            workspace
 941                .active_modal::<CommandPalette>(cx)
 942                .unwrap()
 943                .read(cx)
 944                .picker
 945                .clone()
 946        });
 947
 948        palette.update(cx, |palette, _cx| {
 949            palette.delegate.seed_history(history);
 950        });
 951
 952        palette
 953    }
 954
 955    #[gpui::test]
 956    async fn test_history_navigation_basic(cx: &mut TestAppContext) {
 957        let app_state = init_test(cx);
 958        let project = Project::test(app_state.fs.clone(), [], cx).await;
 959        let (multi_workspace, cx) =
 960            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
 961        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
 962
 963        let palette = open_palette_with_history(&workspace, &["backspace", "select all"], cx);
 964
 965        // Query should be empty initially
 966        palette.read_with(cx, |palette, cx| {
 967            assert_eq!(palette.query(cx), "");
 968        });
 969
 970        // Press up - should load most recent query "select all"
 971        cx.simulate_keystrokes("up");
 972        cx.background_executor.run_until_parked();
 973        palette.read_with(cx, |palette, cx| {
 974            assert_eq!(palette.query(cx), "select all");
 975        });
 976
 977        // Press up again - should load "backspace"
 978        cx.simulate_keystrokes("up");
 979        cx.background_executor.run_until_parked();
 980        palette.read_with(cx, |palette, cx| {
 981            assert_eq!(palette.query(cx), "backspace");
 982        });
 983
 984        // Press down - should go back to "select all"
 985        cx.simulate_keystrokes("down");
 986        cx.background_executor.run_until_parked();
 987        palette.read_with(cx, |palette, cx| {
 988            assert_eq!(palette.query(cx), "select all");
 989        });
 990
 991        // Press down again - should clear query (exit history mode)
 992        cx.simulate_keystrokes("down");
 993        cx.background_executor.run_until_parked();
 994        palette.read_with(cx, |palette, cx| {
 995            assert_eq!(palette.query(cx), "");
 996        });
 997    }
 998
 999    #[gpui::test]
1000    async fn test_history_mode_exit_on_typing(cx: &mut TestAppContext) {
1001        let app_state = init_test(cx);
1002        let project = Project::test(app_state.fs.clone(), [], cx).await;
1003        let (multi_workspace, cx) =
1004            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1005        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1006
1007        let palette = open_palette_with_history(&workspace, &["backspace"], cx);
1008
1009        // Press up to enter history mode
1010        cx.simulate_keystrokes("up");
1011        cx.background_executor.run_until_parked();
1012        palette.read_with(cx, |palette, cx| {
1013            assert_eq!(palette.query(cx), "backspace");
1014        });
1015
1016        // Type something - should append to the history query
1017        cx.simulate_input("x");
1018        cx.background_executor.run_until_parked();
1019        palette.read_with(cx, |palette, cx| {
1020            assert_eq!(palette.query(cx), "backspacex");
1021        });
1022    }
1023
1024    #[gpui::test]
1025    async fn test_history_navigation_with_suggestions(cx: &mut TestAppContext) {
1026        let app_state = init_test(cx);
1027        let project = Project::test(app_state.fs.clone(), [], cx).await;
1028        let (multi_workspace, cx) =
1029            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1030        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1031
1032        let palette = open_palette_with_history(&workspace, &["editor: close", "editor: open"], cx);
1033
1034        // Open palette with a query that has multiple matches
1035        cx.simulate_input("editor");
1036        cx.background_executor.run_until_parked();
1037
1038        // Should have multiple matches, selected_ix should be 0
1039        palette.read_with(cx, |palette, _| {
1040            assert!(palette.delegate.matches.len() > 1);
1041            assert_eq!(palette.delegate.selected_ix, 0);
1042        });
1043
1044        // Press down - should navigate to next suggestion (not history)
1045        cx.simulate_keystrokes("down");
1046        cx.background_executor.run_until_parked();
1047        palette.read_with(cx, |palette, _| {
1048            assert_eq!(palette.delegate.selected_ix, 1);
1049        });
1050
1051        // Press up - should go back to first suggestion
1052        cx.simulate_keystrokes("up");
1053        cx.background_executor.run_until_parked();
1054        palette.read_with(cx, |palette, _| {
1055            assert_eq!(palette.delegate.selected_ix, 0);
1056        });
1057
1058        // Press up again at top - should enter history mode and show previous query
1059        // that matches the "editor" prefix
1060        cx.simulate_keystrokes("up");
1061        cx.background_executor.run_until_parked();
1062        palette.read_with(cx, |palette, cx| {
1063            assert_eq!(palette.query(cx), "editor: open");
1064        });
1065    }
1066
1067    #[gpui::test]
1068    async fn test_history_prefix_search(cx: &mut TestAppContext) {
1069        let app_state = init_test(cx);
1070        let project = Project::test(app_state.fs.clone(), [], cx).await;
1071        let (multi_workspace, cx) =
1072            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1073        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1074
1075        let palette = open_palette_with_history(
1076            &workspace,
1077            &["open file", "select all", "select line", "backspace"],
1078            cx,
1079        );
1080
1081        // Type "sel" as a prefix
1082        cx.simulate_input("sel");
1083        cx.background_executor.run_until_parked();
1084
1085        // Press up - should get "select line" (most recent matching "sel")
1086        cx.simulate_keystrokes("up");
1087        cx.background_executor.run_until_parked();
1088        palette.read_with(cx, |palette, cx| {
1089            assert_eq!(palette.query(cx), "select line");
1090        });
1091
1092        // Press up again - should get "select all" (next matching "sel")
1093        cx.simulate_keystrokes("up");
1094        cx.background_executor.run_until_parked();
1095        palette.read_with(cx, |palette, cx| {
1096            assert_eq!(palette.query(cx), "select all");
1097        });
1098
1099        // Press up again - should stay at "select all" (no more matches for "sel")
1100        cx.simulate_keystrokes("up");
1101        cx.background_executor.run_until_parked();
1102        palette.read_with(cx, |palette, cx| {
1103            assert_eq!(palette.query(cx), "select all");
1104        });
1105
1106        // Press down - should go back to "select line"
1107        cx.simulate_keystrokes("down");
1108        cx.background_executor.run_until_parked();
1109        palette.read_with(cx, |palette, cx| {
1110            assert_eq!(palette.query(cx), "select line");
1111        });
1112
1113        // Press down again - should return to original prefix "sel"
1114        cx.simulate_keystrokes("down");
1115        cx.background_executor.run_until_parked();
1116        palette.read_with(cx, |palette, cx| {
1117            assert_eq!(palette.query(cx), "sel");
1118        });
1119    }
1120
1121    #[gpui::test]
1122    async fn test_history_prefix_search_no_matches(cx: &mut TestAppContext) {
1123        let app_state = init_test(cx);
1124        let project = Project::test(app_state.fs.clone(), [], cx).await;
1125        let (multi_workspace, cx) =
1126            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1127        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1128
1129        let palette =
1130            open_palette_with_history(&workspace, &["open file", "backspace", "select all"], cx);
1131
1132        // Type "xyz" as a prefix that doesn't match anything
1133        cx.simulate_input("xyz");
1134        cx.background_executor.run_until_parked();
1135
1136        // Press up - should stay at "xyz" (no matches)
1137        cx.simulate_keystrokes("up");
1138        cx.background_executor.run_until_parked();
1139        palette.read_with(cx, |palette, cx| {
1140            assert_eq!(palette.query(cx), "xyz");
1141        });
1142    }
1143
1144    #[gpui::test]
1145    async fn test_history_empty_prefix_searches_all(cx: &mut TestAppContext) {
1146        let app_state = init_test(cx);
1147        let project = Project::test(app_state.fs.clone(), [], cx).await;
1148        let (multi_workspace, cx) =
1149            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1150        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1151
1152        let palette = open_palette_with_history(&workspace, &["alpha", "beta", "gamma"], cx);
1153
1154        // With empty query, press up - should get "gamma" (most recent)
1155        cx.simulate_keystrokes("up");
1156        cx.background_executor.run_until_parked();
1157        palette.read_with(cx, |palette, cx| {
1158            assert_eq!(palette.query(cx), "gamma");
1159        });
1160
1161        // Press up - should get "beta"
1162        cx.simulate_keystrokes("up");
1163        cx.background_executor.run_until_parked();
1164        palette.read_with(cx, |palette, cx| {
1165            assert_eq!(palette.query(cx), "beta");
1166        });
1167
1168        // Press up - should get "alpha"
1169        cx.simulate_keystrokes("up");
1170        cx.background_executor.run_until_parked();
1171        palette.read_with(cx, |palette, cx| {
1172            assert_eq!(palette.query(cx), "alpha");
1173        });
1174
1175        // Press down - should get "beta"
1176        cx.simulate_keystrokes("down");
1177        cx.background_executor.run_until_parked();
1178        palette.read_with(cx, |palette, cx| {
1179            assert_eq!(palette.query(cx), "beta");
1180        });
1181
1182        // Press down - should get "gamma"
1183        cx.simulate_keystrokes("down");
1184        cx.background_executor.run_until_parked();
1185        palette.read_with(cx, |palette, cx| {
1186            assert_eq!(palette.query(cx), "gamma");
1187        });
1188
1189        // Press down - should return to empty string (exit history mode)
1190        cx.simulate_keystrokes("down");
1191        cx.background_executor.run_until_parked();
1192        palette.read_with(cx, |palette, cx| {
1193            assert_eq!(palette.query(cx), "");
1194        });
1195    }
1196}