code_context_menus.rs

   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        let mut additional_matches = Vec::new();
 669        // Deprioritize all candidates where the query's start does not match the start of any word in the candidate
 670        if let Some(query) = query {
 671            if let Some(query_start) = query.chars().next() {
 672                let (primary, secondary) = matches.into_iter().partition(|string_match| {
 673                    split_words(&string_match.string).any(|word| {
 674                        // Check that the first codepoint of the word as lowercase matches the first
 675                        // codepoint of the query as lowercase
 676                        word.chars()
 677                            .flat_map(|codepoint| codepoint.to_lowercase())
 678                            .zip(query_start.to_lowercase())
 679                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 680                    })
 681                });
 682                matches = primary;
 683                additional_matches = secondary;
 684            }
 685        }
 686
 687        let completions = self.completions.borrow_mut();
 688        if self.sort_completions {
 689            matches.sort_unstable_by_key(|mat| {
 690                // We do want to strike a balance here between what the language server tells us
 691                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 692                // `Creat` and there is a local variable called `CreateComponent`).
 693                // So what we do is: we bucket all matches into two buckets
 694                // - Strong matches
 695                // - Weak matches
 696                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 697                // and the Weak matches are the rest.
 698                //
 699                // For the strong matches, we sort by our fuzzy-finder score first and for the weak
 700                // matches, we prefer language-server sort_text first.
 701                //
 702                // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
 703                // Rest of the matches(weak) can be sorted as language-server expects.
 704
 705                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 706                enum MatchScore<'a> {
 707                    Strong {
 708                        score: Reverse<OrderedFloat<f64>>,
 709                        sort_text: Option<&'a str>,
 710                        sort_key: (usize, &'a str),
 711                    },
 712                    Weak {
 713                        sort_text: Option<&'a str>,
 714                        score: Reverse<OrderedFloat<f64>>,
 715                        sort_key: (usize, &'a str),
 716                    },
 717                }
 718
 719                let completion = &completions[mat.candidate_id];
 720                let sort_key = completion.sort_key();
 721                let sort_text =
 722                    if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
 723                        lsp_completion.sort_text.as_deref()
 724                    } else {
 725                        None
 726                    };
 727                let score = Reverse(OrderedFloat(mat.score));
 728
 729                if mat.score >= 0.2 {
 730                    MatchScore::Strong {
 731                        score,
 732                        sort_text,
 733                        sort_key,
 734                    }
 735                } else {
 736                    MatchScore::Weak {
 737                        sort_text,
 738                        score,
 739                        sort_key,
 740                    }
 741                }
 742            });
 743        }
 744        drop(completions);
 745
 746        matches.extend(additional_matches);
 747
 748        *self.entries.borrow_mut() = matches;
 749        self.selected_item = 0;
 750        // This keeps the display consistent when y_flipped.
 751        self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
 752    }
 753}
 754
 755#[derive(Clone)]
 756pub struct AvailableCodeAction {
 757    pub excerpt_id: ExcerptId,
 758    pub action: CodeAction,
 759    pub provider: Rc<dyn CodeActionProvider>,
 760}
 761
 762#[derive(Clone)]
 763pub struct CodeActionContents {
 764    pub tasks: Option<Rc<ResolvedTasks>>,
 765    pub actions: Option<Rc<[AvailableCodeAction]>>,
 766}
 767
 768impl CodeActionContents {
 769    fn len(&self) -> usize {
 770        match (&self.tasks, &self.actions) {
 771            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 772            (Some(tasks), None) => tasks.templates.len(),
 773            (None, Some(actions)) => actions.len(),
 774            (None, None) => 0,
 775        }
 776    }
 777
 778    fn is_empty(&self) -> bool {
 779        match (&self.tasks, &self.actions) {
 780            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 781            (Some(tasks), None) => tasks.templates.is_empty(),
 782            (None, Some(actions)) => actions.is_empty(),
 783            (None, None) => true,
 784        }
 785    }
 786
 787    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 788        self.tasks
 789            .iter()
 790            .flat_map(|tasks| {
 791                tasks
 792                    .templates
 793                    .iter()
 794                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 795            })
 796            .chain(self.actions.iter().flat_map(|actions| {
 797                actions.iter().map(|available| CodeActionsItem::CodeAction {
 798                    excerpt_id: available.excerpt_id,
 799                    action: available.action.clone(),
 800                    provider: available.provider.clone(),
 801                })
 802            }))
 803    }
 804
 805    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
 806        match (&self.tasks, &self.actions) {
 807            (Some(tasks), Some(actions)) => {
 808                if index < tasks.templates.len() {
 809                    tasks
 810                        .templates
 811                        .get(index)
 812                        .cloned()
 813                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 814                } else {
 815                    actions.get(index - tasks.templates.len()).map(|available| {
 816                        CodeActionsItem::CodeAction {
 817                            excerpt_id: available.excerpt_id,
 818                            action: available.action.clone(),
 819                            provider: available.provider.clone(),
 820                        }
 821                    })
 822                }
 823            }
 824            (Some(tasks), None) => tasks
 825                .templates
 826                .get(index)
 827                .cloned()
 828                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 829            (None, Some(actions)) => {
 830                actions
 831                    .get(index)
 832                    .map(|available| CodeActionsItem::CodeAction {
 833                        excerpt_id: available.excerpt_id,
 834                        action: available.action.clone(),
 835                        provider: available.provider.clone(),
 836                    })
 837            }
 838            (None, None) => None,
 839        }
 840    }
 841}
 842
 843#[allow(clippy::large_enum_variant)]
 844#[derive(Clone)]
 845pub enum CodeActionsItem {
 846    Task(TaskSourceKind, ResolvedTask),
 847    CodeAction {
 848        excerpt_id: ExcerptId,
 849        action: CodeAction,
 850        provider: Rc<dyn CodeActionProvider>,
 851    },
 852}
 853
 854impl CodeActionsItem {
 855    fn as_task(&self) -> Option<&ResolvedTask> {
 856        let Self::Task(_, task) = self else {
 857            return None;
 858        };
 859        Some(task)
 860    }
 861
 862    fn as_code_action(&self) -> Option<&CodeAction> {
 863        let Self::CodeAction { action, .. } = self else {
 864            return None;
 865        };
 866        Some(action)
 867    }
 868
 869    pub fn label(&self) -> String {
 870        match self {
 871            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
 872            Self::Task(_, task) => task.resolved_label.clone(),
 873        }
 874    }
 875}
 876
 877pub struct CodeActionsMenu {
 878    pub actions: CodeActionContents,
 879    pub buffer: Entity<Buffer>,
 880    pub selected_item: usize,
 881    pub scroll_handle: UniformListScrollHandle,
 882    pub deployed_from_indicator: Option<DisplayRow>,
 883}
 884
 885impl CodeActionsMenu {
 886    fn select_first(&mut self, cx: &mut Context<Editor>) {
 887        self.selected_item = if self.scroll_handle.y_flipped() {
 888            self.actions.len() - 1
 889        } else {
 890            0
 891        };
 892        self.scroll_handle
 893            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 894        cx.notify()
 895    }
 896
 897    fn select_last(&mut self, cx: &mut Context<Editor>) {
 898        self.selected_item = if self.scroll_handle.y_flipped() {
 899            0
 900        } else {
 901            self.actions.len() - 1
 902        };
 903        self.scroll_handle
 904            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 905        cx.notify()
 906    }
 907
 908    fn select_prev(&mut self, cx: &mut Context<Editor>) {
 909        self.selected_item = if self.scroll_handle.y_flipped() {
 910            self.next_match_index()
 911        } else {
 912            self.prev_match_index()
 913        };
 914        self.scroll_handle
 915            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 916        cx.notify();
 917    }
 918
 919    fn select_next(&mut self, cx: &mut Context<Editor>) {
 920        self.selected_item = if self.scroll_handle.y_flipped() {
 921            self.prev_match_index()
 922        } else {
 923            self.next_match_index()
 924        };
 925        self.scroll_handle
 926            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 927        cx.notify();
 928    }
 929
 930    fn prev_match_index(&self) -> usize {
 931        if self.selected_item > 0 {
 932            self.selected_item - 1
 933        } else {
 934            self.actions.len() - 1
 935        }
 936    }
 937
 938    fn next_match_index(&self) -> usize {
 939        if self.selected_item + 1 < self.actions.len() {
 940            self.selected_item + 1
 941        } else {
 942            0
 943        }
 944    }
 945
 946    fn visible(&self) -> bool {
 947        !self.actions.is_empty()
 948    }
 949
 950    fn origin(&self) -> ContextMenuOrigin {
 951        if let Some(row) = self.deployed_from_indicator {
 952            ContextMenuOrigin::GutterIndicator(row)
 953        } else {
 954            ContextMenuOrigin::Cursor
 955        }
 956    }
 957
 958    fn render(
 959        &self,
 960        _style: &EditorStyle,
 961        max_height_in_lines: u32,
 962        y_flipped: bool,
 963        window: &mut Window,
 964        cx: &mut Context<Editor>,
 965    ) -> AnyElement {
 966        let actions = self.actions.clone();
 967        let selected_item = self.selected_item;
 968        let list = uniform_list(
 969            cx.entity().clone(),
 970            "code_actions_menu",
 971            self.actions.len(),
 972            move |_this, range, _, cx| {
 973                actions
 974                    .iter()
 975                    .skip(range.start)
 976                    .take(range.end - range.start)
 977                    .enumerate()
 978                    .map(|(ix, action)| {
 979                        let item_ix = range.start + ix;
 980                        let selected = item_ix == selected_item;
 981                        let colors = cx.theme().colors();
 982                        div().min_w(px(220.)).max_w(px(540.)).child(
 983                            ListItem::new(item_ix)
 984                                .inset(true)
 985                                .toggle_state(selected)
 986                                .when_some(action.as_code_action(), |this, action| {
 987                                    this.on_click(cx.listener(move |editor, _, window, cx| {
 988                                        cx.stop_propagation();
 989                                        if let Some(task) = editor.confirm_code_action(
 990                                            &ConfirmCodeAction {
 991                                                item_ix: Some(item_ix),
 992                                            },
 993                                            window,
 994                                            cx,
 995                                        ) {
 996                                            task.detach_and_log_err(cx)
 997                                        }
 998                                    }))
 999                                    .child(
1000                                        h_flex()
1001                                            .overflow_hidden()
1002                                            .child(
1003                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1004                                                action.lsp_action.title().replace("\n", ""),
1005                                            )
1006                                            .when(selected, |this| {
1007                                                this.text_color(colors.text_accent)
1008                                            }),
1009                                    )
1010                                })
1011                                .when_some(action.as_task(), |this, task| {
1012                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1013                                        cx.stop_propagation();
1014                                        if let Some(task) = editor.confirm_code_action(
1015                                            &ConfirmCodeAction {
1016                                                item_ix: Some(item_ix),
1017                                            },
1018                                            window,
1019                                            cx,
1020                                        ) {
1021                                            task.detach_and_log_err(cx)
1022                                        }
1023                                    }))
1024                                    .child(
1025                                        h_flex()
1026                                            .overflow_hidden()
1027                                            .child(task.resolved_label.replace("\n", ""))
1028                                            .when(selected, |this| {
1029                                                this.text_color(colors.text_accent)
1030                                            }),
1031                                    )
1032                                }),
1033                        )
1034                    })
1035                    .collect()
1036            },
1037        )
1038        .occlude()
1039        .max_h(max_height_in_lines as f32 * window.line_height())
1040        .track_scroll(self.scroll_handle.clone())
1041        .y_flipped(y_flipped)
1042        .with_width_from_item(
1043            self.actions
1044                .iter()
1045                .enumerate()
1046                .max_by_key(|(_, action)| match action {
1047                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1048                    CodeActionsItem::CodeAction { action, .. } => {
1049                        action.lsp_action.title().chars().count()
1050                    }
1051                })
1052                .map(|(ix, _)| ix),
1053        )
1054        .with_sizing_behavior(ListSizingBehavior::Infer);
1055
1056        Popover::new().child(list).into_any_element()
1057    }
1058}