code_context_menus.rs

   1use feature_flags::{DebuggerFeatureFlag, FeatureFlagAppExt as _};
   2use fuzzy::{StringMatch, StringMatchCandidate};
   3use gpui::{
   4    AnyElement, BackgroundExecutor, Entity, Focusable, FontWeight, ListSizingBehavior,
   5    ScrollStrategy, SharedString, Size, StrikethroughStyle, StyledText, UniformListScrollHandle,
   6    div, px, uniform_list,
   7};
   8use language::Buffer;
   9use language::CodeLabel;
  10use markdown::{Markdown, MarkdownElement};
  11use multi_buffer::{Anchor, ExcerptId};
  12use ordered_float::OrderedFloat;
  13use project::CompletionSource;
  14use project::lsp_store::CompletionDocumentation;
  15use project::{CodeAction, Completion, TaskSourceKind};
  16
  17use std::{
  18    cell::RefCell,
  19    cmp::{Reverse, min},
  20    iter,
  21    ops::Range,
  22    rc::Rc,
  23};
  24use task::ResolvedTask;
  25use ui::{Color, IntoElement, ListItem, Pixels, Popover, Styled, prelude::*};
  26use util::ResultExt;
  27
  28use crate::editor_settings::SnippetSortOrder;
  29use crate::hover_popover::{hover_markdown_style, open_markdown_url};
  30use crate::{
  31    CodeActionProvider, CompletionId, CompletionItemKind, CompletionProvider, DisplayRow, Editor,
  32    EditorStyle, ResolvedTasks,
  33    actions::{ConfirmCodeAction, ConfirmCompletion},
  34    split_words, styled_runs_for_code_label,
  35};
  36
  37pub const MENU_GAP: Pixels = px(4.);
  38pub const MENU_ASIDE_X_PADDING: Pixels = px(16.);
  39pub const MENU_ASIDE_MIN_WIDTH: Pixels = px(260.);
  40pub const MENU_ASIDE_MAX_WIDTH: Pixels = px(500.);
  41
  42pub enum CodeContextMenu {
  43    Completions(CompletionsMenu),
  44    CodeActions(CodeActionsMenu),
  45}
  46
  47impl CodeContextMenu {
  48    pub fn select_first(
  49        &mut self,
  50        provider: Option<&dyn CompletionProvider>,
  51        cx: &mut Context<Editor>,
  52    ) -> bool {
  53        if self.visible() {
  54            match self {
  55                CodeContextMenu::Completions(menu) => menu.select_first(provider, cx),
  56                CodeContextMenu::CodeActions(menu) => menu.select_first(cx),
  57            }
  58            true
  59        } else {
  60            false
  61        }
  62    }
  63
  64    pub fn select_prev(
  65        &mut self,
  66        provider: Option<&dyn CompletionProvider>,
  67        cx: &mut Context<Editor>,
  68    ) -> bool {
  69        if self.visible() {
  70            match self {
  71                CodeContextMenu::Completions(menu) => menu.select_prev(provider, cx),
  72                CodeContextMenu::CodeActions(menu) => menu.select_prev(cx),
  73            }
  74            true
  75        } else {
  76            false
  77        }
  78    }
  79
  80    pub fn select_next(
  81        &mut self,
  82        provider: Option<&dyn CompletionProvider>,
  83        cx: &mut Context<Editor>,
  84    ) -> bool {
  85        if self.visible() {
  86            match self {
  87                CodeContextMenu::Completions(menu) => menu.select_next(provider, cx),
  88                CodeContextMenu::CodeActions(menu) => menu.select_next(cx),
  89            }
  90            true
  91        } else {
  92            false
  93        }
  94    }
  95
  96    pub fn select_last(
  97        &mut self,
  98        provider: Option<&dyn CompletionProvider>,
  99        cx: &mut Context<Editor>,
 100    ) -> bool {
 101        if self.visible() {
 102            match self {
 103                CodeContextMenu::Completions(menu) => menu.select_last(provider, cx),
 104                CodeContextMenu::CodeActions(menu) => menu.select_last(cx),
 105            }
 106            true
 107        } else {
 108            false
 109        }
 110    }
 111
 112    pub fn visible(&self) -> bool {
 113        match self {
 114            CodeContextMenu::Completions(menu) => menu.visible(),
 115            CodeContextMenu::CodeActions(menu) => menu.visible(),
 116        }
 117    }
 118
 119    pub fn origin(&self) -> ContextMenuOrigin {
 120        match self {
 121            CodeContextMenu::Completions(menu) => menu.origin(),
 122            CodeContextMenu::CodeActions(menu) => menu.origin(),
 123        }
 124    }
 125
 126    pub fn render(
 127        &self,
 128        style: &EditorStyle,
 129        max_height_in_lines: u32,
 130        window: &mut Window,
 131        cx: &mut Context<Editor>,
 132    ) -> AnyElement {
 133        match self {
 134            CodeContextMenu::Completions(menu) => {
 135                menu.render(style, max_height_in_lines, window, cx)
 136            }
 137            CodeContextMenu::CodeActions(menu) => {
 138                menu.render(style, max_height_in_lines, window, cx)
 139            }
 140        }
 141    }
 142
 143    pub fn render_aside(
 144        &mut self,
 145        editor: &Editor,
 146        max_size: Size<Pixels>,
 147        window: &mut Window,
 148        cx: &mut Context<Editor>,
 149    ) -> Option<AnyElement> {
 150        match self {
 151            CodeContextMenu::Completions(menu) => menu.render_aside(editor, max_size, window, cx),
 152            CodeContextMenu::CodeActions(_) => None,
 153        }
 154    }
 155
 156    pub fn focused(&self, window: &mut Window, cx: &mut Context<Editor>) -> bool {
 157        match self {
 158            CodeContextMenu::Completions(completions_menu) => completions_menu
 159                .markdown_element
 160                .as_ref()
 161                .is_some_and(|markdown| markdown.focus_handle(cx).contains_focused(window, cx)),
 162            CodeContextMenu::CodeActions(_) => false,
 163        }
 164    }
 165}
 166
 167pub enum ContextMenuOrigin {
 168    Cursor,
 169    GutterIndicator(DisplayRow),
 170}
 171
 172#[derive(Clone, Debug)]
 173pub struct CompletionsMenu {
 174    pub id: CompletionId,
 175    sort_completions: bool,
 176    pub initial_position: Anchor,
 177    pub buffer: Entity<Buffer>,
 178    pub completions: Rc<RefCell<Box<[Completion]>>>,
 179    match_candidates: Rc<[StringMatchCandidate]>,
 180    pub entries: Rc<RefCell<Vec<StringMatch>>>,
 181    pub selected_item: usize,
 182    scroll_handle: UniformListScrollHandle,
 183    resolve_completions: bool,
 184    show_completion_documentation: bool,
 185    pub(super) ignore_completion_provider: bool,
 186    last_rendered_range: Rc<RefCell<Option<Range<usize>>>>,
 187    markdown_element: Option<Entity<Markdown>>,
 188    snippet_sort_order: SnippetSortOrder,
 189}
 190
 191impl CompletionsMenu {
 192    pub fn new(
 193        id: CompletionId,
 194        sort_completions: bool,
 195        show_completion_documentation: bool,
 196        ignore_completion_provider: bool,
 197        initial_position: Anchor,
 198        buffer: Entity<Buffer>,
 199        completions: Box<[Completion]>,
 200        snippet_sort_order: SnippetSortOrder,
 201    ) -> Self {
 202        let match_candidates = completions
 203            .iter()
 204            .enumerate()
 205            .map(|(id, completion)| StringMatchCandidate::new(id, &completion.label.filter_text()))
 206            .collect();
 207
 208        Self {
 209            id,
 210            sort_completions,
 211            initial_position,
 212            buffer,
 213            show_completion_documentation,
 214            ignore_completion_provider,
 215            completions: RefCell::new(completions).into(),
 216            match_candidates,
 217            entries: RefCell::new(Vec::new()).into(),
 218            selected_item: 0,
 219            scroll_handle: UniformListScrollHandle::new(),
 220            resolve_completions: true,
 221            last_rendered_range: RefCell::new(None).into(),
 222            markdown_element: None,
 223            snippet_sort_order,
 224        }
 225    }
 226
 227    pub fn new_snippet_choices(
 228        id: CompletionId,
 229        sort_completions: bool,
 230        choices: &Vec<String>,
 231        selection: Range<Anchor>,
 232        buffer: Entity<Buffer>,
 233        snippet_sort_order: SnippetSortOrder,
 234    ) -> Self {
 235        let completions = choices
 236            .iter()
 237            .map(|choice| Completion {
 238                replace_range: selection.start.text_anchor..selection.end.text_anchor,
 239                new_text: choice.to_string(),
 240                label: CodeLabel {
 241                    text: choice.to_string(),
 242                    runs: Default::default(),
 243                    filter_range: Default::default(),
 244                },
 245                icon_path: None,
 246                documentation: None,
 247                confirm: None,
 248                insert_text_mode: None,
 249                source: CompletionSource::Custom,
 250            })
 251            .collect();
 252
 253        let match_candidates = choices
 254            .iter()
 255            .enumerate()
 256            .map(|(id, completion)| StringMatchCandidate::new(id, &completion))
 257            .collect();
 258        let entries = choices
 259            .iter()
 260            .enumerate()
 261            .map(|(id, completion)| StringMatch {
 262                candidate_id: id,
 263                score: 1.,
 264                positions: vec![],
 265                string: completion.clone(),
 266            })
 267            .collect::<Vec<_>>();
 268        Self {
 269            id,
 270            sort_completions,
 271            initial_position: selection.start,
 272            buffer,
 273            completions: RefCell::new(completions).into(),
 274            match_candidates,
 275            entries: RefCell::new(entries).into(),
 276            selected_item: 0,
 277            scroll_handle: UniformListScrollHandle::new(),
 278            resolve_completions: false,
 279            show_completion_documentation: false,
 280            ignore_completion_provider: false,
 281            last_rendered_range: RefCell::new(None).into(),
 282            markdown_element: None,
 283            snippet_sort_order,
 284        }
 285    }
 286
 287    fn select_first(
 288        &mut self,
 289        provider: Option<&dyn CompletionProvider>,
 290        cx: &mut Context<Editor>,
 291    ) {
 292        let index = if self.scroll_handle.y_flipped() {
 293            self.entries.borrow().len() - 1
 294        } else {
 295            0
 296        };
 297        self.update_selection_index(index, provider, cx);
 298    }
 299
 300    fn select_last(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
 301        let index = if self.scroll_handle.y_flipped() {
 302            0
 303        } else {
 304            self.entries.borrow().len() - 1
 305        };
 306        self.update_selection_index(index, provider, cx);
 307    }
 308
 309    fn select_prev(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
 310        let index = if self.scroll_handle.y_flipped() {
 311            self.next_match_index()
 312        } else {
 313            self.prev_match_index()
 314        };
 315        self.update_selection_index(index, provider, cx);
 316    }
 317
 318    fn select_next(&mut self, provider: Option<&dyn CompletionProvider>, cx: &mut Context<Editor>) {
 319        let index = if self.scroll_handle.y_flipped() {
 320            self.prev_match_index()
 321        } else {
 322            self.next_match_index()
 323        };
 324        self.update_selection_index(index, provider, cx);
 325    }
 326
 327    fn update_selection_index(
 328        &mut self,
 329        match_index: usize,
 330        provider: Option<&dyn CompletionProvider>,
 331        cx: &mut Context<Editor>,
 332    ) {
 333        if self.selected_item != match_index {
 334            self.selected_item = match_index;
 335            self.scroll_handle
 336                .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 337            self.resolve_visible_completions(provider, cx);
 338            cx.notify();
 339        }
 340    }
 341
 342    fn prev_match_index(&self) -> usize {
 343        if self.selected_item > 0 {
 344            self.selected_item - 1
 345        } else {
 346            self.entries.borrow().len() - 1
 347        }
 348    }
 349
 350    fn next_match_index(&self) -> usize {
 351        if self.selected_item + 1 < self.entries.borrow().len() {
 352            self.selected_item + 1
 353        } else {
 354            0
 355        }
 356    }
 357
 358    pub fn resolve_visible_completions(
 359        &mut self,
 360        provider: Option<&dyn CompletionProvider>,
 361        cx: &mut Context<Editor>,
 362    ) {
 363        if !self.resolve_completions {
 364            return;
 365        }
 366        let Some(provider) = provider else {
 367            return;
 368        };
 369
 370        // Attempt to resolve completions for every item that will be displayed. This matters
 371        // because single line documentation may be displayed inline with the completion.
 372        //
 373        // When navigating to the very beginning or end of completions, `last_rendered_range` may
 374        // have no overlap with the completions that will be displayed, so instead use a range based
 375        // on the last rendered count.
 376        const APPROXIMATE_VISIBLE_COUNT: usize = 12;
 377        let last_rendered_range = self.last_rendered_range.borrow().clone();
 378        let visible_count = last_rendered_range
 379            .clone()
 380            .map_or(APPROXIMATE_VISIBLE_COUNT, |range| range.count());
 381        let entries = self.entries.borrow();
 382        let entry_range = if self.selected_item == 0 {
 383            0..min(visible_count, entries.len())
 384        } else if self.selected_item == entries.len() - 1 {
 385            entries.len().saturating_sub(visible_count)..entries.len()
 386        } else {
 387            last_rendered_range.map_or(0..0, |range| {
 388                min(range.start, entries.len())..min(range.end, entries.len())
 389            })
 390        };
 391
 392        // Expand the range to resolve more completions than are predicted to be visible, to reduce
 393        // jank on navigation.
 394        const EXTRA_TO_RESOLVE: usize = 4;
 395        let entry_indices = util::iterate_expanded_and_wrapped_usize_range(
 396            entry_range.clone(),
 397            EXTRA_TO_RESOLVE,
 398            EXTRA_TO_RESOLVE,
 399            entries.len(),
 400        );
 401
 402        // Avoid work by sometimes filtering out completions that already have documentation.
 403        // This filtering doesn't happen if the completions are currently being updated.
 404        let completions = self.completions.borrow();
 405        let candidate_ids = entry_indices
 406            .map(|i| entries[i].candidate_id)
 407            .filter(|i| completions[*i].documentation.is_none());
 408
 409        // Current selection is always resolved even if it already has documentation, to handle
 410        // out-of-spec language servers that return more results later.
 411        let selected_candidate_id = entries[self.selected_item].candidate_id;
 412        let candidate_ids = iter::once(selected_candidate_id)
 413            .chain(candidate_ids.filter(|id| *id != selected_candidate_id))
 414            .collect::<Vec<usize>>();
 415        drop(entries);
 416
 417        if candidate_ids.is_empty() {
 418            return;
 419        }
 420
 421        let resolve_task = provider.resolve_completions(
 422            self.buffer.clone(),
 423            candidate_ids,
 424            self.completions.clone(),
 425            cx,
 426        );
 427
 428        cx.spawn(async move |editor, cx| {
 429            if let Some(true) = resolve_task.await.log_err() {
 430                editor.update(cx, |_, cx| cx.notify()).ok();
 431            }
 432        })
 433        .detach();
 434    }
 435
 436    pub fn visible(&self) -> bool {
 437        !self.entries.borrow().is_empty()
 438    }
 439
 440    fn origin(&self) -> ContextMenuOrigin {
 441        ContextMenuOrigin::Cursor
 442    }
 443
 444    fn render(
 445        &self,
 446        style: &EditorStyle,
 447        max_height_in_lines: u32,
 448        window: &mut Window,
 449        cx: &mut Context<Editor>,
 450    ) -> AnyElement {
 451        let completions = self.completions.borrow_mut();
 452        let show_completion_documentation = self.show_completion_documentation;
 453        let widest_completion_ix = self
 454            .entries
 455            .borrow()
 456            .iter()
 457            .enumerate()
 458            .max_by_key(|(_, mat)| {
 459                let completion = &completions[mat.candidate_id];
 460                let documentation = &completion.documentation;
 461
 462                let mut len = completion.label.text.chars().count();
 463                if let Some(CompletionDocumentation::SingleLine(text)) = documentation {
 464                    if show_completion_documentation {
 465                        len += text.chars().count();
 466                    }
 467                }
 468
 469                len
 470            })
 471            .map(|(ix, _)| ix);
 472        drop(completions);
 473
 474        let selected_item = self.selected_item;
 475        let completions = self.completions.clone();
 476        let entries = self.entries.clone();
 477        let last_rendered_range = self.last_rendered_range.clone();
 478        let style = style.clone();
 479        let list = uniform_list(
 480            cx.entity().clone(),
 481            "completions",
 482            self.entries.borrow().len(),
 483            move |_editor, range, _window, cx| {
 484                last_rendered_range.borrow_mut().replace(range.clone());
 485                let start_ix = range.start;
 486                let completions_guard = completions.borrow_mut();
 487
 488                entries.borrow()[range]
 489                    .iter()
 490                    .enumerate()
 491                    .map(|(ix, mat)| {
 492                        let item_ix = start_ix + ix;
 493                        let completion = &completions_guard[mat.candidate_id];
 494                        let documentation = if show_completion_documentation {
 495                            &completion.documentation
 496                        } else {
 497                            &None
 498                        };
 499
 500                        let filter_start = completion.label.filter_range.start;
 501                        let highlights = gpui::combine_highlights(
 502                            mat.ranges().map(|range| {
 503                                (
 504                                    filter_start + range.start..filter_start + range.end,
 505                                    FontWeight::BOLD.into(),
 506                                )
 507                            }),
 508                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 509                                |(range, mut highlight)| {
 510                                    // Ignore font weight for syntax highlighting, as we'll use it
 511                                    // for fuzzy matches.
 512                                    highlight.font_weight = None;
 513                                    if completion
 514                                        .source
 515                                        .lsp_completion(false)
 516                                        .and_then(|lsp_completion| lsp_completion.deprecated)
 517                                        .unwrap_or(false)
 518                                    {
 519                                        highlight.strikethrough = Some(StrikethroughStyle {
 520                                            thickness: 1.0.into(),
 521                                            ..Default::default()
 522                                        });
 523                                        highlight.color = Some(cx.theme().colors().text_muted);
 524                                    }
 525
 526                                    (range, highlight)
 527                                },
 528                            ),
 529                        );
 530
 531                        let completion_label = StyledText::new(completion.label.text.clone())
 532                            .with_default_highlights(&style.text, highlights);
 533                        let documentation_label = if let Some(
 534                            CompletionDocumentation::SingleLine(text),
 535                        ) = documentation
 536                        {
 537                            if text.trim().is_empty() {
 538                                None
 539                            } else {
 540                                Some(
 541                                    Label::new(text.clone())
 542                                        .ml_4()
 543                                        .size(LabelSize::Small)
 544                                        .color(Color::Muted),
 545                                )
 546                            }
 547                        } else {
 548                            None
 549                        };
 550
 551                        let start_slot = completion
 552                            .color()
 553                            .map(|color| {
 554                                div()
 555                                    .flex_shrink_0()
 556                                    .size_3p5()
 557                                    .rounded_xs()
 558                                    .bg(color)
 559                                    .into_any_element()
 560                            })
 561                            .or_else(|| {
 562                                completion.icon_path.as_ref().map(|path| {
 563                                    Icon::from_path(path)
 564                                        .size(IconSize::XSmall)
 565                                        .color(Color::Muted)
 566                                        .into_any_element()
 567                                })
 568                            });
 569
 570                        div().min_w(px(280.)).max_w(px(540.)).child(
 571                            ListItem::new(mat.candidate_id)
 572                                .inset(true)
 573                                .toggle_state(item_ix == selected_item)
 574                                .on_click(cx.listener(move |editor, _event, window, cx| {
 575                                    cx.stop_propagation();
 576                                    if let Some(task) = editor.confirm_completion(
 577                                        &ConfirmCompletion {
 578                                            item_ix: Some(item_ix),
 579                                        },
 580                                        window,
 581                                        cx,
 582                                    ) {
 583                                        task.detach_and_log_err(cx)
 584                                    }
 585                                }))
 586                                .start_slot::<AnyElement>(start_slot)
 587                                .child(h_flex().overflow_hidden().child(completion_label))
 588                                .end_slot::<Label>(documentation_label),
 589                        )
 590                    })
 591                    .collect()
 592            },
 593        )
 594        .occlude()
 595        .max_h(max_height_in_lines as f32 * window.line_height())
 596        .track_scroll(self.scroll_handle.clone())
 597        .with_width_from_item(widest_completion_ix)
 598        .with_sizing_behavior(ListSizingBehavior::Infer);
 599
 600        Popover::new().child(list).into_any_element()
 601    }
 602
 603    fn render_aside(
 604        &mut self,
 605        editor: &Editor,
 606        max_size: Size<Pixels>,
 607        window: &mut Window,
 608        cx: &mut Context<Editor>,
 609    ) -> Option<AnyElement> {
 610        if !self.show_completion_documentation {
 611            return None;
 612        }
 613
 614        let mat = &self.entries.borrow()[self.selected_item];
 615        let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
 616            .documentation
 617            .as_ref()?
 618        {
 619            CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
 620            CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
 621                let markdown = self.markdown_element.get_or_insert_with(|| {
 622                    cx.new(|cx| {
 623                        let languages = editor
 624                            .workspace
 625                            .as_ref()
 626                            .and_then(|(workspace, _)| workspace.upgrade())
 627                            .map(|workspace| workspace.read(cx).app_state().languages.clone());
 628                        let language = editor
 629                            .language_at(self.initial_position, cx)
 630                            .map(|l| l.name().to_proto());
 631                        Markdown::new(SharedString::default(), languages, language, cx)
 632                    })
 633                });
 634                markdown.update(cx, |markdown, cx| {
 635                    markdown.reset(parsed.clone(), cx);
 636                });
 637                div().child(
 638                    MarkdownElement::new(markdown.clone(), hover_markdown_style(window, cx))
 639                        .code_block_renderer(markdown::CodeBlockRenderer::Default {
 640                            copy_button: false,
 641                            border: false,
 642                        })
 643                        .on_url_click(open_markdown_url),
 644                )
 645            }
 646            CompletionDocumentation::MultiLineMarkdown(_) => return None,
 647            CompletionDocumentation::SingleLine(_) => return None,
 648            CompletionDocumentation::Undocumented => return None,
 649        };
 650
 651        Some(
 652            Popover::new()
 653                .child(
 654                    multiline_docs
 655                        .id("multiline_docs")
 656                        .px(MENU_ASIDE_X_PADDING / 2.)
 657                        .max_w(max_size.width)
 658                        .max_h(max_size.height)
 659                        .overflow_y_scroll()
 660                        .occlude(),
 661                )
 662                .into_any_element(),
 663        )
 664    }
 665
 666    pub fn sort_matches(
 667        matches: &mut Vec<SortableMatch<'_>>,
 668        query: Option<&str>,
 669        snippet_sort_order: SnippetSortOrder,
 670    ) {
 671        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
 672        enum MatchTier<'a> {
 673            WordStartMatch {
 674                sort_score_int: Reverse<i32>,
 675                sort_snippet: Reverse<i32>,
 676                sort_text: Option<&'a str>,
 677                sort_key: (usize, &'a str),
 678            },
 679            OtherMatch {
 680                sort_score: Reverse<OrderedFloat<f64>>,
 681            },
 682        }
 683
 684        // Our goal here is to intelligently sort completion suggestions. We want to
 685        // balance the raw fuzzy match score with hints from the language server
 686        //
 687        // We first primary sort using fuzzy score by putting matches into two buckets
 688        // strong one and weak one. Among these buckets matches are then compared by
 689        // various criteria like snippet, LSP hints, kind, label text etc.
 690        //
 691        const FUZZY_THRESHOLD: f64 = 0.1317;
 692
 693        let query_start_lower = query
 694            .and_then(|q| q.chars().next())
 695            .and_then(|c| c.to_lowercase().next());
 696
 697        matches.sort_unstable_by_key(|mat| {
 698            let score = mat.string_match.score;
 699
 700            let is_other_match = query_start_lower
 701                .map(|query_char| {
 702                    !split_words(&mat.string_match.string).any(|word| {
 703                        word.chars()
 704                            .next()
 705                            .and_then(|c| c.to_lowercase().next())
 706                            .map_or(false, |word_char| word_char == query_char)
 707                    })
 708                })
 709                .unwrap_or(false);
 710
 711            if is_other_match {
 712                let sort_score = Reverse(OrderedFloat(score));
 713                MatchTier::OtherMatch { sort_score }
 714            } else {
 715                let sort_score_int = Reverse(if score >= FUZZY_THRESHOLD { 1 } else { 0 });
 716                let sort_snippet = match snippet_sort_order {
 717                    SnippetSortOrder::Top => Reverse(if mat.is_snippet { 1 } else { 0 }),
 718                    SnippetSortOrder::Bottom => Reverse(if mat.is_snippet { 0 } else { 1 }),
 719                    SnippetSortOrder::Inline => Reverse(0),
 720                };
 721                MatchTier::WordStartMatch {
 722                    sort_score_int,
 723                    sort_snippet,
 724                    sort_text: mat.sort_text,
 725                    sort_key: mat.sort_key,
 726                }
 727            }
 728        });
 729    }
 730
 731    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 732        let mut matches = if let Some(query) = query {
 733            fuzzy::match_strings(
 734                &self.match_candidates,
 735                query,
 736                query.chars().any(|c| c.is_uppercase()),
 737                100,
 738                &Default::default(),
 739                executor,
 740            )
 741            .await
 742        } else {
 743            self.match_candidates
 744                .iter()
 745                .enumerate()
 746                .map(|(candidate_id, candidate)| StringMatch {
 747                    candidate_id,
 748                    score: Default::default(),
 749                    positions: Default::default(),
 750                    string: candidate.string.clone(),
 751                })
 752                .collect()
 753        };
 754
 755        if self.sort_completions {
 756            let completions = self.completions.borrow();
 757
 758            let mut sortable_items: Vec<SortableMatch<'_>> = matches
 759                .into_iter()
 760                .map(|string_match| {
 761                    let completion = &completions[string_match.candidate_id];
 762
 763                    let is_snippet = matches!(
 764                        &completion.source,
 765                        CompletionSource::Lsp { lsp_completion, .. }
 766                        if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
 767                    );
 768
 769                    let sort_text =
 770                        if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
 771                            lsp_completion.sort_text.as_deref()
 772                        } else {
 773                            None
 774                        };
 775
 776                    let sort_key = completion.sort_key();
 777
 778                    SortableMatch {
 779                        string_match,
 780                        is_snippet,
 781                        sort_text,
 782                        sort_key,
 783                    }
 784                })
 785                .collect();
 786
 787            Self::sort_matches(&mut sortable_items, query, self.snippet_sort_order);
 788
 789            matches = sortable_items
 790                .into_iter()
 791                .map(|sortable| sortable.string_match)
 792                .collect();
 793        }
 794
 795        *self.entries.borrow_mut() = matches;
 796        self.selected_item = 0;
 797        // This keeps the display consistent when y_flipped.
 798        self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
 799    }
 800}
 801
 802#[derive(Debug)]
 803pub struct SortableMatch<'a> {
 804    pub string_match: StringMatch,
 805    pub is_snippet: bool,
 806    pub sort_text: Option<&'a str>,
 807    pub sort_key: (usize, &'a str),
 808}
 809
 810#[derive(Clone)]
 811pub struct AvailableCodeAction {
 812    pub excerpt_id: ExcerptId,
 813    pub action: CodeAction,
 814    pub provider: Rc<dyn CodeActionProvider>,
 815}
 816
 817#[derive(Clone)]
 818pub struct CodeActionContents {
 819    tasks: Option<Rc<ResolvedTasks>>,
 820    actions: Option<Rc<[AvailableCodeAction]>>,
 821}
 822
 823impl CodeActionContents {
 824    pub fn new(
 825        mut tasks: Option<ResolvedTasks>,
 826        actions: Option<Rc<[AvailableCodeAction]>>,
 827        cx: &App,
 828    ) -> Self {
 829        if !cx.has_flag::<DebuggerFeatureFlag>() {
 830            if let Some(tasks) = &mut tasks {
 831                tasks
 832                    .templates
 833                    .retain(|(_, task)| !matches!(task.task_type(), task::TaskType::Debug(_)));
 834            }
 835        }
 836
 837        Self {
 838            tasks: tasks.map(Rc::new),
 839            actions,
 840        }
 841    }
 842
 843    pub fn tasks(&self) -> Option<&ResolvedTasks> {
 844        self.tasks.as_deref()
 845    }
 846
 847    fn len(&self) -> usize {
 848        match (&self.tasks, &self.actions) {
 849            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 850            (Some(tasks), None) => tasks.templates.len(),
 851            (None, Some(actions)) => actions.len(),
 852            (None, None) => 0,
 853        }
 854    }
 855
 856    fn is_empty(&self) -> bool {
 857        match (&self.tasks, &self.actions) {
 858            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 859            (Some(tasks), None) => tasks.templates.is_empty(),
 860            (None, Some(actions)) => actions.is_empty(),
 861            (None, None) => true,
 862        }
 863    }
 864
 865    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 866        self.tasks
 867            .iter()
 868            .flat_map(|tasks| {
 869                tasks
 870                    .templates
 871                    .iter()
 872                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 873            })
 874            .chain(self.actions.iter().flat_map(|actions| {
 875                actions.iter().map(|available| CodeActionsItem::CodeAction {
 876                    excerpt_id: available.excerpt_id,
 877                    action: available.action.clone(),
 878                    provider: available.provider.clone(),
 879                })
 880            }))
 881    }
 882
 883    pub fn get(&self, index: usize) -> Option<CodeActionsItem> {
 884        match (&self.tasks, &self.actions) {
 885            (Some(tasks), Some(actions)) => {
 886                if index < tasks.templates.len() {
 887                    tasks
 888                        .templates
 889                        .get(index)
 890                        .cloned()
 891                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 892                } else {
 893                    actions.get(index - tasks.templates.len()).map(|available| {
 894                        CodeActionsItem::CodeAction {
 895                            excerpt_id: available.excerpt_id,
 896                            action: available.action.clone(),
 897                            provider: available.provider.clone(),
 898                        }
 899                    })
 900                }
 901            }
 902            (Some(tasks), None) => tasks
 903                .templates
 904                .get(index)
 905                .cloned()
 906                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 907            (None, Some(actions)) => {
 908                actions
 909                    .get(index)
 910                    .map(|available| CodeActionsItem::CodeAction {
 911                        excerpt_id: available.excerpt_id,
 912                        action: available.action.clone(),
 913                        provider: available.provider.clone(),
 914                    })
 915            }
 916            (None, None) => None,
 917        }
 918    }
 919}
 920
 921#[allow(clippy::large_enum_variant)]
 922#[derive(Clone)]
 923pub enum CodeActionsItem {
 924    Task(TaskSourceKind, ResolvedTask),
 925    CodeAction {
 926        excerpt_id: ExcerptId,
 927        action: CodeAction,
 928        provider: Rc<dyn CodeActionProvider>,
 929    },
 930}
 931
 932impl CodeActionsItem {
 933    fn as_task(&self) -> Option<&ResolvedTask> {
 934        let Self::Task(_, task) = self else {
 935            return None;
 936        };
 937        Some(task)
 938    }
 939
 940    fn as_code_action(&self) -> Option<&CodeAction> {
 941        let Self::CodeAction { action, .. } = self else {
 942            return None;
 943        };
 944        Some(action)
 945    }
 946
 947    pub fn label(&self) -> String {
 948        match self {
 949            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
 950            Self::Task(_, task) => task.resolved_label.clone(),
 951        }
 952    }
 953}
 954
 955pub struct CodeActionsMenu {
 956    pub actions: CodeActionContents,
 957    pub buffer: Entity<Buffer>,
 958    pub selected_item: usize,
 959    pub scroll_handle: UniformListScrollHandle,
 960    pub deployed_from_indicator: Option<DisplayRow>,
 961}
 962
 963impl CodeActionsMenu {
 964    fn select_first(&mut self, cx: &mut Context<Editor>) {
 965        self.selected_item = if self.scroll_handle.y_flipped() {
 966            self.actions.len() - 1
 967        } else {
 968            0
 969        };
 970        self.scroll_handle
 971            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 972        cx.notify()
 973    }
 974
 975    fn select_last(&mut self, cx: &mut Context<Editor>) {
 976        self.selected_item = if self.scroll_handle.y_flipped() {
 977            0
 978        } else {
 979            self.actions.len() - 1
 980        };
 981        self.scroll_handle
 982            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 983        cx.notify()
 984    }
 985
 986    fn select_prev(&mut self, cx: &mut Context<Editor>) {
 987        self.selected_item = if self.scroll_handle.y_flipped() {
 988            self.next_match_index()
 989        } else {
 990            self.prev_match_index()
 991        };
 992        self.scroll_handle
 993            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 994        cx.notify();
 995    }
 996
 997    fn select_next(&mut self, cx: &mut Context<Editor>) {
 998        self.selected_item = if self.scroll_handle.y_flipped() {
 999            self.prev_match_index()
1000        } else {
1001            self.next_match_index()
1002        };
1003        self.scroll_handle
1004            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1005        cx.notify();
1006    }
1007
1008    fn prev_match_index(&self) -> usize {
1009        if self.selected_item > 0 {
1010            self.selected_item - 1
1011        } else {
1012            self.actions.len() - 1
1013        }
1014    }
1015
1016    fn next_match_index(&self) -> usize {
1017        if self.selected_item + 1 < self.actions.len() {
1018            self.selected_item + 1
1019        } else {
1020            0
1021        }
1022    }
1023
1024    fn visible(&self) -> bool {
1025        !self.actions.is_empty()
1026    }
1027
1028    fn origin(&self) -> ContextMenuOrigin {
1029        if let Some(row) = self.deployed_from_indicator {
1030            ContextMenuOrigin::GutterIndicator(row)
1031        } else {
1032            ContextMenuOrigin::Cursor
1033        }
1034    }
1035
1036    fn render(
1037        &self,
1038        _style: &EditorStyle,
1039        max_height_in_lines: u32,
1040        window: &mut Window,
1041        cx: &mut Context<Editor>,
1042    ) -> AnyElement {
1043        let actions = self.actions.clone();
1044        let selected_item = self.selected_item;
1045        let list = uniform_list(
1046            cx.entity().clone(),
1047            "code_actions_menu",
1048            self.actions.len(),
1049            move |_this, range, _, cx| {
1050                actions
1051                    .iter()
1052                    .skip(range.start)
1053                    .take(range.end - range.start)
1054                    .enumerate()
1055                    .map(|(ix, action)| {
1056                        let item_ix = range.start + ix;
1057                        let selected = item_ix == selected_item;
1058                        let colors = cx.theme().colors();
1059                        div().min_w(px(220.)).max_w(px(540.)).child(
1060                            ListItem::new(item_ix)
1061                                .inset(true)
1062                                .toggle_state(selected)
1063                                .when_some(action.as_code_action(), |this, action| {
1064                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1065                                        cx.stop_propagation();
1066                                        if let Some(task) = editor.confirm_code_action(
1067                                            &ConfirmCodeAction {
1068                                                item_ix: Some(item_ix),
1069                                            },
1070                                            window,
1071                                            cx,
1072                                        ) {
1073                                            task.detach_and_log_err(cx)
1074                                        }
1075                                    }))
1076                                    .child(
1077                                        h_flex()
1078                                            .overflow_hidden()
1079                                            .child(
1080                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1081                                                action.lsp_action.title().replace("\n", ""),
1082                                            )
1083                                            .when(selected, |this| {
1084                                                this.text_color(colors.text_accent)
1085                                            }),
1086                                    )
1087                                })
1088                                .when_some(action.as_task(), |this, task| {
1089                                    this.on_click(cx.listener(move |editor, _, window, cx| {
1090                                        cx.stop_propagation();
1091                                        if let Some(task) = editor.confirm_code_action(
1092                                            &ConfirmCodeAction {
1093                                                item_ix: Some(item_ix),
1094                                            },
1095                                            window,
1096                                            cx,
1097                                        ) {
1098                                            task.detach_and_log_err(cx)
1099                                        }
1100                                    }))
1101                                    .child(
1102                                        h_flex()
1103                                            .overflow_hidden()
1104                                            .child(task.resolved_label.replace("\n", ""))
1105                                            .when(selected, |this| {
1106                                                this.text_color(colors.text_accent)
1107                                            }),
1108                                    )
1109                                }),
1110                        )
1111                    })
1112                    .collect()
1113            },
1114        )
1115        .occlude()
1116        .max_h(max_height_in_lines as f32 * window.line_height())
1117        .track_scroll(self.scroll_handle.clone())
1118        .with_width_from_item(
1119            self.actions
1120                .iter()
1121                .enumerate()
1122                .max_by_key(|(_, action)| match action {
1123                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1124                    CodeActionsItem::CodeAction { action, .. } => {
1125                        action.lsp_action.title().chars().count()
1126                    }
1127                })
1128                .map(|(ix, _)| ix),
1129        )
1130        .with_sizing_behavior(ListSizingBehavior::Infer);
1131
1132        Popover::new().child(list).into_any_element()
1133    }
1134}