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