code_context_menus.rs

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