1use fuzzy::{StringMatch, StringMatchCandidate};
2use gpui::{
3 div, px, uniform_list, AnyElement, BackgroundExecutor, Div, Entity, Focusable, FontWeight,
4 ListSizingBehavior, ScrollStrategy, SharedString, Size, StrikethroughStyle, StyledText,
5 UniformListScrollHandle,
6};
7use language::Buffer;
8use language::CodeLabel;
9use markdown::Markdown;
10use multi_buffer::{Anchor, ExcerptId};
11use ordered_float::OrderedFloat;
12use project::lsp_store::CompletionDocumentation;
13use project::CompletionSource;
14use project::{CodeAction, Completion, TaskSourceKind};
15
16use std::{
17 cell::RefCell,
18 cmp::{min, Reverse},
19 iter,
20 ops::Range,
21 rc::Rc,
22};
23use task::ResolvedTask;
24use ui::{prelude::*, Color, IntoElement, ListItem, Pixels, Popover, Styled};
25use util::ResultExt;
26
27use crate::hover_popover::{hover_markdown_style, open_markdown_url};
28use crate::{
29 actions::{ConfirmCodeAction, ConfirmCompletion},
30 split_words, styled_runs_for_code_label, CodeActionProvider, CompletionId, CompletionProvider,
31 DisplayRow, Editor, EditorStyle, ResolvedTasks,
32};
33
34pub const MENU_GAP: Pixels = px(4.);
35pub const MENU_ASIDE_X_PADDING: Pixels = px(16.);
36pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
37pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
38
39pub enum CodeContextMenu {
40 Completions(CompletionsMenu),
41 CodeActions(CodeActionsMenu),
42}
43
44impl CodeContextMenu {
45 pub fn select_first(
46 &mut self,
47 provider: Option<&dyn CompletionProvider>,
48 cx: &mut Context<Editor>,
49 ) -> bool {
50 if self.visible() {
51 match self {
52 CodeContextMenu::Completions(menu) => menu.select_first(provider, cx),
53 CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
54 }
55 true
56 } else {
57 false
58 }
59 }
60
61 pub fn select_prev(
62 &mut self,
63 provider: Option<&dyn CompletionProvider>,
64 cx: &mut Context<Editor>,
65 ) -> bool {
66 if self.visible() {
67 match self {
68 CodeContextMenu::Completions(menu) => menu.select_prev(provider, cx),
69 CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
70 }
71 true
72 } else {
73 false
74 }
75 }
76
77 pub fn select_next(
78 &mut self,
79 provider: Option<&dyn CompletionProvider>,
80 cx: &mut Context<Editor>,
81 ) -> bool {
82 if self.visible() {
83 match self {
84 CodeContextMenu::Completions(menu) => menu.select_next(provider, cx),
85 CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
86 }
87 true
88 } else {
89 false
90 }
91 }
92
93 pub fn select_last(
94 &mut self,
95 provider: Option<&dyn CompletionProvider>,
96 cx: &mut Context<Editor>,
97 ) -> bool {
98 if self.visible() {
99 match self {
100 CodeContextMenu::Completions(menu) => menu.select_last(provider, cx),
101 CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
102 }
103 true
104 } else {
105 false
106 }
107 }
108
109 pub fn visible(&self) -> bool {
110 match self {
111 CodeContextMenu::Completions(menu) => menu.visible(),
112 CodeContextMenu::CodeActions(menu) => menu.visible(),
113 }
114 }
115
116 pub fn origin(&self) -> ContextMenuOrigin {
117 match self {
118 CodeContextMenu::Completions(menu) => menu.origin(),
119 CodeContextMenu::CodeActions(menu) => menu.origin(),
120 }
121 }
122
123 pub fn render(
124 &self,
125 style: &EditorStyle,
126 max_height_in_lines: u32,
127 y_flipped: bool,
128 window: &mut Window,
129 cx: &mut Context<Editor>,
130 ) -> AnyElement {
131 match self {
132 CodeContextMenu::Completions(menu) => {
133 menu.render(style, max_height_in_lines, y_flipped, window, cx)
134 }
135 CodeContextMenu::CodeActions(menu) => {
136 menu.render(style, max_height_in_lines, y_flipped, window, cx)
137 }
138 }
139 }
140
141 pub fn render_aside(
142 &mut self,
143 editor: &Editor,
144 max_size: Size<Pixels>,
145 window: &mut Window,
146 cx: &mut Context<Editor>,
147 ) -> Option<AnyElement> {
148 match self {
149 CodeContextMenu::Completions(menu) => menu.render_aside(editor, max_size, window, cx),
150 CodeContextMenu::CodeActions(_) => None,
151 }
152 }
153
154 pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
155 match self {
156 CodeContextMenu::Completions(completions_menu) => completions_menu
157 .markdown_element
158 .as_ref()
159 .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
160 CodeContextMenu::CodeActions(_) => false,
161 }
162 }
163}
164
165pub enum ContextMenuOrigin {
166 Cursor,
167 GutterIndicator(DisplayRow),
168}
169
170#[derive(Clone, Debug)]
171pub struct CompletionsMenu {
172 pub id: CompletionId,
173 sort_completions: bool,
174 pub initial_position: Anchor,
175 pub buffer: Entity<Buffer>,
176 pub completions: Rc<RefCell<Box<[Completion]>>>,
177 match_candidates: Rc<[StringMatchCandidate]>,
178 pub entries: Rc<RefCell<Vec<StringMatch>>>,
179 pub selected_item: usize,
180 scroll_handle: UniformListScrollHandle,
181 resolve_completions: bool,
182 show_completion_documentation: bool,
183 last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
184 markdown_element: Option<Entity<Markdown>>,
185}
186
187impl CompletionsMenu {
188 pub fn new(
189 id: CompletionId,
190 sort_completions: bool,
191 show_completion_documentation: bool,
192 initial_position: Anchor,
193 buffer: Entity<Buffer>,
194 completions: Box<[Completion]>,
195 ) -> Self {
196 let match_candidates = completions
197 .iter()
198 .enumerate()
199 .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
200 .collect();
201
202 Self {
203 id,
204 sort_completions,
205 initial_position,
206 buffer,
207 show_completion_documentation,
208 completions: RefCell::new(completions).into(),
209 match_candidates,
210 entries: RefCell::new(Vec::new()).into(),
211 selected_item: 0,
212 scroll_handle: UniformListScrollHandle::new(),
213 resolve_completions: true,
214 last_rendered_range: RefCell::new(None).into(),
215 markdown_element: None,
216 }
217 }
218
219 pub fn new_snippet_choices(
220 id: CompletionId,
221 sort_completions: bool,
222 choices: &Vec<String>,
223 selection: Range<Anchor>,
224 buffer: Entity<Buffer>,
225 ) -> Self {
226 let completions = choices
227 .iter()
228 .map(|choice| Completion {
229 old_range: selection.start.text_anchor..selection.end.text_anchor,
230 new_text: choice.to_string(),
231 label: CodeLabel {
232 text: choice.to_string(),
233 runs: Default::default(),
234 filter_range: Default::default(),
235 },
236 documentation: None,
237 confirm: None,
238 source: CompletionSource::Custom,
239 })
240 .collect();
241
242 let match_candidates = choices
243 .iter()
244 .enumerate()
245 .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
246 .collect();
247 let entries = choices
248 .iter()
249 .enumerate()
250 .map(|(id, completion)| StringMatch {
251 candidate_id: id,
252 score: 1.,
253 positions: vec![],
254 string: completion.clone(),
255 })
256 .collect::<Vec<_>>();
257 Self {
258 id,
259 sort_completions,
260 initial_position: selection.start,
261 buffer,
262 completions: RefCell::new(completions).into(),
263 match_candidates,
264 entries: RefCell::new(entries).into(),
265 selected_item: 0,
266 scroll_handle: UniformListScrollHandle::new(),
267 resolve_completions: false,
268 show_completion_documentation: false,
269 last_rendered_range: RefCell::new(None).into(),
270 markdown_element: None,
271 }
272 }
273
274 fn select_first(
275 &mut self,
276 provider: Option<&dyn CompletionProvider>,
277 cx: &mut Context<Editor>,
278 ) {
279 let index = if self.scroll_handle.y_flipped() {
280 self.entries.borrow().len() - 1
281 } else {
282 0
283 };
284 self.update_selection_index(index, provider, cx);
285 }
286
287 fn select_last(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
288 let index = if self.scroll_handle.y_flipped() {
289 0
290 } else {
291 self.entries.borrow().len() - 1
292 };
293 self.update_selection_index(index, provider, cx);
294 }
295
296 fn select_prev(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
297 let index = if self.scroll_handle.y_flipped() {
298 self.next_match_index()
299 } else {
300 self.prev_match_index()
301 };
302 self.update_selection_index(index, provider, cx);
303 }
304
305 fn select_next(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
306 let index = if self.scroll_handle.y_flipped() {
307 self.prev_match_index()
308 } else {
309 self.next_match_index()
310 };
311 self.update_selection_index(index, provider, cx);
312 }
313
314 fn update_selection_index(
315 &mut self,
316 match_index: usize,
317 provider: Option<&dyn CompletionProvider>,
318 cx: &mut Context<Editor>,
319 ) {
320 if self.selected_item != match_index {
321 self.selected_item = match_index;
322 self.scroll_handle
323 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
324 self.resolve_visible_completions(provider, cx);
325 cx.notify();
326 }
327 }
328
329 fn prev_match_index(&self) -> usize {
330 if self.selected_item > 0 {
331 self.selected_item - 1
332 } else {
333 self.entries.borrow().len() - 1
334 }
335 }
336
337 fn next_match_index(&self) -> usize {
338 if self.selected_item + 1 < self.entries.borrow().len() {
339 self.selected_item + 1
340 } else {
341 0
342 }
343 }
344
345 pub fn resolve_visible_completions(
346 &mut self,
347 provider: Option<&dyn CompletionProvider>,
348 cx: &mut Context<Editor>,
349 ) {
350 if !self.resolve_completions {
351 return;
352 }
353 let Some(provider) = provider else {
354 return;
355 };
356
357 // Attempt to resolve completions for every item that will be displayed. This matters
358 // because single line documentation may be displayed inline with the completion.
359 //
360 // When navigating to the very beginning or end of completions, `last_rendered_range` may
361 // have no overlap with the completions that will be displayed, so instead use a range based
362 // on the last rendered count.
363 const APPROXIMATE_VISIBLE_COUNT: usize = 12;
364 let last_rendered_range = self.last_rendered_range.borrow().clone();
365 let visible_count = last_rendered_range
366 .clone()
367 .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
368 let entries = self.entries.borrow();
369 let entry_range = if self.selected_item == 0 {
370 0..min(visible_count, entries.len())
371 } else if self.selected_item == entries.len() - 1 {
372 entries.len().saturating_sub(visible_count)..entries.len()
373 } else {
374 last_rendered_range.map_or(0..0, |range| {
375 min(range.start, entries.len())..min(range.end, entries.len())
376 })
377 };
378
379 // Expand the range to resolve more completions than are predicted to be visible, to reduce
380 // jank on navigation.
381 const EXTRA_TO_RESOLVE: usize = 4;
382 let entry_indices = util::iterate_expanded_and_wrapped_usize_range(
383 entry_range.clone(),
384 EXTRA_TO_RESOLVE,
385 EXTRA_TO_RESOLVE,
386 entries.len(),
387 );
388
389 // Avoid work by sometimes filtering out completions that already have documentation.
390 // This filtering doesn't happen if the completions are currently being updated.
391 let completions = self.completions.borrow();
392 let candidate_ids = entry_indices
393 .map(|i| entries[i].candidate_id)
394 .filter(|i| completions[*i].documentation.is_none());
395
396 // Current selection is always resolved even if it already has documentation, to handle
397 // out-of-spec language servers that return more results later.
398 let selected_candidate_id = entries[self.selected_item].candidate_id;
399 let candidate_ids = iter::once(selected_candidate_id)
400 .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
401 .collect::<Vec<usize>>();
402 drop(entries);
403
404 if candidate_ids.is_empty() {
405 return;
406 }
407
408 let resolve_task = provider.resolve_completions(
409 self.buffer.clone(),
410 candidate_ids,
411 self.completions.clone(),
412 cx,
413 );
414
415 cx.spawn(move |editor, mut cx| async move {
416 if let Some(true) = resolve_task.await.log_err() {
417 editor.update(&mut cx, |_, cx| cx.notify()).ok();
418 }
419 })
420 .detach();
421 }
422
423 pub fn visible(&self) -> bool {
424 !self.entries.borrow().is_empty()
425 }
426
427 fn origin(&self) -> ContextMenuOrigin {
428 ContextMenuOrigin::Cursor
429 }
430
431 fn render(
432 &self,
433 style: &EditorStyle,
434 max_height_in_lines: u32,
435 y_flipped: bool,
436 window: &mut Window,
437 cx: &mut Context<Editor>,
438 ) -> AnyElement {
439 let completions = self.completions.borrow_mut();
440 let show_completion_documentation = self.show_completion_documentation;
441 let widest_completion_ix = self
442 .entries
443 .borrow()
444 .iter()
445 .enumerate()
446 .max_by_key(|(_, mat)| {
447 let completion = &completions[mat.candidate_id];
448 let documentation = &completion.documentation;
449
450 let mut len = completion.label.text.chars().count();
451 if let Some(CompletionDocumentation::SingleLine(text)) = documentation {
452 if show_completion_documentation {
453 len += text.chars().count();
454 }
455 }
456
457 len
458 })
459 .map(|(ix, _)| ix);
460 drop(completions);
461
462 let selected_item = self.selected_item;
463 let completions = self.completions.clone();
464 let entries = self.entries.clone();
465 let last_rendered_range = self.last_rendered_range.clone();
466 let style = style.clone();
467 let list = uniform_list(
468 cx.entity().clone(),
469 "completions",
470 self.entries.borrow().len(),
471 move |_editor, range, _window, cx| {
472 last_rendered_range.borrow_mut().replace(range.clone());
473 let start_ix = range.start;
474 let completions_guard = completions.borrow_mut();
475
476 entries.borrow()[range]
477 .iter()
478 .enumerate()
479 .map(|(ix, mat)| {
480 let item_ix = start_ix + ix;
481 let completion = &completions_guard[mat.candidate_id];
482 let documentation = if show_completion_documentation {
483 &completion.documentation
484 } else {
485 &None
486 };
487
488 let filter_start = completion.label.filter_range.start;
489 let highlights = gpui::combine_highlights(
490 mat.ranges().map(|range| {
491 (
492 filter_start + range.start..filter_start + range.end,
493 FontWeight::BOLD.into(),
494 )
495 }),
496 styled_runs_for_code_label(&completion.label, &style.syntax).map(
497 |(range, mut highlight)| {
498 // Ignore font weight for syntax highlighting, as we'll use it
499 // for fuzzy matches.
500 highlight.font_weight = None;
501 if completion
502 .source
503 .lsp_completion(false)
504 .and_then(|lsp_completion| lsp_completion.deprecated)
505 .unwrap_or(false)
506 {
507 highlight.strikethrough = Some(StrikethroughStyle {
508 thickness: 1.0.into(),
509 ..Default::default()
510 });
511 highlight.color = Some(cx.theme().colors().text_muted);
512 }
513
514 (range, highlight)
515 },
516 ),
517 );
518
519 let completion_label = StyledText::new(completion.label.text.clone())
520 .with_default_highlights(&style.text, highlights);
521 let documentation_label = if let Some(
522 CompletionDocumentation::SingleLine(text),
523 ) = documentation
524 {
525 if text.trim().is_empty() {
526 None
527 } else {
528 Some(
529 Label::new(text.clone())
530 .ml_4()
531 .size(LabelSize::Small)
532 .color(Color::Muted),
533 )
534 }
535 } else {
536 None
537 };
538 let color_swatch = completion
539 .color()
540 .map(|color| div().size_4().bg(color).rounded_xs());
541
542 div().min_w(px(280.)).max_w(px(540.)).child(
543 ListItem::new(mat.candidate_id)
544 .inset(true)
545 .toggle_state(item_ix == selected_item)
546 .on_click(cx.listener(move |editor, _event, window, cx| {
547 cx.stop_propagation();
548 if let Some(task) = editor.confirm_completion(
549 &ConfirmCompletion {
550 item_ix: Some(item_ix),
551 },
552 window,
553 cx,
554 ) {
555 task.detach_and_log_err(cx)
556 }
557 }))
558 .start_slot::<Div>(color_swatch)
559 .child(h_flex().overflow_hidden().child(completion_label))
560 .end_slot::<Label>(documentation_label),
561 )
562 })
563 .collect()
564 },
565 )
566 .occlude()
567 .max_h(max_height_in_lines as f32 * window.line_height())
568 .track_scroll(self.scroll_handle.clone())
569 .y_flipped(y_flipped)
570 .with_width_from_item(widest_completion_ix)
571 .with_sizing_behavior(ListSizingBehavior::Infer);
572
573 Popover::new().child(list).into_any_element()
574 }
575
576 fn render_aside(
577 &mut self,
578 editor: &Editor,
579 max_size: Size<Pixels>,
580 window: &mut Window,
581 cx: &mut Context<Editor>,
582 ) -> Option<AnyElement> {
583 if !self.show_completion_documentation {
584 return None;
585 }
586
587 let mat = &self.entries.borrow()[self.selected_item];
588 let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
589 .documentation
590 .as_ref()?
591 {
592 CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
593 CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
594 let markdown = self.markdown_element.get_or_insert_with(|| {
595 cx.new(|cx| {
596 let languages = editor
597 .workspace
598 .as_ref()
599 .and_then(|(workspace, _)| workspace.upgrade())
600 .map(|workspace| workspace.read(cx).app_state().languages.clone());
601 let language = editor
602 .language_at(self.initial_position, cx)
603 .map(|l| l.name().to_proto());
604 Markdown::new(
605 SharedString::default(),
606 hover_markdown_style(window, cx),
607 languages,
608 language,
609 cx,
610 )
611 .copy_code_block_buttons(false)
612 .open_url(open_markdown_url)
613 })
614 });
615 markdown.update(cx, |markdown, cx| {
616 markdown.reset(parsed.clone(), cx);
617 });
618 div().child(markdown.clone())
619 }
620 CompletionDocumentation::MultiLineMarkdown(_) => return None,
621 CompletionDocumentation::SingleLine(_) => return None,
622 CompletionDocumentation::Undocumented => return None,
623 };
624
625 Some(
626 Popover::new()
627 .child(
628 multiline_docs
629 .id("multiline_docs")
630 .px(MENU_ASIDE_X_PADDING / 2.)
631 .max_w(max_size.width)
632 .max_h(max_size.height)
633 .overflow_y_scroll()
634 .occlude(),
635 )
636 .into_any_element(),
637 )
638 }
639
640 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
641 let mut matches = if let Some(query) = query {
642 fuzzy::match_strings(
643 &self.match_candidates,
644 query,
645 query.chars().any(|c| c.is_uppercase()),
646 100,
647 &Default::default(),
648 executor,
649 )
650 .await
651 } else {
652 self.match_candidates
653 .iter()
654 .enumerate()
655 .map(|(candidate_id, candidate)| StringMatch {
656 candidate_id,
657 score: Default::default(),
658 positions: Default::default(),
659 string: candidate.string.clone(),
660 })
661 .collect()
662 };
663
664 // Remove all candidates where the query's start does not match the start of any word in the candidate
665 if let Some(query) = query {
666 if let Some(query_start) = query.chars().next() {
667 matches.retain(|string_match| {
668 split_words(&string_match.string).any(|word| {
669 // Check that the first codepoint of the word as lowercase matches the first
670 // codepoint of the query as lowercase
671 word.chars()
672 .flat_map(|codepoint| codepoint.to_lowercase())
673 .zip(query_start.to_lowercase())
674 .all(|(word_cp, query_cp)| word_cp == query_cp)
675 })
676 });
677 }
678 }
679
680 let completions = self.completions.borrow_mut();
681 if self.sort_completions {
682 matches.sort_unstable_by_key(|mat| {
683 // We do want to strike a balance here between what the language server tells us
684 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
685 // `Creat` and there is a local variable called `CreateComponent`).
686 // So what we do is: we bucket all matches into two buckets
687 // - Strong matches
688 // - Weak matches
689 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
690 // and the Weak matches are the rest.
691 //
692 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
693 // matches, we prefer language-server sort_text first.
694 //
695 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
696 // Rest of the matches(weak) can be sorted as language-server expects.
697
698 #[derive(PartialEq, Eq, PartialOrd, Ord)]
699 enum MatchScore<'a> {
700 Strong {
701 score: Reverse<OrderedFloat<f64>>,
702 sort_text: Option<&'a str>,
703 sort_key: (usize, &'a str),
704 },
705 Weak {
706 sort_text: Option<&'a str>,
707 score: Reverse<OrderedFloat<f64>>,
708 sort_key: (usize, &'a str),
709 },
710 }
711
712 let completion = &completions[mat.candidate_id];
713 let sort_key = completion.sort_key();
714 let sort_text =
715 if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
716 lsp_completion.sort_text.as_deref()
717 } else {
718 None
719 };
720 let score = Reverse(OrderedFloat(mat.score));
721
722 if mat.score >= 0.2 {
723 MatchScore::Strong {
724 score,
725 sort_text,
726 sort_key,
727 }
728 } else {
729 MatchScore::Weak {
730 sort_text,
731 score,
732 sort_key,
733 }
734 }
735 });
736 }
737 drop(completions);
738
739 *self.entries.borrow_mut() = matches;
740 self.selected_item = 0;
741 // This keeps the display consistent when y_flipped.
742 self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
743 }
744}
745
746#[derive(Clone)]
747pub struct AvailableCodeAction {
748 pub excerpt_id: ExcerptId,
749 pub action: CodeAction,
750 pub provider: Rc<dyn CodeActionProvider>,
751}
752
753#[derive(Clone)]
754pub struct CodeActionContents {
755 pub tasks: Option<Rc<ResolvedTasks>>,
756 pub actions: Option<Rc<[AvailableCodeAction]>>,
757}
758
759impl CodeActionContents {
760 fn len(&self) -> usize {
761 match (&self.tasks, &self.actions) {
762 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
763 (Some(tasks), None) => tasks.templates.len(),
764 (None, Some(actions)) => actions.len(),
765 (None, None) => 0,
766 }
767 }
768
769 fn is_empty(&self) -> bool {
770 match (&self.tasks, &self.actions) {
771 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
772 (Some(tasks), None) => tasks.templates.is_empty(),
773 (None, Some(actions)) => actions.is_empty(),
774 (None, None) => true,
775 }
776 }
777
778 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
779 self.tasks
780 .iter()
781 .flat_map(|tasks| {
782 tasks
783 .templates
784 .iter()
785 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
786 })
787 .chain(self.actions.iter().flat_map(|actions| {
788 actions.iter().map(|available| CodeActionsItem::CodeAction {
789 excerpt_id: available.excerpt_id,
790 action: available.action.clone(),
791 provider: available.provider.clone(),
792 })
793 }))
794 }
795
796 pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
797 match (&self.tasks, &self.actions) {
798 (Some(tasks), Some(actions)) => {
799 if index < tasks.templates.len() {
800 tasks
801 .templates
802 .get(index)
803 .cloned()
804 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
805 } else {
806 actions.get(index - tasks.templates.len()).map(|available| {
807 CodeActionsItem::CodeAction {
808 excerpt_id: available.excerpt_id,
809 action: available.action.clone(),
810 provider: available.provider.clone(),
811 }
812 })
813 }
814 }
815 (Some(tasks), None) => tasks
816 .templates
817 .get(index)
818 .cloned()
819 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
820 (None, Some(actions)) => {
821 actions
822 .get(index)
823 .map(|available| CodeActionsItem::CodeAction {
824 excerpt_id: available.excerpt_id,
825 action: available.action.clone(),
826 provider: available.provider.clone(),
827 })
828 }
829 (None, None) => None,
830 }
831 }
832}
833
834#[allow(clippy::large_enum_variant)]
835#[derive(Clone)]
836pub enum CodeActionsItem {
837 Task(TaskSourceKind, ResolvedTask),
838 CodeAction {
839 excerpt_id: ExcerptId,
840 action: CodeAction,
841 provider: Rc<dyn CodeActionProvider>,
842 },
843}
844
845impl CodeActionsItem {
846 fn as_task(&self) -> Option<&ResolvedTask> {
847 let Self::Task(_, task) = self else {
848 return None;
849 };
850 Some(task)
851 }
852
853 fn as_code_action(&self) -> Option<&CodeAction> {
854 let Self::CodeAction { action, .. } = self else {
855 return None;
856 };
857 Some(action)
858 }
859
860 pub fn label(&self) -> String {
861 match self {
862 Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
863 Self::Task(_, task) => task.resolved_label.clone(),
864 }
865 }
866}
867
868pub struct CodeActionsMenu {
869 pub actions: CodeActionContents,
870 pub buffer: Entity<Buffer>,
871 pub selected_item: usize,
872 pub scroll_handle: UniformListScrollHandle,
873 pub deployed_from_indicator: Option<DisplayRow>,
874}
875
876impl CodeActionsMenu {
877 fn select_first(&mut self, cx: &mut Context<Editor>) {
878 self.selected_item = if self.scroll_handle.y_flipped() {
879 self.actions.len() - 1
880 } else {
881 0
882 };
883 self.scroll_handle
884 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
885 cx.notify()
886 }
887
888 fn select_last(&mut self, cx: &mut Context<Editor>) {
889 self.selected_item = if self.scroll_handle.y_flipped() {
890 0
891 } else {
892 self.actions.len() - 1
893 };
894 self.scroll_handle
895 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
896 cx.notify()
897 }
898
899 fn select_prev(&mut self, cx: &mut Context<Editor>) {
900 self.selected_item = if self.scroll_handle.y_flipped() {
901 self.next_match_index()
902 } else {
903 self.prev_match_index()
904 };
905 self.scroll_handle
906 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
907 cx.notify();
908 }
909
910 fn select_next(&mut self, cx: &mut Context<Editor>) {
911 self.selected_item = if self.scroll_handle.y_flipped() {
912 self.prev_match_index()
913 } else {
914 self.next_match_index()
915 };
916 self.scroll_handle
917 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
918 cx.notify();
919 }
920
921 fn prev_match_index(&self) -> usize {
922 if self.selected_item > 0 {
923 self.selected_item - 1
924 } else {
925 self.actions.len() - 1
926 }
927 }
928
929 fn next_match_index(&self) -> usize {
930 if self.selected_item + 1 < self.actions.len() {
931 self.selected_item + 1
932 } else {
933 0
934 }
935 }
936
937 fn visible(&self) -> bool {
938 !self.actions.is_empty()
939 }
940
941 fn origin(&self) -> ContextMenuOrigin {
942 if let Some(row) = self.deployed_from_indicator {
943 ContextMenuOrigin::GutterIndicator(row)
944 } else {
945 ContextMenuOrigin::Cursor
946 }
947 }
948
949 fn render(
950 &self,
951 _style: &EditorStyle,
952 max_height_in_lines: u32,
953 y_flipped: bool,
954 window: &mut Window,
955 cx: &mut Context<Editor>,
956 ) -> AnyElement {
957 let actions = self.actions.clone();
958 let selected_item = self.selected_item;
959 let list = uniform_list(
960 cx.entity().clone(),
961 "code_actions_menu",
962 self.actions.len(),
963 move |_this, range, _, cx| {
964 actions
965 .iter()
966 .skip(range.start)
967 .take(range.end - range.start)
968 .enumerate()
969 .map(|(ix, action)| {
970 let item_ix = range.start + ix;
971 let selected = item_ix == selected_item;
972 let colors = cx.theme().colors();
973 div().min_w(px(220.)).max_w(px(540.)).child(
974 ListItem::new(item_ix)
975 .inset(true)
976 .toggle_state(selected)
977 .when_some(action.as_code_action(), |this, action| {
978 this.on_click(cx.listener(move |editor, _, window, cx| {
979 cx.stop_propagation();
980 if let Some(task) = editor.confirm_code_action(
981 &ConfirmCodeAction {
982 item_ix: Some(item_ix),
983 },
984 window,
985 cx,
986 ) {
987 task.detach_and_log_err(cx)
988 }
989 }))
990 .child(
991 h_flex()
992 .overflow_hidden()
993 .child(
994 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
995 action.lsp_action.title().replace("\n", ""),
996 )
997 .when(selected, |this| {
998 this.text_color(colors.text_accent)
999 }),
1000 )
1001 })
1002 .when_some(action.as_task(), |this, task| {
1003 this.on_click(cx.listener(move |editor, _, window, cx| {
1004 cx.stop_propagation();
1005 if let Some(task) = editor.confirm_code_action(
1006 &ConfirmCodeAction {
1007 item_ix: Some(item_ix),
1008 },
1009 window,
1010 cx,
1011 ) {
1012 task.detach_and_log_err(cx)
1013 }
1014 }))
1015 .child(
1016 h_flex()
1017 .overflow_hidden()
1018 .child(task.resolved_label.replace("\n", ""))
1019 .when(selected, |this| {
1020 this.text_color(colors.text_accent)
1021 }),
1022 )
1023 }),
1024 )
1025 })
1026 .collect()
1027 },
1028 )
1029 .occlude()
1030 .max_h(max_height_in_lines as f32 * window.line_height())
1031 .track_scroll(self.scroll_handle.clone())
1032 .y_flipped(y_flipped)
1033 .with_width_from_item(
1034 self.actions
1035 .iter()
1036 .enumerate()
1037 .max_by_key(|(_, action)| match action {
1038 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1039 CodeActionsItem::CodeAction { action, .. } => {
1040 action.lsp_action.title().chars().count()
1041 }
1042 })
1043 .map(|(ix, _)| ix),
1044 )
1045 .with_sizing_behavior(ListSizingBehavior::Infer);
1046
1047 Popover::new().child(list).into_any_element()
1048 }
1049}