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 show_completion_documentation = self.show_completion_documentation;
 454        let selected_item = self.selected_item;
 455        let completions = self.completions.clone();
 456        let entries = self.entries.clone();
 457        let last_rendered_range = self.last_rendered_range.clone();
 458        let style = style.clone();
 459        let list = uniform_list(
 460            cx.entity().clone(),
 461            "completions",
 462            self.entries.borrow().len(),
 463            move |_editor, range, _window, cx| {
 464                last_rendered_range.borrow_mut().replace(range.clone());
 465                let start_ix = range.start;
 466                let completions_guard = completions.borrow_mut();
 467
 468                entries.borrow()[range]
 469                    .iter()
 470                    .enumerate()
 471                    .map(|(ix, mat)| {
 472                        let item_ix = start_ix + ix;
 473                        let completion = &completions_guard[mat.candidate_id];
 474                        let documentation = if show_completion_documentation {
 475                            &completion.documentation
 476                        } else {
 477                            &None
 478                        };
 479
 480                        let filter_start = completion.label.filter_range.start;
 481                        let highlights = gpui::combine_highlights(
 482                            mat.ranges().map(|range| {
 483                                (
 484                                    filter_start + range.start..filter_start + range.end,
 485                                    FontWeight::BOLD.into(),
 486                                )
 487                            }),
 488                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 489                                |(range, mut highlight)| {
 490                                    // Ignore font weight for syntax highlighting, as we'll use it
 491                                    // for fuzzy matches.
 492                                    highlight.font_weight = None;
 493                                    if completion
 494                                        .source
 495                                        .lsp_completion(false)
 496                                        .and_then(|lsp_completion| lsp_completion.deprecated)
 497                                        .unwrap_or(false)
 498                                    {
 499                                        highlight.strikethrough = Some(StrikethroughStyle {
 500                                            thickness: 1.0.into(),
 501                                            ..Default::default()
 502                                        });
 503                                        highlight.color = Some(cx.theme().colors().text_muted);
 504                                    }
 505
 506                                    (range, highlight)
 507                                },
 508                            ),
 509                        );
 510
 511                        let completion_label = StyledText::new(completion.label.text.clone())
 512                            .with_default_highlights(&style.text, highlights);
 513
 514                        let documentation_label = match documentation {
 515                            Some(CompletionDocumentation::SingleLine(text))
 516                            | Some(CompletionDocumentation::SingleLineAndMultiLinePlainText {
 517                                single_line: text,
 518                                ..
 519                            }) => {
 520                                if text.trim().is_empty() {
 521                                    None
 522                                } else {
 523                                    Some(
 524                                        Label::new(text.clone())
 525                                            .ml_4()
 526                                            .size(LabelSize::Small)
 527                                            .color(Color::Muted),
 528                                    )
 529                                }
 530                            }
 531                            _ => None,
 532                        };
 533
 534                        let start_slot = completion
 535                            .color()
 536                            .map(|color| {
 537                                div()
 538                                    .flex_shrink_0()
 539                                    .size_3p5()
 540                                    .rounded_xs()
 541                                    .bg(color)
 542                                    .into_any_element()
 543                            })
 544                            .or_else(|| {
 545                                completion.icon_path.as_ref().map(|path| {
 546                                    Icon::from_path(path)
 547                                        .size(IconSize::XSmall)
 548                                        .color(Color::Muted)
 549                                        .into_any_element()
 550                                })
 551                            });
 552
 553                        div().min_w(px(280.)).max_w(px(540.)).child(
 554                            ListItem::new(mat.candidate_id)
 555                                .inset(true)
 556                                .toggle_state(item_ix == selected_item)
 557                                .on_click(cx.listener(move |editor, _event, window, cx| {
 558                                    cx.stop_propagation();
 559                                    if let Some(task) = editor.confirm_completion(
 560                                        &ConfirmCompletion {
 561                                            item_ix: Some(item_ix),
 562                                        },
 563                                        window,
 564                                        cx,
 565                                    ) {
 566                                        task.detach_and_log_err(cx)
 567                                    }
 568                                }))
 569                                .start_slot::<AnyElement>(start_slot)
 570                                .child(h_flex().overflow_hidden().child(completion_label))
 571                                .end_slot::<Label>(documentation_label),
 572                        )
 573                    })
 574                    .collect()
 575            },
 576        )
 577        .occlude()
 578        .max_h(max_height_in_lines as f32 * window.line_height())
 579        .track_scroll(self.scroll_handle.clone())
 580        .with_sizing_behavior(ListSizingBehavior::Infer)
 581        .w(rems(34.));
 582
 583        Popover::new().child(list).into_any_element()
 584    }
 585
 586    fn render_aside(
 587        &mut self,
 588        editor: &Editor,
 589        max_size: Size<Pixels>,
 590        window: &mut Window,
 591        cx: &mut Context<Editor>,
 592    ) -> Option<AnyElement> {
 593        if !self.show_completion_documentation {
 594            return None;
 595        }
 596
 597        let mat = &self.entries.borrow()[self.selected_item];
 598        let multiline_docs = match self.completions.borrow_mut()[mat.candidate_id]
 599            .documentation
 600            .as_ref()?
 601        {
 602            CompletionDocumentation::MultiLinePlainText(text) => div().child(text.clone()),
 603            CompletionDocumentation::SingleLineAndMultiLinePlainText {
 604                plain_text: Some(text),
 605                ..
 606            } => div().child(text.clone()),
 607            CompletionDocumentation::MultiLineMarkdown(parsed) if !parsed.is_empty() => {
 608                let markdown = self.markdown_element.get_or_insert_with(|| {
 609                    cx.new(|cx| {
 610                        let languages = editor
 611                            .workspace
 612                            .as_ref()
 613                            .and_then(|(workspace, _)| workspace.upgrade())
 614                            .map(|workspace| workspace.read(cx).app_state().languages.clone());
 615                        let language = editor
 616                            .language_at(self.initial_position, cx)
 617                            .map(|l| l.name().to_proto());
 618                        Markdown::new(SharedString::default(), languages, language, cx)
 619                    })
 620                });
 621                markdown.update(cx, |markdown, cx| {
 622                    markdown.reset(parsed.clone(), cx);
 623                });
 624                div().child(
 625                    MarkdownElement::new(markdown.clone(), hover_markdown_style(window, cx))
 626                        .code_block_renderer(markdown::CodeBlockRenderer::Default {
 627                            copy_button: false,
 628                            copy_button_on_hover: false,
 629                            border: false,
 630                        })
 631                        .on_url_click(open_markdown_url),
 632                )
 633            }
 634            CompletionDocumentation::MultiLineMarkdown(_) => return None,
 635            CompletionDocumentation::SingleLine(_) => return None,
 636            CompletionDocumentation::Undocumented => return None,
 637            CompletionDocumentation::SingleLineAndMultiLinePlainText {
 638                plain_text: None, ..
 639            } => {
 640                return None;
 641            }
 642        };
 643
 644        Some(
 645            Popover::new()
 646                .child(
 647                    multiline_docs
 648                        .id("multiline_docs")
 649                        .px(MENU_ASIDE_X_PADDING / 2.)
 650                        .max_w(max_size.width)
 651                        .max_h(max_size.height)
 652                        .overflow_y_scroll()
 653                        .occlude(),
 654                )
 655                .into_any_element(),
 656        )
 657    }
 658
 659    pub fn sort_matches(
 660        matches: &mut Vec<SortableMatch<'_>>,
 661        query: Option<&str>,
 662        snippet_sort_order: SnippetSortOrder,
 663    ) {
 664        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
 665        enum MatchTier<'a> {
 666            WordStartMatch {
 667                sort_mixed_case_prefix_length: Reverse<usize>,
 668                sort_snippet: Reverse<i32>,
 669                sort_kind: usize,
 670                sort_fuzzy_bracket: Reverse<usize>,
 671                sort_text: Option<&'a str>,
 672                sort_score: Reverse<OrderedFloat<f64>>,
 673                sort_label: &'a str,
 674            },
 675            OtherMatch {
 676                sort_score: Reverse<OrderedFloat<f64>>,
 677            },
 678        }
 679
 680        // Our goal here is to intelligently sort completion suggestions. We want to
 681        // balance the raw fuzzy match score with hints from the language server
 682
 683        // In a fuzzy bracket, matches with a score of 1.0 are prioritized.
 684        // The remaining matches are partitioned into two groups at 3/5 of the max_score.
 685        let max_score = matches
 686            .iter()
 687            .map(|mat| mat.string_match.score)
 688            .fold(0.0, f64::max);
 689        let fuzzy_bracket_threshold = max_score * (3.0 / 5.0);
 690
 691        let query_start_lower = query
 692            .and_then(|q| q.chars().next())
 693            .and_then(|c| c.to_lowercase().next());
 694
 695        matches.sort_unstable_by_key(|mat| {
 696            let score = mat.string_match.score;
 697            let sort_score = Reverse(OrderedFloat(score));
 698
 699            let query_start_doesnt_match_split_words = query_start_lower
 700                .map(|query_char| {
 701                    !split_words(&mat.string_match.string).any(|word| {
 702                        word.chars()
 703                            .next()
 704                            .and_then(|c| c.to_lowercase().next())
 705                            .map_or(false, |word_char| word_char == query_char)
 706                    })
 707                })
 708                .unwrap_or(false);
 709
 710            if query_start_doesnt_match_split_words {
 711                MatchTier::OtherMatch { sort_score }
 712            } else {
 713                let sort_fuzzy_bracket = Reverse(if score >= fuzzy_bracket_threshold {
 714                    1
 715                } else {
 716                    0
 717                });
 718                let sort_snippet = match snippet_sort_order {
 719                    SnippetSortOrder::Top => Reverse(if mat.is_snippet { 1 } else { 0 }),
 720                    SnippetSortOrder::Bottom => Reverse(if mat.is_snippet { 0 } else { 1 }),
 721                    SnippetSortOrder::Inline => Reverse(0),
 722                };
 723                let sort_mixed_case_prefix_length = Reverse(
 724                    query
 725                        .map(|q| {
 726                            q.chars()
 727                                .zip(mat.string_match.string.chars())
 728                                .enumerate()
 729                                .take_while(|(i, (q_char, match_char))| {
 730                                    if *i == 0 {
 731                                        // Case-sensitive comparison for first character
 732                                        q_char == match_char
 733                                    } else {
 734                                        // Case-insensitive comparison for other characters
 735                                        q_char.to_lowercase().eq(match_char.to_lowercase())
 736                                    }
 737                                })
 738                                .count()
 739                        })
 740                        .unwrap_or(0),
 741                );
 742                MatchTier::WordStartMatch {
 743                    sort_mixed_case_prefix_length,
 744                    sort_snippet,
 745                    sort_kind: mat.sort_kind,
 746                    sort_fuzzy_bracket,
 747                    sort_text: mat.sort_text,
 748                    sort_score,
 749                    sort_label: mat.sort_label,
 750                }
 751            }
 752        });
 753    }
 754
 755    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 756        let mut matches = if let Some(query) = query {
 757            fuzzy::match_strings(
 758                &self.match_candidates,
 759                query,
 760                query.chars().any(|c| c.is_uppercase()),
 761                100,
 762                &Default::default(),
 763                executor,
 764            )
 765            .await
 766        } else {
 767            self.match_candidates
 768                .iter()
 769                .enumerate()
 770                .map(|(candidate_id, candidate)| StringMatch {
 771                    candidate_id,
 772                    score: Default::default(),
 773                    positions: Default::default(),
 774                    string: candidate.string.clone(),
 775                })
 776                .collect()
 777        };
 778
 779        if self.sort_completions {
 780            let completions = self.completions.borrow();
 781
 782            let mut sortable_items: Vec<SortableMatch<'_>> = matches
 783                .into_iter()
 784                .map(|string_match| {
 785                    let completion = &completions[string_match.candidate_id];
 786
 787                    let is_snippet = matches!(
 788                        &completion.source,
 789                        CompletionSource::Lsp { lsp_completion, .. }
 790                        if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
 791                    );
 792
 793                    let sort_text =
 794                        if let CompletionSource::Lsp { lsp_completion, .. } = &completion.source {
 795                            lsp_completion.sort_text.as_deref()
 796                        } else {
 797                            None
 798                        };
 799
 800                    let (sort_kind, sort_label) = completion.sort_key();
 801
 802                    SortableMatch {
 803                        string_match,
 804                        is_snippet,
 805                        sort_text,
 806                        sort_kind,
 807                        sort_label,
 808                    }
 809                })
 810                .collect();
 811
 812            Self::sort_matches(&mut sortable_items, query, self.snippet_sort_order);
 813
 814            matches = sortable_items
 815                .into_iter()
 816                .map(|sortable| sortable.string_match)
 817                .collect();
 818        }
 819
 820        *self.entries.borrow_mut() = matches;
 821        self.selected_item = 0;
 822        // This keeps the display consistent when y_flipped.
 823        self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
 824    }
 825}
 826
 827#[derive(Debug)]
 828pub struct SortableMatch<'a> {
 829    pub string_match: StringMatch,
 830    pub is_snippet: bool,
 831    pub sort_text: Option<&'a str>,
 832    pub sort_kind: usize,
 833    pub sort_label: &'a str,
 834}
 835
 836#[derive(Clone)]
 837pub struct AvailableCodeAction {
 838    pub excerpt_id: ExcerptId,
 839    pub action: CodeAction,
 840    pub provider: Rc<dyn CodeActionProvider>,
 841}
 842
 843#[derive(Clone)]
 844pub(crate) struct CodeActionContents {
 845    tasks: Option<Rc<ResolvedTasks>>,
 846    actions: Option<Rc<[AvailableCodeAction]>>,
 847    debug_scenarios: Vec<DebugScenario>,
 848    pub(crate) context: TaskContext,
 849}
 850
 851impl CodeActionContents {
 852    pub(crate) fn new(
 853        tasks: Option<ResolvedTasks>,
 854        actions: Option<Rc<[AvailableCodeAction]>>,
 855        debug_scenarios: Vec<DebugScenario>,
 856        context: TaskContext,
 857    ) -> Self {
 858        Self {
 859            tasks: tasks.map(Rc::new),
 860            actions,
 861            debug_scenarios,
 862            context,
 863        }
 864    }
 865
 866    pub fn tasks(&self) -> Option<&ResolvedTasks> {
 867        self.tasks.as_deref()
 868    }
 869
 870    fn len(&self) -> usize {
 871        let tasks_len = self.tasks.as_ref().map_or(0, |tasks| tasks.templates.len());
 872        let code_actions_len = self.actions.as_ref().map_or(0, |actions| actions.len());
 873        tasks_len + code_actions_len + self.debug_scenarios.len()
 874    }
 875
 876    fn is_empty(&self) -> bool {
 877        self.len() == 0
 878    }
 879
 880    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 881        self.tasks
 882            .iter()
 883            .flat_map(|tasks| {
 884                tasks
 885                    .templates
 886                    .iter()
 887                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 888            })
 889            .chain(self.actions.iter().flat_map(|actions| {
 890                actions.iter().map(|available| CodeActionsItem::CodeAction {
 891                    excerpt_id: available.excerpt_id,
 892                    action: available.action.clone(),
 893                    provider: available.provider.clone(),
 894                })
 895            }))
 896            .chain(
 897                self.debug_scenarios
 898                    .iter()
 899                    .cloned()
 900                    .map(CodeActionsItem::DebugScenario),
 901            )
 902    }
 903
 904    pub fn get(&self, mut index: usize) -> Option<CodeActionsItem> {
 905        if let Some(tasks) = &self.tasks {
 906            if let Some((kind, task)) = tasks.templates.get(index) {
 907                return Some(CodeActionsItem::Task(kind.clone(), task.clone()));
 908            } else {
 909                index -= tasks.templates.len();
 910            }
 911        }
 912        if let Some(actions) = &self.actions {
 913            if let Some(available) = actions.get(index) {
 914                return Some(CodeActionsItem::CodeAction {
 915                    excerpt_id: available.excerpt_id,
 916                    action: available.action.clone(),
 917                    provider: available.provider.clone(),
 918                });
 919            } else {
 920                index -= actions.len();
 921            }
 922        }
 923
 924        self.debug_scenarios
 925            .get(index)
 926            .cloned()
 927            .map(CodeActionsItem::DebugScenario)
 928    }
 929}
 930
 931#[allow(clippy::large_enum_variant)]
 932#[derive(Clone)]
 933pub enum CodeActionsItem {
 934    Task(TaskSourceKind, ResolvedTask),
 935    CodeAction {
 936        excerpt_id: ExcerptId,
 937        action: CodeAction,
 938        provider: Rc<dyn CodeActionProvider>,
 939    },
 940    DebugScenario(DebugScenario),
 941}
 942
 943impl CodeActionsItem {
 944    fn as_task(&self) -> Option<&ResolvedTask> {
 945        let Self::Task(_, task) = self else {
 946            return None;
 947        };
 948        Some(task)
 949    }
 950
 951    fn as_code_action(&self) -> Option<&CodeAction> {
 952        let Self::CodeAction { action, .. } = self else {
 953            return None;
 954        };
 955        Some(action)
 956    }
 957    fn as_debug_scenario(&self) -> Option<&DebugScenario> {
 958        let Self::DebugScenario(scenario) = self else {
 959            return None;
 960        };
 961        Some(scenario)
 962    }
 963
 964    pub fn label(&self) -> String {
 965        match self {
 966            Self::CodeAction { action, .. } => action.lsp_action.title().to_owned(),
 967            Self::Task(_, task) => task.resolved_label.clone(),
 968            Self::DebugScenario(scenario) => scenario.label.to_string(),
 969        }
 970    }
 971}
 972
 973pub(crate) struct CodeActionsMenu {
 974    pub actions: CodeActionContents,
 975    pub buffer: Entity<Buffer>,
 976    pub selected_item: usize,
 977    pub scroll_handle: UniformListScrollHandle,
 978    pub deployed_from_indicator: Option<DisplayRow>,
 979}
 980
 981impl CodeActionsMenu {
 982    fn select_first(&mut self, cx: &mut Context<Editor>) {
 983        self.selected_item = if self.scroll_handle.y_flipped() {
 984            self.actions.len() - 1
 985        } else {
 986            0
 987        };
 988        self.scroll_handle
 989            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
 990        cx.notify()
 991    }
 992
 993    fn select_last(&mut self, cx: &mut Context<Editor>) {
 994        self.selected_item = if self.scroll_handle.y_flipped() {
 995            0
 996        } else {
 997            self.actions.len() - 1
 998        };
 999        self.scroll_handle
1000            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1001        cx.notify()
1002    }
1003
1004    fn select_prev(&mut self, cx: &mut Context<Editor>) {
1005        self.selected_item = if self.scroll_handle.y_flipped() {
1006            self.next_match_index()
1007        } else {
1008            self.prev_match_index()
1009        };
1010        self.scroll_handle
1011            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1012        cx.notify();
1013    }
1014
1015    fn select_next(&mut self, cx: &mut Context<Editor>) {
1016        self.selected_item = if self.scroll_handle.y_flipped() {
1017            self.prev_match_index()
1018        } else {
1019            self.next_match_index()
1020        };
1021        self.scroll_handle
1022            .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1023        cx.notify();
1024    }
1025
1026    fn prev_match_index(&self) -> usize {
1027        if self.selected_item > 0 {
1028            self.selected_item - 1
1029        } else {
1030            self.actions.len() - 1
1031        }
1032    }
1033
1034    fn next_match_index(&self) -> usize {
1035        if self.selected_item + 1 < self.actions.len() {
1036            self.selected_item + 1
1037        } else {
1038            0
1039        }
1040    }
1041
1042    fn visible(&self) -> bool {
1043        !self.actions.is_empty()
1044    }
1045
1046    fn origin(&self) -> ContextMenuOrigin {
1047        if let Some(row) = self.deployed_from_indicator {
1048            ContextMenuOrigin::GutterIndicator(row)
1049        } else {
1050            ContextMenuOrigin::Cursor
1051        }
1052    }
1053
1054    fn render(
1055        &self,
1056        _style: &EditorStyle,
1057        max_height_in_lines: u32,
1058        window: &mut Window,
1059        cx: &mut Context<Editor>,
1060    ) -> AnyElement {
1061        let actions = self.actions.clone();
1062        let selected_item = self.selected_item;
1063        let list = uniform_list(
1064            cx.entity().clone(),
1065            "code_actions_menu",
1066            self.actions.len(),
1067            move |_this, range, _, cx| {
1068                actions
1069                    .iter()
1070                    .skip(range.start)
1071                    .take(range.end - range.start)
1072                    .enumerate()
1073                    .map(|(ix, action)| {
1074                        let item_ix = range.start + ix;
1075                        let selected = item_ix == selected_item;
1076                        let colors = cx.theme().colors();
1077                        div().min_w(px(220.)).max_w(px(540.)).child(
1078                            ListItem::new(item_ix)
1079                                .inset(true)
1080                                .toggle_state(selected)
1081                                .when_some(action.as_code_action(), |this, action| {
1082                                    this.child(
1083                                        h_flex()
1084                                            .overflow_hidden()
1085                                            .child(
1086                                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1087                                                action.lsp_action.title().replace("\n", ""),
1088                                            )
1089                                            .when(selected, |this| {
1090                                                this.text_color(colors.text_accent)
1091                                            }),
1092                                    )
1093                                })
1094                                .when_some(action.as_task(), |this, task| {
1095                                    this.child(
1096                                        h_flex()
1097                                            .overflow_hidden()
1098                                            .child(task.resolved_label.replace("\n", ""))
1099                                            .when(selected, |this| {
1100                                                this.text_color(colors.text_accent)
1101                                            }),
1102                                    )
1103                                })
1104                                .when_some(action.as_debug_scenario(), |this, scenario| {
1105                                    this.child(
1106                                        h_flex()
1107                                            .overflow_hidden()
1108                                            .child("debug: ")
1109                                            .child(scenario.label.clone())
1110                                            .when(selected, |this| {
1111                                                this.text_color(colors.text_accent)
1112                                            }),
1113                                    )
1114                                })
1115                                .on_click(cx.listener(move |editor, _, window, cx| {
1116                                    cx.stop_propagation();
1117                                    if let Some(task) = editor.confirm_code_action(
1118                                        &ConfirmCodeAction {
1119                                            item_ix: Some(item_ix),
1120                                        },
1121                                        window,
1122                                        cx,
1123                                    ) {
1124                                        task.detach_and_log_err(cx)
1125                                    }
1126                                })),
1127                        )
1128                    })
1129                    .collect()
1130            },
1131        )
1132        .occlude()
1133        .max_h(max_height_in_lines as f32 * window.line_height())
1134        .track_scroll(self.scroll_handle.clone())
1135        .with_width_from_item(
1136            self.actions
1137                .iter()
1138                .enumerate()
1139                .max_by_key(|(_, action)| match action {
1140                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1141                    CodeActionsItem::CodeAction { action, .. } => {
1142                        action.lsp_action.title().chars().count()
1143                    }
1144                    CodeActionsItem::DebugScenario(scenario) => {
1145                        format!("debug: {}", scenario.label).chars().count()
1146                    }
1147                })
1148                .map(|(ix, _)| ix),
1149        )
1150        .with_sizing_behavior(ListSizingBehavior::Infer);
1151
1152        Popover::new().child(list).into_any_element()
1153    }
1154}