code_context_menus.rs

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