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, 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 (workspace, cx) =
781 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
782
783 let editor = cx.new_window_entity(|window, cx| {
784 let mut editor = Editor::single_line(window, cx);
785 editor.set_text("abc", window, cx);
786 editor
787 });
788
789 workspace.update_in(cx, |workspace, window, cx| {
790 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
791 editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
792 });
793
794 cx.simulate_keystrokes("cmd-shift-p");
795
796 let palette = workspace.update(cx, |workspace, cx| {
797 workspace
798 .active_modal::<CommandPalette>(cx)
799 .unwrap()
800 .read(cx)
801 .picker
802 .clone()
803 });
804
805 palette.read_with(cx, |palette, _| {
806 assert!(palette.delegate.commands.len() > 5);
807 let is_sorted =
808 |actions: &[Command]| actions.windows(2).all(|pair| pair[0].name <= pair[1].name);
809 assert!(is_sorted(&palette.delegate.commands));
810 });
811
812 cx.simulate_input("bcksp");
813
814 palette.read_with(cx, |palette, _| {
815 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
816 });
817
818 cx.simulate_keystrokes("enter");
819
820 workspace.update(cx, |workspace, cx| {
821 assert!(workspace.active_modal::<CommandPalette>(cx).is_none());
822 assert_eq!(editor.read(cx).text(cx), "ab")
823 });
824
825 // Add namespace filter, and redeploy the palette
826 cx.update(|_window, cx| {
827 CommandPaletteFilter::update_global(cx, |filter, _| {
828 filter.hide_namespace("editor");
829 });
830 });
831
832 cx.simulate_keystrokes("cmd-shift-p");
833 cx.simulate_input("bcksp");
834
835 let palette = workspace.update(cx, |workspace, cx| {
836 workspace
837 .active_modal::<CommandPalette>(cx)
838 .unwrap()
839 .read(cx)
840 .picker
841 .clone()
842 });
843 palette.read_with(cx, |palette, _| {
844 assert!(palette.delegate.matches.is_empty())
845 });
846 }
847 #[gpui::test]
848 async fn test_normalized_matches(cx: &mut TestAppContext) {
849 let app_state = init_test(cx);
850 let project = Project::test(app_state.fs.clone(), [], cx).await;
851 let (workspace, cx) =
852 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
853
854 let editor = cx.new_window_entity(|window, cx| {
855 let mut editor = Editor::single_line(window, cx);
856 editor.set_text("abc", window, cx);
857 editor
858 });
859
860 workspace.update_in(cx, |workspace, window, cx| {
861 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
862 editor.update(cx, |editor, cx| window.focus(&editor.focus_handle(cx), cx))
863 });
864
865 // Test normalize (trimming whitespace and double colons)
866 cx.simulate_keystrokes("cmd-shift-p");
867
868 let palette = workspace.update(cx, |workspace, cx| {
869 workspace
870 .active_modal::<CommandPalette>(cx)
871 .unwrap()
872 .read(cx)
873 .picker
874 .clone()
875 });
876
877 cx.simulate_input("Editor:: Backspace");
878 palette.read_with(cx, |palette, _| {
879 assert_eq!(palette.delegate.matches[0].string, "editor: backspace");
880 });
881 }
882
883 #[gpui::test]
884 async fn test_go_to_line(cx: &mut TestAppContext) {
885 let app_state = init_test(cx);
886 let project = Project::test(app_state.fs.clone(), [], cx).await;
887 let (workspace, cx) =
888 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
889
890 cx.simulate_keystrokes("cmd-n");
891
892 let editor = workspace.update(cx, |workspace, cx| {
893 workspace.active_item_as::<Editor>(cx).unwrap()
894 });
895 editor.update_in(cx, |editor, window, cx| {
896 editor.set_text("1\n2\n3\n4\n5\n6\n", window, cx)
897 });
898
899 cx.simulate_keystrokes("cmd-shift-p");
900 cx.simulate_input("go to line: Toggle");
901 cx.simulate_keystrokes("enter");
902
903 workspace.update(cx, |workspace, cx| {
904 assert!(workspace.active_modal::<GoToLine>(cx).is_some())
905 });
906
907 cx.simulate_keystrokes("3 enter");
908
909 editor.update_in(cx, |editor, window, cx| {
910 assert!(editor.focus_handle(cx).is_focused(window));
911 assert_eq!(
912 editor
913 .selections
914 .last::<Point>(&editor.display_snapshot(cx))
915 .range()
916 .start,
917 Point::new(2, 0)
918 );
919 });
920 }
921
922 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
923 cx.update(|cx| {
924 let app_state = AppState::test(cx);
925 theme::init(theme::LoadThemes::JustBase, cx);
926 editor::init(cx);
927 menu::init();
928 go_to_line::init(cx);
929 workspace::init(app_state.clone(), cx);
930 init(cx);
931 cx.bind_keys(KeymapFile::load_panic_on_failure(
932 r#"[
933 {
934 "bindings": {
935 "cmd-n": "workspace::NewFile",
936 "enter": "menu::Confirm",
937 "cmd-shift-p": "command_palette::Toggle",
938 "up": "menu::SelectPrevious",
939 "down": "menu::SelectNext"
940 }
941 }
942 ]"#,
943 cx,
944 ));
945 app_state
946 })
947 }
948
949 fn open_palette_with_history(
950 workspace: &Entity<Workspace>,
951 history: &[&str],
952 cx: &mut VisualTestContext,
953 ) -> Entity<Picker<CommandPaletteDelegate>> {
954 cx.simulate_keystrokes("cmd-shift-p");
955 cx.run_until_parked();
956
957 let palette = workspace.update(cx, |workspace, cx| {
958 workspace
959 .active_modal::<CommandPalette>(cx)
960 .unwrap()
961 .read(cx)
962 .picker
963 .clone()
964 });
965
966 palette.update(cx, |palette, _cx| {
967 palette.delegate.seed_history(history);
968 });
969
970 palette
971 }
972
973 #[gpui::test]
974 async fn test_history_navigation_basic(cx: &mut TestAppContext) {
975 let app_state = init_test(cx);
976 let project = Project::test(app_state.fs.clone(), [], cx).await;
977 let (workspace, cx) =
978 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
979
980 let palette = open_palette_with_history(&workspace, &["backspace", "select all"], cx);
981
982 // Query should be empty initially
983 palette.read_with(cx, |palette, cx| {
984 assert_eq!(palette.query(cx), "");
985 });
986
987 // Press up - should load most recent query "select all"
988 cx.simulate_keystrokes("up");
989 cx.background_executor.run_until_parked();
990 palette.read_with(cx, |palette, cx| {
991 assert_eq!(palette.query(cx), "select all");
992 });
993
994 // Press up again - should load "backspace"
995 cx.simulate_keystrokes("up");
996 cx.background_executor.run_until_parked();
997 palette.read_with(cx, |palette, cx| {
998 assert_eq!(palette.query(cx), "backspace");
999 });
1000
1001 // Press down - should go back to "select all"
1002 cx.simulate_keystrokes("down");
1003 cx.background_executor.run_until_parked();
1004 palette.read_with(cx, |palette, cx| {
1005 assert_eq!(palette.query(cx), "select all");
1006 });
1007
1008 // Press down again - should clear query (exit history mode)
1009 cx.simulate_keystrokes("down");
1010 cx.background_executor.run_until_parked();
1011 palette.read_with(cx, |palette, cx| {
1012 assert_eq!(palette.query(cx), "");
1013 });
1014 }
1015
1016 #[gpui::test]
1017 async fn test_history_mode_exit_on_typing(cx: &mut TestAppContext) {
1018 let app_state = init_test(cx);
1019 let project = Project::test(app_state.fs.clone(), [], cx).await;
1020 let (workspace, cx) =
1021 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1022
1023 let palette = open_palette_with_history(&workspace, &["backspace"], cx);
1024
1025 // Press up to enter history mode
1026 cx.simulate_keystrokes("up");
1027 cx.background_executor.run_until_parked();
1028 palette.read_with(cx, |palette, cx| {
1029 assert_eq!(palette.query(cx), "backspace");
1030 });
1031
1032 // Type something - should append to the history query
1033 cx.simulate_input("x");
1034 cx.background_executor.run_until_parked();
1035 palette.read_with(cx, |palette, cx| {
1036 assert_eq!(palette.query(cx), "backspacex");
1037 });
1038 }
1039
1040 #[gpui::test]
1041 async fn test_history_navigation_with_suggestions(cx: &mut TestAppContext) {
1042 let app_state = init_test(cx);
1043 let project = Project::test(app_state.fs.clone(), [], cx).await;
1044 let (workspace, cx) =
1045 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1046
1047 let palette = open_palette_with_history(&workspace, &["editor: close", "editor: open"], cx);
1048
1049 // Open palette with a query that has multiple matches
1050 cx.simulate_input("editor");
1051 cx.background_executor.run_until_parked();
1052
1053 // Should have multiple matches, selected_ix should be 0
1054 palette.read_with(cx, |palette, _| {
1055 assert!(palette.delegate.matches.len() > 1);
1056 assert_eq!(palette.delegate.selected_ix, 0);
1057 });
1058
1059 // Press down - should navigate to next suggestion (not history)
1060 cx.simulate_keystrokes("down");
1061 cx.background_executor.run_until_parked();
1062 palette.read_with(cx, |palette, _| {
1063 assert_eq!(palette.delegate.selected_ix, 1);
1064 });
1065
1066 // Press up - should go back to first suggestion
1067 cx.simulate_keystrokes("up");
1068 cx.background_executor.run_until_parked();
1069 palette.read_with(cx, |palette, _| {
1070 assert_eq!(palette.delegate.selected_ix, 0);
1071 });
1072
1073 // Press up again at top - should enter history mode and show previous query
1074 // that matches the "editor" prefix
1075 cx.simulate_keystrokes("up");
1076 cx.background_executor.run_until_parked();
1077 palette.read_with(cx, |palette, cx| {
1078 assert_eq!(palette.query(cx), "editor: open");
1079 });
1080 }
1081
1082 #[gpui::test]
1083 async fn test_history_prefix_search(cx: &mut TestAppContext) {
1084 let app_state = init_test(cx);
1085 let project = Project::test(app_state.fs.clone(), [], cx).await;
1086 let (workspace, cx) =
1087 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1088
1089 let palette = open_palette_with_history(
1090 &workspace,
1091 &["open file", "select all", "select line", "backspace"],
1092 cx,
1093 );
1094
1095 // Type "sel" as a prefix
1096 cx.simulate_input("sel");
1097 cx.background_executor.run_until_parked();
1098
1099 // Press up - should get "select line" (most recent matching "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 line");
1104 });
1105
1106 // Press up again - should get "select all" (next 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 all");
1111 });
1112
1113 // Press up again - should stay at "select all" (no more matches for "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 down - should go back to "select line"
1121 cx.simulate_keystrokes("down");
1122 cx.background_executor.run_until_parked();
1123 palette.read_with(cx, |palette, cx| {
1124 assert_eq!(palette.query(cx), "select line");
1125 });
1126
1127 // Press down again - should return to original prefix "sel"
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), "sel");
1132 });
1133 }
1134
1135 #[gpui::test]
1136 async fn test_history_prefix_search_no_matches(cx: &mut TestAppContext) {
1137 let app_state = init_test(cx);
1138 let project = Project::test(app_state.fs.clone(), [], cx).await;
1139 let (workspace, cx) =
1140 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1141
1142 let palette =
1143 open_palette_with_history(&workspace, &["open file", "backspace", "select all"], cx);
1144
1145 // Type "xyz" as a prefix that doesn't match anything
1146 cx.simulate_input("xyz");
1147 cx.background_executor.run_until_parked();
1148
1149 // Press up - should stay at "xyz" (no matches)
1150 cx.simulate_keystrokes("up");
1151 cx.background_executor.run_until_parked();
1152 palette.read_with(cx, |palette, cx| {
1153 assert_eq!(palette.query(cx), "xyz");
1154 });
1155 }
1156
1157 #[gpui::test]
1158 async fn test_history_empty_prefix_searches_all(cx: &mut TestAppContext) {
1159 let app_state = init_test(cx);
1160 let project = Project::test(app_state.fs.clone(), [], cx).await;
1161 let (workspace, cx) =
1162 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1163
1164 let palette = open_palette_with_history(&workspace, &["alpha", "beta", "gamma"], cx);
1165
1166 // With empty query, press up - should get "gamma" (most recent)
1167 cx.simulate_keystrokes("up");
1168 cx.background_executor.run_until_parked();
1169 palette.read_with(cx, |palette, cx| {
1170 assert_eq!(palette.query(cx), "gamma");
1171 });
1172
1173 // Press up - should get "beta"
1174 cx.simulate_keystrokes("up");
1175 cx.background_executor.run_until_parked();
1176 palette.read_with(cx, |palette, cx| {
1177 assert_eq!(palette.query(cx), "beta");
1178 });
1179
1180 // Press up - should get "alpha"
1181 cx.simulate_keystrokes("up");
1182 cx.background_executor.run_until_parked();
1183 palette.read_with(cx, |palette, cx| {
1184 assert_eq!(palette.query(cx), "alpha");
1185 });
1186
1187 // Press down - should get "beta"
1188 cx.simulate_keystrokes("down");
1189 cx.background_executor.run_until_parked();
1190 palette.read_with(cx, |palette, cx| {
1191 assert_eq!(palette.query(cx), "beta");
1192 });
1193
1194 // Press down - should get "gamma"
1195 cx.simulate_keystrokes("down");
1196 cx.background_executor.run_until_parked();
1197 palette.read_with(cx, |palette, cx| {
1198 assert_eq!(palette.query(cx), "gamma");
1199 });
1200
1201 // Press down - should return to empty string (exit history mode)
1202 cx.simulate_keystrokes("down");
1203 cx.background_executor.run_until_parked();
1204 palette.read_with(cx, |palette, cx| {
1205 assert_eq!(palette.query(cx), "");
1206 });
1207 }
1208}