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 .log_err();
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 .log_err();
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
683pub fn humanize_action_name(name: &str) -> String {
684 let capacity = name.len() + name.chars().filter(|c| c.is_uppercase()).count();
685 let mut result = String::with_capacity(capacity);
686 for char in name.chars() {
687 if char == ':' {
688 if result.ends_with(':') {
689 result.push(' ');
690 } else {
691 result.push(':');
692 }
693 } else if char == '_' {
694 result.push(' ');
695 } else if char.is_uppercase() {
696 if !result.ends_with(' ') {
697 result.push(' ');
698 }
699 result.extend(char.to_lowercase());
700 } else {
701 result.push(char);
702 }
703 }
704 result
705}
706
707impl std::fmt::Debug for Command {
708 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
709 f.debug_struct("Command")
710 .field("name", &self.name)
711 .finish_non_exhaustive()
712 }
713}
714
715#[cfg(test)]
716mod tests {
717 use std::sync::Arc;
718
719 use super::*;
720 use editor::Editor;
721 use go_to_line::GoToLine;
722 use gpui::{TestAppContext, VisualTestContext};
723 use language::Point;
724 use project::Project;
725 use settings::KeymapFile;
726 use workspace::{AppState, MultiWorkspace, Workspace};
727
728 #[test]
729 fn test_humanize_action_name() {
730 assert_eq!(
731 humanize_action_name("editor::GoToDefinition"),
732 "editor: go to definition"
733 );
734 assert_eq!(
735 humanize_action_name("editor::Backspace"),
736 "editor: backspace"
737 );
738 assert_eq!(
739 humanize_action_name("go_to_line::Deploy"),
740 "go to line: deploy"
741 );
742 }
743
744 #[test]
745 fn test_normalize_query() {
746 assert_eq!(
747 normalize_action_query("editor: backspace"),
748 "editor: backspace"
749 );
750 assert_eq!(
751 normalize_action_query("editor: backspace"),
752 "editor: backspace"
753 );
754 assert_eq!(
755 normalize_action_query("editor: backspace"),
756 "editor: backspace"
757 );
758 assert_eq!(
759 normalize_action_query("editor::GoToDefinition"),
760 "editor:GoToDefinition"
761 );
762 assert_eq!(
763 normalize_action_query("editor::::GoToDefinition"),
764 "editor:GoToDefinition"
765 );
766 assert_eq!(
767 normalize_action_query("editor: :GoToDefinition"),
768 "editor: :GoToDefinition"
769 );
770 }
771
772 #[gpui::test]
773 async fn test_command_palette(cx: &mut TestAppContext) {
774 persistence::COMMAND_PALETTE_HISTORY
775 .clear_all()
776 .await
777 .unwrap();
778 let app_state = init_test(cx);
779 let project = Project::test(app_state.fs.clone(), [], cx).await;
780 let (multi_workspace, cx) =
781 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
782 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
783
784 let editor = cx.new_window_entity(|window, cx| {
785 let mut editor = Editor::single_line(window, cx);
786 editor.set_text("abc", window, cx);
787 editor
788 });
789
790 workspace.update_in(cx, |workspace, window, cx| {
791 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
792 editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
793 });
794
795 cx.simulate_keystrokes("cmd-shift-p");
796
797 let palette = workspace.update(cx, |workspace, cx| {
798 workspace
799 .active_modal::<CommandPalette>(cx)
800 .unwrap()
801 .read(cx)
802 .picker
803 .clone()
804 });
805
806 palette.read_with(cx, |palette, _| {
807 assert!(palette.delegate.commands.len() > 5);
808 let is_sorted =
809 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
810 assert!(is_sorted(&palette.delegate.commands));
811 });
812
813 cx.simulate_input("bcksp");
814
815 palette.read_with(cx, |palette, _| {
816 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
817 });
818
819 cx.simulate_keystrokes("enter");
820
821 workspace.update(cx, |workspace, cx| {
822 assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
823 assert_eq!(editor.read(cx).text(cx), "ab")
824 });
825
826 // Add namespace filter, and redeploy the palette
827 cx.update(|_window, cx| {
828 CommandPaletteFilter::update_global(cx, |filter, _| {
829 filter.hide_namespace("editor");
830 });
831 });
832
833 cx.simulate_keystrokes("cmd-shift-p");
834 cx.simulate_input("bcksp");
835
836 let palette = workspace.update(cx, |workspace, cx| {
837 workspace
838 .active_modal::<CommandPalette>(cx)
839 .unwrap()
840 .read(cx)
841 .picker
842 .clone()
843 });
844 palette.read_with(cx, |palette, _| {
845 assert!(palette.delegate.matches.is_empty())
846 });
847 }
848 #[gpui::test]
849 async fn test_normalized_matches(cx: &mut TestAppContext) {
850 let app_state = init_test(cx);
851 let project = Project::test(app_state.fs.clone(), [], cx).await;
852 let (multi_workspace, cx) =
853 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
854 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
855
856 let editor = cx.new_window_entity(|window, cx| {
857 let mut editor = Editor::single_line(window, cx);
858 editor.set_text("abc", window, cx);
859 editor
860 });
861
862 workspace.update_in(cx, |workspace, window, cx| {
863 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
864 editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
865 });
866
867 // Test normalize (trimming whitespace and double colons)
868 cx.simulate_keystrokes("cmd-shift-p");
869
870 let palette = workspace.update(cx, |workspace, cx| {
871 workspace
872 .active_modal::<CommandPalette>(cx)
873 .unwrap()
874 .read(cx)
875 .picker
876 .clone()
877 });
878
879 cx.simulate_input("Editor:: Backspace");
880 palette.read_with(cx, |palette, _| {
881 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
882 });
883 }
884
885 #[gpui::test]
886 async fn test_go_to_line(cx: &mut TestAppContext) {
887 let app_state = init_test(cx);
888 let project = Project::test(app_state.fs.clone(), [], cx).await;
889 let (multi_workspace, cx) =
890 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
891 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
892
893 cx.simulate_keystrokes("cmd-n");
894
895 let editor = workspace.update(cx, |workspace, cx| {
896 workspace.active_item_as::<Editor>(cx).unwrap()
897 });
898 editor.update_in(cx, |editor, window, cx| {
899 editor.set_text("1\n2\n3\n4\n5\n6\n", window, cx)
900 });
901
902 cx.simulate_keystrokes("cmd-shift-p");
903 cx.simulate_input("go to line: Toggle");
904 cx.simulate_keystrokes("enter");
905
906 workspace.update(cx, |workspace, cx| {
907 assert!(workspace.active_modal::<GoToLine>(cx).is_some())
908 });
909
910 cx.simulate_keystrokes("3 enter");
911
912 editor.update_in(cx, |editor, window, cx| {
913 assert!(editor.focus_handle(cx).is_focused(window));
914 assert_eq!(
915 editor
916 .selections
917 .last::<Point>(&editor.display_snapshot(cx))
918 .range()
919 .start,
920 Point::new(2, 0)
921 );
922 });
923 }
924
925 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
926 cx.update(|cx| {
927 let app_state = AppState::test(cx);
928 theme::init(theme::LoadThemes::JustBase, cx);
929 editor::init(cx);
930 menu::init();
931 go_to_line::init(cx);
932 workspace::init(app_state.clone(), cx);
933 init(cx);
934 cx.bind_keys(KeymapFile::load_panic_on_failure(
935 r#"[
936 {
937 "bindings": {
938 "cmd-n": "workspace::NewFile",
939 "enter": "menu::Confirm",
940 "cmd-shift-p": "command_palette::Toggle",
941 "up": "menu::SelectPrevious",
942 "down": "menu::SelectNext"
943 }
944 }
945 ]"#,
946 cx,
947 ));
948 app_state
949 })
950 }
951
952 fn open_palette_with_history(
953 workspace: &Entity<Workspace>,
954 history: &[&str],
955 cx: &mut VisualTestContext,
956 ) -> Entity<Picker<CommandPaletteDelegate>> {
957 cx.simulate_keystrokes("cmd-shift-p");
958 cx.run_until_parked();
959
960 let palette = workspace.update(cx, |workspace, cx| {
961 workspace
962 .active_modal::<CommandPalette>(cx)
963 .unwrap()
964 .read(cx)
965 .picker
966 .clone()
967 });
968
969 palette.update(cx, |palette, _cx| {
970 palette.delegate.seed_history(history);
971 });
972
973 palette
974 }
975
976 #[gpui::test]
977 async fn test_history_navigation_basic(cx: &mut TestAppContext) {
978 let app_state = init_test(cx);
979 let project = Project::test(app_state.fs.clone(), [], cx).await;
980 let (multi_workspace, cx) =
981 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
982 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
983
984 let palette = open_palette_with_history(&workspace, &["backspace", "select all"], cx);
985
986 // Query should be empty initially
987 palette.read_with(cx, |palette, cx| {
988 assert_eq!(palette.query(cx), "");
989 });
990
991 // Press up - should load most recent query "select all"
992 cx.simulate_keystrokes("up");
993 cx.background_executor.run_until_parked();
994 palette.read_with(cx, |palette, cx| {
995 assert_eq!(palette.query(cx), "select all");
996 });
997
998 // Press up again - should load "backspace"
999 cx.simulate_keystrokes("up");
1000 cx.background_executor.run_until_parked();
1001 palette.read_with(cx, |palette, cx| {
1002 assert_eq!(palette.query(cx), "backspace");
1003 });
1004
1005 // Press down - should go back to "select all"
1006 cx.simulate_keystrokes("down");
1007 cx.background_executor.run_until_parked();
1008 palette.read_with(cx, |palette, cx| {
1009 assert_eq!(palette.query(cx), "select all");
1010 });
1011
1012 // Press down again - should clear query (exit history mode)
1013 cx.simulate_keystrokes("down");
1014 cx.background_executor.run_until_parked();
1015 palette.read_with(cx, |palette, cx| {
1016 assert_eq!(palette.query(cx), "");
1017 });
1018 }
1019
1020 #[gpui::test]
1021 async fn test_history_mode_exit_on_typing(cx: &mut TestAppContext) {
1022 let app_state = init_test(cx);
1023 let project = Project::test(app_state.fs.clone(), [], cx).await;
1024 let (multi_workspace, cx) =
1025 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1026 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1027
1028 let palette = open_palette_with_history(&workspace, &["backspace"], cx);
1029
1030 // Press up to enter history mode
1031 cx.simulate_keystrokes("up");
1032 cx.background_executor.run_until_parked();
1033 palette.read_with(cx, |palette, cx| {
1034 assert_eq!(palette.query(cx), "backspace");
1035 });
1036
1037 // Type something - should append to the history query
1038 cx.simulate_input("x");
1039 cx.background_executor.run_until_parked();
1040 palette.read_with(cx, |palette, cx| {
1041 assert_eq!(palette.query(cx), "backspacex");
1042 });
1043 }
1044
1045 #[gpui::test]
1046 async fn test_history_navigation_with_suggestions(cx: &mut TestAppContext) {
1047 let app_state = init_test(cx);
1048 let project = Project::test(app_state.fs.clone(), [], cx).await;
1049 let (multi_workspace, cx) =
1050 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1051 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1052
1053 let palette = open_palette_with_history(&workspace, &["editor: close", "editor: open"], cx);
1054
1055 // Open palette with a query that has multiple matches
1056 cx.simulate_input("editor");
1057 cx.background_executor.run_until_parked();
1058
1059 // Should have multiple matches, selected_ix should be 0
1060 palette.read_with(cx, |palette, _| {
1061 assert!(palette.delegate.matches.len() > 1);
1062 assert_eq!(palette.delegate.selected_ix, 0);
1063 });
1064
1065 // Press down - should navigate to next suggestion (not history)
1066 cx.simulate_keystrokes("down");
1067 cx.background_executor.run_until_parked();
1068 palette.read_with(cx, |palette, _| {
1069 assert_eq!(palette.delegate.selected_ix, 1);
1070 });
1071
1072 // Press up - should go back to first suggestion
1073 cx.simulate_keystrokes("up");
1074 cx.background_executor.run_until_parked();
1075 palette.read_with(cx, |palette, _| {
1076 assert_eq!(palette.delegate.selected_ix, 0);
1077 });
1078
1079 // Press up again at top - should enter history mode and show previous query
1080 // that matches the "editor" prefix
1081 cx.simulate_keystrokes("up");
1082 cx.background_executor.run_until_parked();
1083 palette.read_with(cx, |palette, cx| {
1084 assert_eq!(palette.query(cx), "editor: open");
1085 });
1086 }
1087
1088 #[gpui::test]
1089 async fn test_history_prefix_search(cx: &mut TestAppContext) {
1090 let app_state = init_test(cx);
1091 let project = Project::test(app_state.fs.clone(), [], cx).await;
1092 let (multi_workspace, cx) =
1093 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1094 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1095
1096 let palette = open_palette_with_history(
1097 &workspace,
1098 &["open file", "select all", "select line", "backspace"],
1099 cx,
1100 );
1101
1102 // Type "sel" as a prefix
1103 cx.simulate_input("sel");
1104 cx.background_executor.run_until_parked();
1105
1106 // Press up - should get "select line" (most recent matching "sel")
1107 cx.simulate_keystrokes("up");
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 up again - should get "select all" (next matching "sel")
1114 cx.simulate_keystrokes("up");
1115 cx.background_executor.run_until_parked();
1116 palette.read_with(cx, |palette, cx| {
1117 assert_eq!(palette.query(cx), "select all");
1118 });
1119
1120 // Press up again - should stay at "select all" (no more matches for "sel")
1121 cx.simulate_keystrokes("up");
1122 cx.background_executor.run_until_parked();
1123 palette.read_with(cx, |palette, cx| {
1124 assert_eq!(palette.query(cx), "select all");
1125 });
1126
1127 // Press down - should go back to "select line"
1128 cx.simulate_keystrokes("down");
1129 cx.background_executor.run_until_parked();
1130 palette.read_with(cx, |palette, cx| {
1131 assert_eq!(palette.query(cx), "select line");
1132 });
1133
1134 // Press down again - should return to original prefix "sel"
1135 cx.simulate_keystrokes("down");
1136 cx.background_executor.run_until_parked();
1137 palette.read_with(cx, |palette, cx| {
1138 assert_eq!(palette.query(cx), "sel");
1139 });
1140 }
1141
1142 #[gpui::test]
1143 async fn test_history_prefix_search_no_matches(cx: &mut TestAppContext) {
1144 let app_state = init_test(cx);
1145 let project = Project::test(app_state.fs.clone(), [], cx).await;
1146 let (multi_workspace, cx) =
1147 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1148 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1149
1150 let palette =
1151 open_palette_with_history(&workspace, &["open file", "backspace", "select all"], cx);
1152
1153 // Type "xyz" as a prefix that doesn't match anything
1154 cx.simulate_input("xyz");
1155 cx.background_executor.run_until_parked();
1156
1157 // Press up - should stay at "xyz" (no matches)
1158 cx.simulate_keystrokes("up");
1159 cx.background_executor.run_until_parked();
1160 palette.read_with(cx, |palette, cx| {
1161 assert_eq!(palette.query(cx), "xyz");
1162 });
1163 }
1164
1165 #[gpui::test]
1166 async fn test_history_empty_prefix_searches_all(cx: &mut TestAppContext) {
1167 let app_state = init_test(cx);
1168 let project = Project::test(app_state.fs.clone(), [], cx).await;
1169 let (multi_workspace, cx) =
1170 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
1171 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
1172
1173 let palette = open_palette_with_history(&workspace, &["alpha", "beta", "gamma"], cx);
1174
1175 // With empty query, press up - should get "gamma" (most recent)
1176 cx.simulate_keystrokes("up");
1177 cx.background_executor.run_until_parked();
1178 palette.read_with(cx, |palette, cx| {
1179 assert_eq!(palette.query(cx), "gamma");
1180 });
1181
1182 // Press up - should get "beta"
1183 cx.simulate_keystrokes("up");
1184 cx.background_executor.run_until_parked();
1185 palette.read_with(cx, |palette, cx| {
1186 assert_eq!(palette.query(cx), "beta");
1187 });
1188
1189 // Press up - should get "alpha"
1190 cx.simulate_keystrokes("up");
1191 cx.background_executor.run_until_parked();
1192 palette.read_with(cx, |palette, cx| {
1193 assert_eq!(palette.query(cx), "alpha");
1194 });
1195
1196 // Press down - should get "beta"
1197 cx.simulate_keystrokes("down");
1198 cx.background_executor.run_until_parked();
1199 palette.read_with(cx, |palette, cx| {
1200 assert_eq!(palette.query(cx), "beta");
1201 });
1202
1203 // Press down - should get "gamma"
1204 cx.simulate_keystrokes("down");
1205 cx.background_executor.run_until_parked();
1206 palette.read_with(cx, |palette, cx| {
1207 assert_eq!(palette.query(cx), "gamma");
1208 });
1209
1210 // Press down - should return to empty string (exit history mode)
1211 cx.simulate_keystrokes("down");
1212 cx.background_executor.run_until_parked();
1213 palette.read_with(cx, |palette, cx| {
1214 assert_eq!(palette.query(cx), "");
1215 });
1216 }
1217}