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