code_context_menus.rs

  1use std::{cell::Cell, cmp::Reverse, ops::Range, sync::Arc};
  2
  3use fuzzy::{StringMatch, StringMatchCandidate};
  4use gpui::{
  5    div, px, uniform_list, AnyElement, BackgroundExecutor, Div, FontWeight, ListSizingBehavior,
  6    Model, MouseButton, Pixels, ScrollStrategy, SharedString, StrikethroughStyle, StyledText,
  7    UniformListScrollHandle, ViewContext, WeakView,
  8};
  9use language::Buffer;
 10use language::{CodeLabel, Documentation};
 11use lsp::LanguageServerId;
 12use multi_buffer::{Anchor, ExcerptId};
 13use ordered_float::OrderedFloat;
 14use parking_lot::RwLock;
 15use project::{CodeAction, Completion, TaskSourceKind};
 16use task::ResolvedTask;
 17use ui::{
 18    h_flex, ActiveTheme as _, Color, FluentBuilder as _, InteractiveElement as _, IntoElement,
 19    Label, LabelCommon as _, LabelSize, ListItem, ParentElement as _, Popover,
 20    StatefulInteractiveElement as _, Styled, StyledExt as _, Toggleable as _,
 21};
 22use util::ResultExt as _;
 23use workspace::Workspace;
 24
 25use crate::{
 26    actions::{ConfirmCodeAction, ConfirmCompletion},
 27    display_map::DisplayPoint,
 28    render_parsed_markdown, split_words, styled_runs_for_code_label, CodeActionProvider,
 29    CompletionId, CompletionProvider, DisplayRow, Editor, EditorStyle, ResolvedTasks,
 30};
 31
 32pub enum CodeContextMenu {
 33    Completions(CompletionsMenu),
 34    CodeActions(CodeActionsMenu),
 35}
 36
 37impl CodeContextMenu {
 38    pub fn select_first(
 39        &mut self,
 40        provider: Option<&dyn CompletionProvider>,
 41        cx: &mut ViewContext<Editor>,
 42    ) -> bool {
 43        if self.visible() {
 44            match self {
 45                CodeContextMenu::Completions(menu) => menu.select_first(provider, cx),
 46                CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
 47            }
 48            true
 49        } else {
 50            false
 51        }
 52    }
 53
 54    pub fn select_prev(
 55        &mut self,
 56        provider: Option<&dyn CompletionProvider>,
 57        cx: &mut ViewContext<Editor>,
 58    ) -> bool {
 59        if self.visible() {
 60            match self {
 61                CodeContextMenu::Completions(menu) => menu.select_prev(provider, cx),
 62                CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
 63            }
 64            true
 65        } else {
 66            false
 67        }
 68    }
 69
 70    pub fn select_next(
 71        &mut self,
 72        provider: Option<&dyn CompletionProvider>,
 73        cx: &mut ViewContext<Editor>,
 74    ) -> bool {
 75        if self.visible() {
 76            match self {
 77                CodeContextMenu::Completions(menu) => menu.select_next(provider, cx),
 78                CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
 79            }
 80            true
 81        } else {
 82            false
 83        }
 84    }
 85
 86    pub fn select_last(
 87        &mut self,
 88        provider: Option<&dyn CompletionProvider>,
 89        cx: &mut ViewContext<Editor>,
 90    ) -> bool {
 91        if self.visible() {
 92            match self {
 93                CodeContextMenu::Completions(menu) => menu.select_last(provider, cx),
 94                CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
 95            }
 96            true
 97        } else {
 98            false
 99        }
100    }
101
102    pub fn visible(&self) -> bool {
103        match self {
104            CodeContextMenu::Completions(menu) => menu.visible(),
105            CodeContextMenu::CodeActions(menu) => menu.visible(),
106        }
107    }
108
109    pub fn render(
110        &self,
111        cursor_position: DisplayPoint,
112        style: &EditorStyle,
113        max_height: Pixels,
114        workspace: Option<WeakView<Workspace>>,
115        cx: &mut ViewContext<Editor>,
116    ) -> (ContextMenuOrigin, AnyElement) {
117        match self {
118            CodeContextMenu::Completions(menu) => (
119                ContextMenuOrigin::EditorPoint(cursor_position),
120                menu.render(style, max_height, workspace, cx),
121            ),
122            CodeContextMenu::CodeActions(menu) => {
123                menu.render(cursor_position, style, max_height, cx)
124            }
125        }
126    }
127}
128
129pub enum ContextMenuOrigin {
130    EditorPoint(DisplayPoint),
131    GutterIndicator(DisplayRow),
132}
133
134#[derive(Clone, Debug)]
135pub struct CompletionsMenu {
136    pub id: CompletionId,
137    sort_completions: bool,
138    pub initial_position: Anchor,
139    pub buffer: Model<Buffer>,
140    pub completions: Arc<RwLock<Box<[Completion]>>>,
141    match_candidates: Arc<[StringMatchCandidate]>,
142    pub matches: Arc<[StringMatch]>,
143    pub selected_item: usize,
144    scroll_handle: UniformListScrollHandle,
145    resolve_completions: bool,
146    pub aside_was_displayed: Cell<bool>,
147    show_completion_documentation: bool,
148}
149
150impl CompletionsMenu {
151    pub fn new(
152        id: CompletionId,
153        sort_completions: bool,
154        show_completion_documentation: bool,
155        initial_position: Anchor,
156        buffer: Model<Buffer>,
157        completions: Box<[Completion]>,
158        aside_was_displayed: bool,
159    ) -> Self {
160        let match_candidates = completions
161            .iter()
162            .enumerate()
163            .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
164            .collect();
165
166        Self {
167            id,
168            sort_completions,
169            initial_position,
170            buffer,
171            show_completion_documentation,
172            completions: Arc::new(RwLock::new(completions)),
173            match_candidates,
174            matches: Vec::new().into(),
175            selected_item: 0,
176            scroll_handle: UniformListScrollHandle::new(),
177            resolve_completions: true,
178            aside_was_displayed: Cell::new(aside_was_displayed),
179        }
180    }
181
182    pub fn new_snippet_choices(
183        id: CompletionId,
184        sort_completions: bool,
185        choices: &Vec<String>,
186        selection: Range<Anchor>,
187        buffer: Model<Buffer>,
188    ) -> Self {
189        let completions = choices
190            .iter()
191            .map(|choice| Completion {
192                old_range: selection.start.text_anchor..selection.end.text_anchor,
193                new_text: choice.to_string(),
194                label: CodeLabel {
195                    text: choice.to_string(),
196                    runs: Default::default(),
197                    filter_range: Default::default(),
198                },
199                server_id: LanguageServerId(usize::MAX),
200                documentation: None,
201                lsp_completion: Default::default(),
202                confirm: None,
203            })
204            .collect();
205
206        let match_candidates = choices
207            .iter()
208            .enumerate()
209            .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
210            .collect();
211        let matches = choices
212            .iter()
213            .enumerate()
214            .map(|(id, completion)| StringMatch {
215                candidate_id: id,
216                score: 1.,
217                positions: vec![],
218                string: completion.clone(),
219            })
220            .collect();
221        Self {
222            id,
223            sort_completions,
224            initial_position: selection.start,
225            buffer,
226            completions: Arc::new(RwLock::new(completions)),
227            match_candidates,
228            matches,
229            selected_item: 0,
230            scroll_handle: UniformListScrollHandle::new(),
231            resolve_completions: false,
232            aside_was_displayed: Cell::new(false),
233            show_completion_documentation: false,
234        }
235    }
236
237    fn select_first(
238        &mut self,
239        provider: Option<&dyn CompletionProvider>,
240        cx: &mut ViewContext<Editor>,
241    ) {
242        self.selected_item = 0;
243        self.scroll_handle
244            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
245        self.resolve_selected_completion(provider, cx);
246        cx.notify();
247    }
248
249    fn select_prev(
250        &mut self,
251        provider: Option<&dyn CompletionProvider>,
252        cx: &mut ViewContext<Editor>,
253    ) {
254        if self.selected_item > 0 {
255            self.selected_item -= 1;
256        } else {
257            self.selected_item = self.matches.len() - 1;
258        }
259        self.scroll_handle
260            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
261        self.resolve_selected_completion(provider, cx);
262        cx.notify();
263    }
264
265    fn select_next(
266        &mut self,
267        provider: Option<&dyn CompletionProvider>,
268        cx: &mut ViewContext<Editor>,
269    ) {
270        if self.selected_item + 1 < self.matches.len() {
271            self.selected_item += 1;
272        } else {
273            self.selected_item = 0;
274        }
275        self.scroll_handle
276            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
277        self.resolve_selected_completion(provider, cx);
278        cx.notify();
279    }
280
281    fn select_last(
282        &mut self,
283        provider: Option<&dyn CompletionProvider>,
284        cx: &mut ViewContext<Editor>,
285    ) {
286        self.selected_item = self.matches.len() - 1;
287        self.scroll_handle
288            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
289        self.resolve_selected_completion(provider, cx);
290        cx.notify();
291    }
292
293    pub fn resolve_selected_completion(
294        &mut self,
295        provider: Option<&dyn CompletionProvider>,
296        cx: &mut ViewContext<Editor>,
297    ) {
298        if !self.resolve_completions {
299            return;
300        }
301        let Some(provider) = provider else {
302            return;
303        };
304
305        let completion_index = self.matches[self.selected_item].candidate_id;
306        let resolve_task = provider.resolve_completions(
307            self.buffer.clone(),
308            vec![completion_index],
309            self.completions.clone(),
310            cx,
311        );
312
313        cx.spawn(move |editor, mut cx| async move {
314            if let Some(true) = resolve_task.await.log_err() {
315                editor.update(&mut cx, |_, cx| cx.notify()).ok();
316            }
317        })
318        .detach();
319    }
320
321    fn visible(&self) -> bool {
322        !self.matches.is_empty()
323    }
324
325    fn render(
326        &self,
327        style: &EditorStyle,
328        max_height: Pixels,
329        workspace: Option<WeakView<Workspace>>,
330        cx: &mut ViewContext<Editor>,
331    ) -> AnyElement {
332        let show_completion_documentation = self.show_completion_documentation;
333        let widest_completion_ix = self
334            .matches
335            .iter()
336            .enumerate()
337            .max_by_key(|(_, mat)| {
338                let completions = self.completions.read();
339                let completion = &completions[mat.candidate_id];
340                let documentation = &completion.documentation;
341
342                let mut len = completion.label.text.chars().count();
343                if let Some(Documentation::SingleLine(text)) = documentation {
344                    if show_completion_documentation {
345                        len += text.chars().count();
346                    }
347                }
348
349                len
350            })
351            .map(|(ix, _)| ix);
352
353        let completions = self.completions.clone();
354        let matches = self.matches.clone();
355        let selected_item = self.selected_item;
356        let style = style.clone();
357
358        let multiline_docs = if show_completion_documentation {
359            let mat = &self.matches[selected_item];
360            match &self.completions.read()[mat.candidate_id].documentation {
361                Some(Documentation::MultiLinePlainText(text)) => {
362                    Some(div().child(SharedString::from(text.clone())))
363                }
364                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
365                    Some(div().child(render_parsed_markdown(
366                        "completions_markdown",
367                        parsed,
368                        &style,
369                        workspace,
370                        cx,
371                    )))
372                }
373                Some(Documentation::Undocumented) if self.aside_was_displayed.get() => {
374                    Some(div().child("No documentation"))
375                }
376                _ => None,
377            }
378        } else {
379            None
380        };
381
382        let aside_contents = if let Some(multiline_docs) = multiline_docs {
383            Some(multiline_docs)
384        } else if self.aside_was_displayed.get() {
385            Some(div().child("Fetching documentation..."))
386        } else {
387            None
388        };
389        self.aside_was_displayed.set(aside_contents.is_some());
390
391        let aside_contents = aside_contents.map(|div| {
392            div.id("multiline_docs")
393                .max_h(max_height)
394                .flex_1()
395                .px_1p5()
396                .py_1()
397                .min_w(px(260.))
398                .max_w(px(640.))
399                .w(px(500.))
400                .overflow_y_scroll()
401                .occlude()
402        });
403
404        let list = uniform_list(
405            cx.view().clone(),
406            "completions",
407            matches.len(),
408            move |_editor, range, cx| {
409                let start_ix = range.start;
410                let completions_guard = completions.read();
411
412                matches[range]
413                    .iter()
414                    .enumerate()
415                    .map(|(ix, mat)| {
416                        let item_ix = start_ix + ix;
417                        let candidate_id = mat.candidate_id;
418                        let completion = &completions_guard[candidate_id];
419
420                        let documentation = if show_completion_documentation {
421                            &completion.documentation
422                        } else {
423                            &None
424                        };
425
426                        let filter_start = completion.label.filter_range.start;
427                        let highlights = gpui::combine_highlights(
428                            mat.ranges().map(|range| {
429                                (
430                                    filter_start + range.start..filter_start + range.end,
431                                    FontWeight::BOLD.into(),
432                                )
433                            }),
434                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
435                                |(range, mut highlight)| {
436                                    // Ignore font weight for syntax highlighting, as we'll use it
437                                    // for fuzzy matches.
438                                    highlight.font_weight = None;
439
440                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
441                                        highlight.strikethrough = Some(StrikethroughStyle {
442                                            thickness: 1.0.into(),
443                                            ..Default::default()
444                                        });
445                                        highlight.color = Some(cx.theme().colors().text_muted);
446                                    }
447
448                                    (range, highlight)
449                                },
450                            ),
451                        );
452                        let completion_label = StyledText::new(completion.label.text.clone())
453                            .with_highlights(&style.text, highlights);
454                        let documentation_label =
455                            if let Some(Documentation::SingleLine(text)) = documentation {
456                                if text.trim().is_empty() {
457                                    None
458                                } else {
459                                    Some(
460                                        Label::new(text.clone())
461                                            .ml_4()
462                                            .size(LabelSize::Small)
463                                            .color(Color::Muted),
464                                    )
465                                }
466                            } else {
467                                None
468                            };
469
470                        let color_swatch = completion
471                            .color()
472                            .map(|color| div().size_4().bg(color).rounded_sm());
473
474                        div().min_w(px(220.)).max_w(px(540.)).child(
475                            ListItem::new(mat.candidate_id)
476                                .inset(true)
477                                .toggle_state(item_ix == selected_item)
478                                .on_click(cx.listener(move |editor, _event, cx| {
479                                    cx.stop_propagation();
480                                    if let Some(task) = editor.confirm_completion(
481                                        &ConfirmCompletion {
482                                            item_ix: Some(item_ix),
483                                        },
484                                        cx,
485                                    ) {
486                                        task.detach_and_log_err(cx)
487                                    }
488                                }))
489                                .start_slot::<Div>(color_swatch)
490                                .child(h_flex().overflow_hidden().child(completion_label))
491                                .end_slot::<Label>(documentation_label),
492                        )
493                    })
494                    .collect()
495            },
496        )
497        .occlude()
498        .max_h(max_height)
499        .track_scroll(self.scroll_handle.clone())
500        .with_width_from_item(widest_completion_ix)
501        .with_sizing_behavior(ListSizingBehavior::Infer);
502
503        Popover::new()
504            .child(list)
505            .when_some(aside_contents, |popover, aside_contents| {
506                popover.aside(aside_contents)
507            })
508            .into_any_element()
509    }
510
511    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
512        let mut matches = if let Some(query) = query {
513            fuzzy::match_strings(
514                &self.match_candidates,
515                query,
516                query.chars().any(|c| c.is_uppercase()),
517                100,
518                &Default::default(),
519                executor,
520            )
521            .await
522        } else {
523            self.match_candidates
524                .iter()
525                .enumerate()
526                .map(|(candidate_id, candidate)| StringMatch {
527                    candidate_id,
528                    score: Default::default(),
529                    positions: Default::default(),
530                    string: candidate.string.clone(),
531                })
532                .collect()
533        };
534
535        // Remove all candidates where the query's start does not match the start of any word in the candidate
536        if let Some(query) = query {
537            if let Some(query_start) = query.chars().next() {
538                matches.retain(|string_match| {
539                    split_words(&string_match.string).any(|word| {
540                        // Check that the first codepoint of the word as lowercase matches the first
541                        // codepoint of the query as lowercase
542                        word.chars()
543                            .flat_map(|codepoint| codepoint.to_lowercase())
544                            .zip(query_start.to_lowercase())
545                            .all(|(word_cp, query_cp)| word_cp == query_cp)
546                    })
547                });
548            }
549        }
550
551        let completions = self.completions.read();
552        if self.sort_completions {
553            matches.sort_unstable_by_key(|mat| {
554                // We do want to strike a balance here between what the language server tells us
555                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
556                // `Creat` and there is a local variable called `CreateComponent`).
557                // So what we do is: we bucket all matches into two buckets
558                // - Strong matches
559                // - Weak matches
560                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
561                // and the Weak matches are the rest.
562                //
563                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
564                // matches, we prefer language-server sort_text first.
565                //
566                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
567                // Rest of the matches(weak) can be sorted as language-server expects.
568
569                #[derive(PartialEq, Eq, PartialOrd, Ord)]
570                enum MatchScore<'a> {
571                    Strong {
572                        score: Reverse<OrderedFloat<f64>>,
573                        sort_text: Option<&'a str>,
574                        sort_key: (usize, &'a str),
575                    },
576                    Weak {
577                        sort_text: Option<&'a str>,
578                        score: Reverse<OrderedFloat<f64>>,
579                        sort_key: (usize, &'a str),
580                    },
581                }
582
583                let completion = &completions[mat.candidate_id];
584                let sort_key = completion.sort_key();
585                let sort_text = completion.lsp_completion.sort_text.as_deref();
586                let score = Reverse(OrderedFloat(mat.score));
587
588                if mat.score >= 0.2 {
589                    MatchScore::Strong {
590                        score,
591                        sort_text,
592                        sort_key,
593                    }
594                } else {
595                    MatchScore::Weak {
596                        sort_text,
597                        score,
598                        sort_key,
599                    }
600                }
601            });
602        }
603        drop(completions);
604
605        self.matches = matches.into();
606        self.selected_item = 0;
607    }
608}
609
610#[derive(Clone)]
611pub struct AvailableCodeAction {
612    pub excerpt_id: ExcerptId,
613    pub action: CodeAction,
614    pub provider: Arc<dyn CodeActionProvider>,
615}
616
617#[derive(Clone)]
618pub struct CodeActionContents {
619    pub tasks: Option<Arc<ResolvedTasks>>,
620    pub actions: Option<Arc<[AvailableCodeAction]>>,
621}
622
623impl CodeActionContents {
624    fn len(&self) -> usize {
625        match (&self.tasks, &self.actions) {
626            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
627            (Some(tasks), None) => tasks.templates.len(),
628            (None, Some(actions)) => actions.len(),
629            (None, None) => 0,
630        }
631    }
632
633    fn is_empty(&self) -> bool {
634        match (&self.tasks, &self.actions) {
635            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
636            (Some(tasks), None) => tasks.templates.is_empty(),
637            (None, Some(actions)) => actions.is_empty(),
638            (None, None) => true,
639        }
640    }
641
642    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
643        self.tasks
644            .iter()
645            .flat_map(|tasks| {
646                tasks
647                    .templates
648                    .iter()
649                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
650            })
651            .chain(self.actions.iter().flat_map(|actions| {
652                actions.iter().map(|available| CodeActionsItem::CodeAction {
653                    excerpt_id: available.excerpt_id,
654                    action: available.action.clone(),
655                    provider: available.provider.clone(),
656                })
657            }))
658    }
659
660    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
661        match (&self.tasks, &self.actions) {
662            (Some(tasks), Some(actions)) => {
663                if index < tasks.templates.len() {
664                    tasks
665                        .templates
666                        .get(index)
667                        .cloned()
668                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
669                } else {
670                    actions.get(index - tasks.templates.len()).map(|available| {
671                        CodeActionsItem::CodeAction {
672                            excerpt_id: available.excerpt_id,
673                            action: available.action.clone(),
674                            provider: available.provider.clone(),
675                        }
676                    })
677                }
678            }
679            (Some(tasks), None) => tasks
680                .templates
681                .get(index)
682                .cloned()
683                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
684            (None, Some(actions)) => {
685                actions
686                    .get(index)
687                    .map(|available| CodeActionsItem::CodeAction {
688                        excerpt_id: available.excerpt_id,
689                        action: available.action.clone(),
690                        provider: available.provider.clone(),
691                    })
692            }
693            (None, None) => None,
694        }
695    }
696}
697
698#[allow(clippy::large_enum_variant)]
699#[derive(Clone)]
700pub enum CodeActionsItem {
701    Task(TaskSourceKind, ResolvedTask),
702    CodeAction {
703        excerpt_id: ExcerptId,
704        action: CodeAction,
705        provider: Arc<dyn CodeActionProvider>,
706    },
707}
708
709impl CodeActionsItem {
710    fn as_task(&self) -> Option<&ResolvedTask> {
711        let Self::Task(_, task) = self else {
712            return None;
713        };
714        Some(task)
715    }
716
717    fn as_code_action(&self) -> Option<&CodeAction> {
718        let Self::CodeAction { action, .. } = self else {
719            return None;
720        };
721        Some(action)
722    }
723
724    pub fn label(&self) -> String {
725        match self {
726            Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
727            Self::Task(_, task) => task.resolved_label.clone(),
728        }
729    }
730}
731
732pub struct CodeActionsMenu {
733    pub actions: CodeActionContents,
734    pub buffer: Model<Buffer>,
735    pub selected_item: usize,
736    pub scroll_handle: UniformListScrollHandle,
737    pub deployed_from_indicator: Option<DisplayRow>,
738}
739
740impl CodeActionsMenu {
741    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
742        self.selected_item = 0;
743        self.scroll_handle
744            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
745        cx.notify()
746    }
747
748    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
749        if self.selected_item > 0 {
750            self.selected_item -= 1;
751        } else {
752            self.selected_item = self.actions.len() - 1;
753        }
754        self.scroll_handle
755            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
756        cx.notify();
757    }
758
759    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
760        if self.selected_item + 1 < self.actions.len() {
761            self.selected_item += 1;
762        } else {
763            self.selected_item = 0;
764        }
765        self.scroll_handle
766            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
767        cx.notify();
768    }
769
770    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
771        self.selected_item = self.actions.len() - 1;
772        self.scroll_handle
773            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
774        cx.notify()
775    }
776
777    fn visible(&self) -> bool {
778        !self.actions.is_empty()
779    }
780
781    fn render(
782        &self,
783        cursor_position: DisplayPoint,
784        _style: &EditorStyle,
785        max_height: Pixels,
786        cx: &mut ViewContext<Editor>,
787    ) -> (ContextMenuOrigin, AnyElement) {
788        let actions = self.actions.clone();
789        let selected_item = self.selected_item;
790        let element = uniform_list(
791            cx.view().clone(),
792            "code_actions_menu",
793            self.actions.len(),
794            move |_this, range, cx| {
795                actions
796                    .iter()
797                    .skip(range.start)
798                    .take(range.end - range.start)
799                    .enumerate()
800                    .map(|(ix, action)| {
801                        let item_ix = range.start + ix;
802                        let selected = selected_item == item_ix;
803                        let colors = cx.theme().colors();
804                        div()
805                            .px_1()
806                            .rounded_md()
807                            .text_color(colors.text)
808                            .when(selected, |style| {
809                                style
810                                    .bg(colors.element_active)
811                                    .text_color(colors.text_accent)
812                            })
813                            .hover(|style| {
814                                style
815                                    .bg(colors.element_hover)
816                                    .text_color(colors.text_accent)
817                            })
818                            .whitespace_nowrap()
819                            .when_some(action.as_code_action(), |this, action| {
820                                this.on_mouse_down(
821                                    MouseButton::Left,
822                                    cx.listener(move |editor, _, cx| {
823                                        cx.stop_propagation();
824                                        if let Some(task) = editor.confirm_code_action(
825                                            &ConfirmCodeAction {
826                                                item_ix: Some(item_ix),
827                                            },
828                                            cx,
829                                        ) {
830                                            task.detach_and_log_err(cx)
831                                        }
832                                    }),
833                                )
834                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
835                                .child(SharedString::from(
836                                    action.lsp_action.title.replace("\n", ""),
837                                ))
838                            })
839                            .when_some(action.as_task(), |this, task| {
840                                this.on_mouse_down(
841                                    MouseButton::Left,
842                                    cx.listener(move |editor, _, cx| {
843                                        cx.stop_propagation();
844                                        if let Some(task) = editor.confirm_code_action(
845                                            &ConfirmCodeAction {
846                                                item_ix: Some(item_ix),
847                                            },
848                                            cx,
849                                        ) {
850                                            task.detach_and_log_err(cx)
851                                        }
852                                    }),
853                                )
854                                .child(SharedString::from(task.resolved_label.replace("\n", "")))
855                            })
856                    })
857                    .collect()
858            },
859        )
860        .elevation_1(cx)
861        .p_1()
862        .max_h(max_height)
863        .occlude()
864        .track_scroll(self.scroll_handle.clone())
865        .with_width_from_item(
866            self.actions
867                .iter()
868                .enumerate()
869                .max_by_key(|(_, action)| match action {
870                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
871                    CodeActionsItem::CodeAction { action, .. } => {
872                        action.lsp_action.title.chars().count()
873                    }
874                })
875                .map(|(ix, _)| ix),
876        )
877        .with_sizing_behavior(ListSizingBehavior::Infer)
878        .into_any_element();
879
880        let cursor_position = if let Some(row) = self.deployed_from_indicator {
881            ContextMenuOrigin::GutterIndicator(row)
882        } else {
883            ContextMenuOrigin::EditorPoint(cursor_position)
884        };
885
886        (cursor_position, element)
887    }
888}