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