completion_provider.rs

   1use std::cell::RefCell;
   2use std::ops::Range;
   3use std::path::PathBuf;
   4use std::rc::Rc;
   5use std::sync::Arc;
   6use std::sync::atomic::AtomicBool;
   7
   8use acp_thread::MentionUri;
   9use agent::{HistoryEntry, HistoryStore};
  10use agent_client_protocol as acp;
  11use anyhow::Result;
  12use editor::{CompletionProvider, Editor, ExcerptId};
  13use fuzzy::{StringMatch, StringMatchCandidate};
  14use gpui::{App, Entity, Task, WeakEntity};
  15use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
  16use lsp::CompletionContext;
  17use project::lsp_store::{CompletionDocumentation, SymbolLocation};
  18use project::{
  19    Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, Project,
  20    ProjectPath, Symbol, WorktreeId,
  21};
  22use prompt_store::PromptStore;
  23use rope::Point;
  24use text::{Anchor, ToPoint as _};
  25use ui::prelude::*;
  26use util::rel_path::RelPath;
  27use workspace::Workspace;
  28
  29use crate::AgentPanel;
  30use crate::acp::message_editor::MessageEditor;
  31use crate::context_picker::file_context_picker::{FileMatch, search_files};
  32use crate::context_picker::rules_context_picker::{RulesContextEntry, search_rules};
  33use crate::context_picker::symbol_context_picker::SymbolMatch;
  34use crate::context_picker::symbol_context_picker::search_symbols;
  35use crate::context_picker::thread_context_picker::search_threads;
  36use crate::context_picker::{
  37    ContextPickerAction, ContextPickerEntry, ContextPickerMode, selection_ranges,
  38};
  39
  40pub(crate) enum Match {
  41    File(FileMatch),
  42    Symbol(SymbolMatch),
  43    Thread(HistoryEntry),
  44    RecentThread(HistoryEntry),
  45    Fetch(SharedString),
  46    Rules(RulesContextEntry),
  47    Entry(EntryMatch),
  48}
  49
  50pub struct EntryMatch {
  51    mat: Option<StringMatch>,
  52    entry: ContextPickerEntry,
  53}
  54
  55impl Match {
  56    pub fn score(&self) -> f64 {
  57        match self {
  58            Match::File(file) => file.mat.score,
  59            Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
  60            Match::Thread(_) => 1.,
  61            Match::RecentThread(_) => 1.,
  62            Match::Symbol(_) => 1.,
  63            Match::Rules(_) => 1.,
  64            Match::Fetch(_) => 1.,
  65        }
  66    }
  67}
  68
  69pub struct ContextPickerCompletionProvider {
  70    message_editor: WeakEntity<MessageEditor>,
  71    workspace: WeakEntity<Workspace>,
  72    history_store: Entity<HistoryStore>,
  73    prompt_store: Option<Entity<PromptStore>>,
  74    prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
  75    available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
  76}
  77
  78impl ContextPickerCompletionProvider {
  79    pub fn new(
  80        message_editor: WeakEntity<MessageEditor>,
  81        workspace: WeakEntity<Workspace>,
  82        history_store: Entity<HistoryStore>,
  83        prompt_store: Option<Entity<PromptStore>>,
  84        prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
  85        available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
  86    ) -> Self {
  87        Self {
  88            message_editor,
  89            workspace,
  90            history_store,
  91            prompt_store,
  92            prompt_capabilities,
  93            available_commands,
  94        }
  95    }
  96
  97    fn completion_for_entry(
  98        entry: ContextPickerEntry,
  99        source_range: Range<Anchor>,
 100        message_editor: WeakEntity<MessageEditor>,
 101        workspace: &Entity<Workspace>,
 102        cx: &mut App,
 103    ) -> Option<Completion> {
 104        match entry {
 105            ContextPickerEntry::Mode(mode) => Some(Completion {
 106                replace_range: source_range,
 107                new_text: format!("@{} ", mode.keyword()),
 108                label: CodeLabel::plain(mode.label().to_string(), None),
 109                icon_path: Some(mode.icon().path().into()),
 110                documentation: None,
 111                source: project::CompletionSource::Custom,
 112                insert_text_mode: None,
 113                // This ensures that when a user accepts this completion, the
 114                // completion menu will still be shown after "@category " is
 115                // inserted
 116                confirm: Some(Arc::new(|_, _, _| true)),
 117            }),
 118            ContextPickerEntry::Action(action) => {
 119                Self::completion_for_action(action, source_range, message_editor, workspace, cx)
 120            }
 121        }
 122    }
 123
 124    fn completion_for_thread(
 125        thread_entry: HistoryEntry,
 126        source_range: Range<Anchor>,
 127        recent: bool,
 128        editor: WeakEntity<MessageEditor>,
 129        cx: &mut App,
 130    ) -> Completion {
 131        let uri = thread_entry.mention_uri();
 132
 133        let icon_for_completion = if recent {
 134            IconName::HistoryRerun.path().into()
 135        } else {
 136            uri.icon_path(cx)
 137        };
 138
 139        let new_text = format!("{} ", uri.as_link());
 140
 141        let new_text_len = new_text.len();
 142        Completion {
 143            replace_range: source_range.clone(),
 144            new_text,
 145            label: CodeLabel::plain(thread_entry.title().to_string(), None),
 146            documentation: None,
 147            insert_text_mode: None,
 148            source: project::CompletionSource::Custom,
 149            icon_path: Some(icon_for_completion),
 150            confirm: Some(confirm_completion_callback(
 151                thread_entry.title().clone(),
 152                source_range.start,
 153                new_text_len - 1,
 154                editor,
 155                uri,
 156            )),
 157        }
 158    }
 159
 160    fn completion_for_rules(
 161        rule: RulesContextEntry,
 162        source_range: Range<Anchor>,
 163        editor: WeakEntity<MessageEditor>,
 164        cx: &mut App,
 165    ) -> Completion {
 166        let uri = MentionUri::Rule {
 167            id: rule.prompt_id.into(),
 168            name: rule.title.to_string(),
 169        };
 170        let new_text = format!("{} ", uri.as_link());
 171        let new_text_len = new_text.len();
 172        let icon_path = uri.icon_path(cx);
 173        Completion {
 174            replace_range: source_range.clone(),
 175            new_text,
 176            label: CodeLabel::plain(rule.title.to_string(), None),
 177            documentation: None,
 178            insert_text_mode: None,
 179            source: project::CompletionSource::Custom,
 180            icon_path: Some(icon_path),
 181            confirm: Some(confirm_completion_callback(
 182                rule.title,
 183                source_range.start,
 184                new_text_len - 1,
 185                editor,
 186                uri,
 187            )),
 188        }
 189    }
 190
 191    pub(crate) fn completion_for_path(
 192        project_path: ProjectPath,
 193        path_prefix: &RelPath,
 194        is_recent: bool,
 195        is_directory: bool,
 196        source_range: Range<Anchor>,
 197        message_editor: WeakEntity<MessageEditor>,
 198        project: Entity<Project>,
 199        cx: &mut App,
 200    ) -> Option<Completion> {
 201        let path_style = project.read(cx).path_style(cx);
 202        let (file_name, directory) =
 203            crate::context_picker::file_context_picker::extract_file_name_and_directory(
 204                &project_path.path,
 205                path_prefix,
 206                path_style,
 207            );
 208
 209        let label =
 210            build_code_label_for_full_path(&file_name, directory.as_ref().map(|s| s.as_ref()), cx);
 211
 212        let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
 213
 214        let uri = if is_directory {
 215            MentionUri::Directory { abs_path }
 216        } else {
 217            MentionUri::File { abs_path }
 218        };
 219
 220        let crease_icon_path = uri.icon_path(cx);
 221        let completion_icon_path = if is_recent {
 222            IconName::HistoryRerun.path().into()
 223        } else {
 224            crease_icon_path
 225        };
 226
 227        let new_text = format!("{} ", uri.as_link());
 228        let new_text_len = new_text.len();
 229        Some(Completion {
 230            replace_range: source_range.clone(),
 231            new_text,
 232            label,
 233            documentation: None,
 234            source: project::CompletionSource::Custom,
 235            icon_path: Some(completion_icon_path),
 236            insert_text_mode: None,
 237            confirm: Some(confirm_completion_callback(
 238                file_name,
 239                source_range.start,
 240                new_text_len - 1,
 241                message_editor,
 242                uri,
 243            )),
 244        })
 245    }
 246
 247    fn completion_for_symbol(
 248        symbol: Symbol,
 249        source_range: Range<Anchor>,
 250        message_editor: WeakEntity<MessageEditor>,
 251        workspace: Entity<Workspace>,
 252        cx: &mut App,
 253    ) -> Option<Completion> {
 254        let project = workspace.read(cx).project().clone();
 255
 256        let label = CodeLabel::plain(symbol.name.clone(), None);
 257
 258        let abs_path = match &symbol.path {
 259            SymbolLocation::InProject(project_path) => {
 260                project.read(cx).absolute_path(&project_path, cx)?
 261            }
 262            SymbolLocation::OutsideProject {
 263                abs_path,
 264                signature: _,
 265            } => PathBuf::from(abs_path.as_ref()),
 266        };
 267        let uri = MentionUri::Symbol {
 268            abs_path,
 269            name: symbol.name.clone(),
 270            line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
 271        };
 272        let new_text = format!("{} ", uri.as_link());
 273        let new_text_len = new_text.len();
 274        let icon_path = uri.icon_path(cx);
 275        Some(Completion {
 276            replace_range: source_range.clone(),
 277            new_text,
 278            label,
 279            documentation: None,
 280            source: project::CompletionSource::Custom,
 281            icon_path: Some(icon_path),
 282            insert_text_mode: None,
 283            confirm: Some(confirm_completion_callback(
 284                symbol.name.into(),
 285                source_range.start,
 286                new_text_len - 1,
 287                message_editor,
 288                uri,
 289            )),
 290        })
 291    }
 292
 293    fn completion_for_fetch(
 294        source_range: Range<Anchor>,
 295        url_to_fetch: SharedString,
 296        message_editor: WeakEntity<MessageEditor>,
 297        cx: &mut App,
 298    ) -> Option<Completion> {
 299        let new_text = format!("@fetch {} ", url_to_fetch);
 300        let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
 301            .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
 302            .ok()?;
 303        let mention_uri = MentionUri::Fetch {
 304            url: url_to_fetch.clone(),
 305        };
 306        let icon_path = mention_uri.icon_path(cx);
 307        Some(Completion {
 308            replace_range: source_range.clone(),
 309            new_text: new_text.clone(),
 310            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 311            documentation: None,
 312            source: project::CompletionSource::Custom,
 313            icon_path: Some(icon_path),
 314            insert_text_mode: None,
 315            confirm: Some(confirm_completion_callback(
 316                url_to_fetch.to_string().into(),
 317                source_range.start,
 318                new_text.len() - 1,
 319                message_editor,
 320                mention_uri,
 321            )),
 322        })
 323    }
 324
 325    pub(crate) fn completion_for_action(
 326        action: ContextPickerAction,
 327        source_range: Range<Anchor>,
 328        message_editor: WeakEntity<MessageEditor>,
 329        workspace: &Entity<Workspace>,
 330        cx: &mut App,
 331    ) -> Option<Completion> {
 332        let (new_text, on_action) = match action {
 333            ContextPickerAction::AddSelections => {
 334                const PLACEHOLDER: &str = "selection ";
 335                let selections = selection_ranges(workspace, cx)
 336                    .into_iter()
 337                    .enumerate()
 338                    .map(|(ix, (buffer, range))| {
 339                        (
 340                            buffer,
 341                            range,
 342                            (PLACEHOLDER.len() * ix)..(PLACEHOLDER.len() * (ix + 1) - 1),
 343                        )
 344                    })
 345                    .collect::<Vec<_>>();
 346
 347                let new_text: String = PLACEHOLDER.repeat(selections.len());
 348
 349                let callback = Arc::new({
 350                    let source_range = source_range.clone();
 351                    move |_, window: &mut Window, cx: &mut App| {
 352                        let selections = selections.clone();
 353                        let message_editor = message_editor.clone();
 354                        let source_range = source_range.clone();
 355                        window.defer(cx, move |window, cx| {
 356                            message_editor
 357                                .update(cx, |message_editor, cx| {
 358                                    message_editor.confirm_mention_for_selection(
 359                                        source_range,
 360                                        selections,
 361                                        window,
 362                                        cx,
 363                                    )
 364                                })
 365                                .ok();
 366                        });
 367                        false
 368                    }
 369                });
 370
 371                (new_text, callback)
 372            }
 373        };
 374
 375        Some(Completion {
 376            replace_range: source_range,
 377            new_text,
 378            label: CodeLabel::plain(action.label().to_string(), None),
 379            icon_path: Some(action.icon().path().into()),
 380            documentation: None,
 381            source: project::CompletionSource::Custom,
 382            insert_text_mode: None,
 383            // This ensures that when a user accepts this completion, the
 384            // completion menu will still be shown after "@category " is
 385            // inserted
 386            confirm: Some(on_action),
 387        })
 388    }
 389
 390    fn search_slash_commands(
 391        &self,
 392        query: String,
 393        cx: &mut App,
 394    ) -> Task<Vec<acp::AvailableCommand>> {
 395        let commands = self.available_commands.borrow().clone();
 396        if commands.is_empty() {
 397            return Task::ready(Vec::new());
 398        }
 399
 400        cx.spawn(async move |cx| {
 401            let candidates = commands
 402                .iter()
 403                .enumerate()
 404                .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
 405                .collect::<Vec<_>>();
 406
 407            let matches = fuzzy::match_strings(
 408                &candidates,
 409                &query,
 410                false,
 411                true,
 412                100,
 413                &Arc::new(AtomicBool::default()),
 414                cx.background_executor().clone(),
 415            )
 416            .await;
 417
 418            matches
 419                .into_iter()
 420                .map(|mat| commands[mat.candidate_id].clone())
 421                .collect()
 422        })
 423    }
 424
 425    fn search_mentions(
 426        &self,
 427        mode: Option<ContextPickerMode>,
 428        query: String,
 429        cancellation_flag: Arc<AtomicBool>,
 430        cx: &mut App,
 431    ) -> Task<Vec<Match>> {
 432        let Some(workspace) = self.workspace.upgrade() else {
 433            return Task::ready(Vec::default());
 434        };
 435        match mode {
 436            Some(ContextPickerMode::File) => {
 437                let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
 438                cx.background_spawn(async move {
 439                    search_files_task
 440                        .await
 441                        .into_iter()
 442                        .map(Match::File)
 443                        .collect()
 444                })
 445            }
 446
 447            Some(ContextPickerMode::Symbol) => {
 448                let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
 449                cx.background_spawn(async move {
 450                    search_symbols_task
 451                        .await
 452                        .into_iter()
 453                        .map(Match::Symbol)
 454                        .collect()
 455                })
 456            }
 457
 458            Some(ContextPickerMode::Thread) => {
 459                let search_threads_task =
 460                    search_threads(query, cancellation_flag, &self.history_store, cx);
 461                cx.background_spawn(async move {
 462                    search_threads_task
 463                        .await
 464                        .into_iter()
 465                        .map(Match::Thread)
 466                        .collect()
 467                })
 468            }
 469
 470            Some(ContextPickerMode::Fetch) => {
 471                if !query.is_empty() {
 472                    Task::ready(vec![Match::Fetch(query.into())])
 473                } else {
 474                    Task::ready(Vec::new())
 475                }
 476            }
 477
 478            Some(ContextPickerMode::Rules) => {
 479                if let Some(prompt_store) = self.prompt_store.as_ref() {
 480                    let search_rules_task =
 481                        search_rules(query, cancellation_flag, prompt_store, cx);
 482                    cx.background_spawn(async move {
 483                        search_rules_task
 484                            .await
 485                            .into_iter()
 486                            .map(Match::Rules)
 487                            .collect::<Vec<_>>()
 488                    })
 489                } else {
 490                    Task::ready(Vec::new())
 491                }
 492            }
 493
 494            None if query.is_empty() => {
 495                let mut matches = self.recent_context_picker_entries(&workspace, cx);
 496
 497                matches.extend(
 498                    self.available_context_picker_entries(&workspace, cx)
 499                        .into_iter()
 500                        .map(|mode| {
 501                            Match::Entry(EntryMatch {
 502                                entry: mode,
 503                                mat: None,
 504                            })
 505                        }),
 506                );
 507
 508                Task::ready(matches)
 509            }
 510            None => {
 511                let executor = cx.background_executor().clone();
 512
 513                let search_files_task =
 514                    search_files(query.clone(), cancellation_flag, &workspace, cx);
 515
 516                let entries = self.available_context_picker_entries(&workspace, cx);
 517                let entry_candidates = entries
 518                    .iter()
 519                    .enumerate()
 520                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 521                    .collect::<Vec<_>>();
 522
 523                cx.background_spawn(async move {
 524                    let mut matches = search_files_task
 525                        .await
 526                        .into_iter()
 527                        .map(Match::File)
 528                        .collect::<Vec<_>>();
 529
 530                    let entry_matches = fuzzy::match_strings(
 531                        &entry_candidates,
 532                        &query,
 533                        false,
 534                        true,
 535                        100,
 536                        &Arc::new(AtomicBool::default()),
 537                        executor,
 538                    )
 539                    .await;
 540
 541                    matches.extend(entry_matches.into_iter().map(|mat| {
 542                        Match::Entry(EntryMatch {
 543                            entry: entries[mat.candidate_id],
 544                            mat: Some(mat),
 545                        })
 546                    }));
 547
 548                    matches.sort_by(|a, b| {
 549                        b.score()
 550                            .partial_cmp(&a.score())
 551                            .unwrap_or(std::cmp::Ordering::Equal)
 552                    });
 553
 554                    matches
 555                })
 556            }
 557        }
 558    }
 559
 560    fn recent_context_picker_entries(
 561        &self,
 562        workspace: &Entity<Workspace>,
 563        cx: &mut App,
 564    ) -> Vec<Match> {
 565        let mut recent = Vec::with_capacity(6);
 566
 567        let mut mentions = self
 568            .message_editor
 569            .read_with(cx, |message_editor, _cx| message_editor.mentions())
 570            .unwrap_or_default();
 571        let workspace = workspace.read(cx);
 572        let project = workspace.project().read(cx);
 573
 574        if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
 575            && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
 576        {
 577            let thread = thread.read(cx);
 578            mentions.insert(MentionUri::Thread {
 579                id: thread.session_id().clone(),
 580                name: thread.title().into(),
 581            });
 582        }
 583
 584        recent.extend(
 585            workspace
 586                .recent_navigation_history_iter(cx)
 587                .filter(|(_, abs_path)| {
 588                    abs_path.as_ref().is_none_or(|path| {
 589                        !mentions.contains(&MentionUri::File {
 590                            abs_path: path.clone(),
 591                        })
 592                    })
 593                })
 594                .take(4)
 595                .filter_map(|(project_path, _)| {
 596                    project
 597                        .worktree_for_id(project_path.worktree_id, cx)
 598                        .map(|worktree| {
 599                            let path_prefix = worktree.read(cx).root_name().into();
 600                            Match::File(FileMatch {
 601                                mat: fuzzy::PathMatch {
 602                                    score: 1.,
 603                                    positions: Vec::new(),
 604                                    worktree_id: project_path.worktree_id.to_usize(),
 605                                    path: project_path.path,
 606                                    path_prefix,
 607                                    is_dir: false,
 608                                    distance_to_relative_ancestor: 0,
 609                                },
 610                                is_recent: true,
 611                            })
 612                        })
 613                }),
 614        );
 615
 616        if self.prompt_capabilities.borrow().embedded_context {
 617            const RECENT_COUNT: usize = 2;
 618            let threads = self
 619                .history_store
 620                .read(cx)
 621                .recently_opened_entries(cx)
 622                .into_iter()
 623                .filter(|thread| !mentions.contains(&thread.mention_uri()))
 624                .take(RECENT_COUNT)
 625                .collect::<Vec<_>>();
 626
 627            recent.extend(threads.into_iter().map(Match::RecentThread));
 628        }
 629
 630        recent
 631    }
 632
 633    fn available_context_picker_entries(
 634        &self,
 635        workspace: &Entity<Workspace>,
 636        cx: &mut App,
 637    ) -> Vec<ContextPickerEntry> {
 638        let embedded_context = self.prompt_capabilities.borrow().embedded_context;
 639        let mut entries = if embedded_context {
 640            vec![
 641                ContextPickerEntry::Mode(ContextPickerMode::File),
 642                ContextPickerEntry::Mode(ContextPickerMode::Symbol),
 643                ContextPickerEntry::Mode(ContextPickerMode::Thread),
 644            ]
 645        } else {
 646            // File is always available, but we don't need a mode entry
 647            vec![]
 648        };
 649
 650        let has_selection = workspace
 651            .read(cx)
 652            .active_item(cx)
 653            .and_then(|item| item.downcast::<Editor>())
 654            .is_some_and(|editor| {
 655                editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
 656            });
 657        if has_selection {
 658            entries.push(ContextPickerEntry::Action(
 659                ContextPickerAction::AddSelections,
 660            ));
 661        }
 662
 663        if embedded_context {
 664            if self.prompt_store.is_some() {
 665                entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
 666            }
 667
 668            entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
 669        }
 670
 671        entries
 672    }
 673}
 674
 675fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
 676    let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 677    let mut label = CodeLabelBuilder::default();
 678
 679    label.push_str(file_name, None);
 680    label.push_str(" ", None);
 681
 682    if let Some(directory) = directory {
 683        label.push_str(directory, comment_id);
 684    }
 685
 686    label.build()
 687}
 688
 689impl CompletionProvider for ContextPickerCompletionProvider {
 690    fn completions(
 691        &self,
 692        _excerpt_id: ExcerptId,
 693        buffer: &Entity<Buffer>,
 694        buffer_position: Anchor,
 695        _trigger: CompletionContext,
 696        _window: &mut Window,
 697        cx: &mut Context<Editor>,
 698    ) -> Task<Result<Vec<CompletionResponse>>> {
 699        let state = buffer.update(cx, |buffer, _cx| {
 700            let position = buffer_position.to_point(buffer);
 701            let line_start = Point::new(position.row, 0);
 702            let offset_to_line = buffer.point_to_offset(line_start);
 703            let mut lines = buffer.text_for_range(line_start..position).lines();
 704            let line = lines.next()?;
 705            ContextCompletion::try_parse(
 706                line,
 707                offset_to_line,
 708                self.prompt_capabilities.borrow().embedded_context,
 709            )
 710        });
 711        let Some(state) = state else {
 712            return Task::ready(Ok(Vec::new()));
 713        };
 714
 715        let Some(workspace) = self.workspace.upgrade() else {
 716            return Task::ready(Ok(Vec::new()));
 717        };
 718
 719        let project = workspace.read(cx).project().clone();
 720        let snapshot = buffer.read(cx).snapshot();
 721        let source_range = snapshot.anchor_before(state.source_range().start)
 722            ..snapshot.anchor_after(state.source_range().end);
 723
 724        let editor = self.message_editor.clone();
 725
 726        match state {
 727            ContextCompletion::SlashCommand(SlashCommandCompletion {
 728                command, argument, ..
 729            }) => {
 730                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
 731                cx.background_spawn(async move {
 732                    let completions = search_task
 733                        .await
 734                        .into_iter()
 735                        .map(|command| {
 736                            let new_text = if let Some(argument) = argument.as_ref() {
 737                                format!("/{} {}", command.name, argument)
 738                            } else {
 739                                format!("/{} ", command.name)
 740                            };
 741
 742                            let is_missing_argument = argument.is_none() && command.input.is_some();
 743                            Completion {
 744                                replace_range: source_range.clone(),
 745                                new_text,
 746                                label: CodeLabel::plain(command.name.to_string(), None),
 747                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
 748                                    command.description.into(),
 749                                )),
 750                                source: project::CompletionSource::Custom,
 751                                icon_path: None,
 752                                insert_text_mode: None,
 753                                confirm: Some(Arc::new({
 754                                    let editor = editor.clone();
 755                                    move |intent, _window, cx| {
 756                                        if !is_missing_argument {
 757                                            cx.defer({
 758                                                let editor = editor.clone();
 759                                                move |cx| {
 760                                                    editor
 761                                                        .update(cx, |editor, cx| {
 762                                                            match intent {
 763                                                                CompletionIntent::Complete
 764                                                                | CompletionIntent::CompleteWithInsert
 765                                                                | CompletionIntent::CompleteWithReplace => {
 766                                                                    if !is_missing_argument {
 767                                                                        editor.send(cx);
 768                                                                    }
 769                                                                }
 770                                                                CompletionIntent::Compose => {}
 771                                                            }
 772                                                        })
 773                                                        .ok();
 774                                                }
 775                                            });
 776                                        }
 777                                        false
 778                                    }
 779                                })),
 780                            }
 781                        })
 782                        .collect();
 783
 784                    Ok(vec![CompletionResponse {
 785                        completions,
 786                        display_options: CompletionDisplayOptions {
 787                            dynamic_width: true,
 788                        },
 789                        // Since this does its own filtering (see `filter_completions()` returns false),
 790                        // there is no benefit to computing whether this set of completions is incomplete.
 791                        is_incomplete: true,
 792                    }])
 793                })
 794            }
 795            ContextCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
 796                let query = argument.unwrap_or_default();
 797                let search_task =
 798                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
 799
 800                cx.spawn(async move |_, cx| {
 801                    let matches = search_task.await;
 802
 803                    let completions = cx.update(|cx| {
 804                        matches
 805                            .into_iter()
 806                            .filter_map(|mat| match mat {
 807                                Match::File(FileMatch { mat, is_recent }) => {
 808                                    let project_path = ProjectPath {
 809                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
 810                                        path: mat.path.clone(),
 811                                    };
 812
 813                                    Self::completion_for_path(
 814                                        project_path,
 815                                        &mat.path_prefix,
 816                                        is_recent,
 817                                        mat.is_dir,
 818                                        source_range.clone(),
 819                                        editor.clone(),
 820                                        project.clone(),
 821                                        cx,
 822                                    )
 823                                }
 824
 825                                Match::Symbol(SymbolMatch { symbol, .. }) => {
 826                                    Self::completion_for_symbol(
 827                                        symbol,
 828                                        source_range.clone(),
 829                                        editor.clone(),
 830                                        workspace.clone(),
 831                                        cx,
 832                                    )
 833                                }
 834
 835                                Match::Thread(thread) => Some(Self::completion_for_thread(
 836                                    thread,
 837                                    source_range.clone(),
 838                                    false,
 839                                    editor.clone(),
 840                                    cx,
 841                                )),
 842
 843                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
 844                                    thread,
 845                                    source_range.clone(),
 846                                    true,
 847                                    editor.clone(),
 848                                    cx,
 849                                )),
 850
 851                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
 852                                    user_rules,
 853                                    source_range.clone(),
 854                                    editor.clone(),
 855                                    cx,
 856                                )),
 857
 858                                Match::Fetch(url) => Self::completion_for_fetch(
 859                                    source_range.clone(),
 860                                    url,
 861                                    editor.clone(),
 862                                    cx,
 863                                ),
 864
 865                                Match::Entry(EntryMatch { entry, .. }) => {
 866                                    Self::completion_for_entry(
 867                                        entry,
 868                                        source_range.clone(),
 869                                        editor.clone(),
 870                                        &workspace,
 871                                        cx,
 872                                    )
 873                                }
 874                            })
 875                            .collect()
 876                    })?;
 877
 878                    Ok(vec![CompletionResponse {
 879                        completions,
 880                        display_options: CompletionDisplayOptions {
 881                            dynamic_width: true,
 882                        },
 883                        // Since this does its own filtering (see `filter_completions()` returns false),
 884                        // there is no benefit to computing whether this set of completions is incomplete.
 885                        is_incomplete: true,
 886                    }])
 887                })
 888            }
 889        }
 890    }
 891
 892    fn is_completion_trigger(
 893        &self,
 894        buffer: &Entity<language::Buffer>,
 895        position: language::Anchor,
 896        _text: &str,
 897        _trigger_in_words: bool,
 898        _menu_is_open: bool,
 899        cx: &mut Context<Editor>,
 900    ) -> bool {
 901        let buffer = buffer.read(cx);
 902        let position = position.to_point(buffer);
 903        let line_start = Point::new(position.row, 0);
 904        let offset_to_line = buffer.point_to_offset(line_start);
 905        let mut lines = buffer.text_for_range(line_start..position).lines();
 906        if let Some(line) = lines.next() {
 907            ContextCompletion::try_parse(
 908                line,
 909                offset_to_line,
 910                self.prompt_capabilities.borrow().embedded_context,
 911            )
 912            .filter(|completion| {
 913                // Right now we don't support completing arguments of slash commands
 914                let is_slash_command_with_argument = matches!(
 915                    completion,
 916                    ContextCompletion::SlashCommand(SlashCommandCompletion {
 917                        argument: Some(_),
 918                        ..
 919                    })
 920                );
 921                !is_slash_command_with_argument
 922            })
 923            .map(|completion| {
 924                completion.source_range().start <= offset_to_line + position.column as usize
 925                    && completion.source_range().end >= offset_to_line + position.column as usize
 926            })
 927            .unwrap_or(false)
 928        } else {
 929            false
 930        }
 931    }
 932
 933    fn sort_completions(&self) -> bool {
 934        false
 935    }
 936
 937    fn filter_completions(&self) -> bool {
 938        false
 939    }
 940}
 941
 942fn confirm_completion_callback(
 943    crease_text: SharedString,
 944    start: Anchor,
 945    content_len: usize,
 946    message_editor: WeakEntity<MessageEditor>,
 947    mention_uri: MentionUri,
 948) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 949    Arc::new(move |_, window, cx| {
 950        let message_editor = message_editor.clone();
 951        let crease_text = crease_text.clone();
 952        let mention_uri = mention_uri.clone();
 953        window.defer(cx, move |window, cx| {
 954            message_editor
 955                .clone()
 956                .update(cx, |message_editor, cx| {
 957                    message_editor
 958                        .confirm_mention_completion(
 959                            crease_text,
 960                            start,
 961                            content_len,
 962                            mention_uri,
 963                            window,
 964                            cx,
 965                        )
 966                        .detach();
 967                })
 968                .ok();
 969        });
 970        false
 971    })
 972}
 973
 974enum ContextCompletion {
 975    SlashCommand(SlashCommandCompletion),
 976    Mention(MentionCompletion),
 977}
 978
 979impl ContextCompletion {
 980    fn source_range(&self) -> Range<usize> {
 981        match self {
 982            Self::SlashCommand(completion) => completion.source_range.clone(),
 983            Self::Mention(completion) => completion.source_range.clone(),
 984        }
 985    }
 986
 987    fn try_parse(line: &str, offset_to_line: usize, allow_non_file_mentions: bool) -> Option<Self> {
 988        if let Some(command) = SlashCommandCompletion::try_parse(line, offset_to_line) {
 989            Some(Self::SlashCommand(command))
 990        } else if let Some(mention) =
 991            MentionCompletion::try_parse(allow_non_file_mentions, line, offset_to_line)
 992        {
 993            Some(Self::Mention(mention))
 994        } else {
 995            None
 996        }
 997    }
 998}
 999
1000#[derive(Debug, Default, PartialEq)]
1001pub struct SlashCommandCompletion {
1002    pub source_range: Range<usize>,
1003    pub command: Option<String>,
1004    pub argument: Option<String>,
1005}
1006
1007impl SlashCommandCompletion {
1008    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1009        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1010        if !line.starts_with('/') || offset_to_line != 0 {
1011            return None;
1012        }
1013
1014        let (prefix, last_command) = line.rsplit_once('/')?;
1015        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1016            || last_command.starts_with(char::is_whitespace)
1017        {
1018            return None;
1019        }
1020
1021        let mut argument = None;
1022        let mut command = None;
1023        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1024            if !args.is_empty() {
1025                argument = Some(args.trim_end().to_string());
1026            }
1027            command = Some(command_text.to_string());
1028        } else if !last_command.is_empty() {
1029            command = Some(last_command.to_string());
1030        };
1031
1032        Some(Self {
1033            source_range: prefix.len() + offset_to_line
1034                ..line
1035                    .rfind(|c: char| !c.is_whitespace())
1036                    .unwrap_or_else(|| line.len())
1037                    + 1
1038                    + offset_to_line,
1039            command,
1040            argument,
1041        })
1042    }
1043}
1044
1045#[derive(Debug, Default, PartialEq)]
1046struct MentionCompletion {
1047    source_range: Range<usize>,
1048    mode: Option<ContextPickerMode>,
1049    argument: Option<String>,
1050}
1051
1052impl MentionCompletion {
1053    fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
1054        let last_mention_start = line.rfind('@')?;
1055
1056        // No whitespace immediately after '@'
1057        if line[last_mention_start + 1..]
1058            .chars()
1059            .next()
1060            .is_some_and(|c| c.is_whitespace())
1061        {
1062            return None;
1063        }
1064
1065        //  Must be a word boundary before '@'
1066        if last_mention_start > 0
1067            && line[..last_mention_start]
1068                .chars()
1069                .last()
1070                .is_some_and(|c| !c.is_whitespace())
1071        {
1072            return None;
1073        }
1074
1075        let rest_of_line = &line[last_mention_start + 1..];
1076
1077        let mut mode = None;
1078        let mut argument = None;
1079
1080        let mut parts = rest_of_line.split_whitespace();
1081        let mut end = last_mention_start + 1;
1082
1083        if let Some(mode_text) = parts.next() {
1084            // Safe since we check no leading whitespace above
1085            end += mode_text.len();
1086
1087            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
1088                && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
1089            {
1090                mode = Some(parsed_mode);
1091            } else {
1092                argument = Some(mode_text.to_string());
1093            }
1094            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1095                Some(whitespace_count) => {
1096                    if let Some(argument_text) = parts.next() {
1097                        // If mode wasn't recognized but we have an argument, don't suggest completions
1098                        // (e.g. '@something word')
1099                        if mode.is_none() && !argument_text.is_empty() {
1100                            return None;
1101                        }
1102
1103                        argument = Some(argument_text.to_string());
1104                        end += whitespace_count + argument_text.len();
1105                    }
1106                }
1107                None => {
1108                    // Rest of line is entirely whitespace
1109                    end += rest_of_line.len() - mode_text.len();
1110                }
1111            }
1112        }
1113
1114        Some(Self {
1115            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1116            mode,
1117            argument,
1118        })
1119    }
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124    use super::*;
1125
1126    #[test]
1127    fn test_slash_command_completion_parse() {
1128        assert_eq!(
1129            SlashCommandCompletion::try_parse("/", 0),
1130            Some(SlashCommandCompletion {
1131                source_range: 0..1,
1132                command: None,
1133                argument: None,
1134            })
1135        );
1136
1137        assert_eq!(
1138            SlashCommandCompletion::try_parse("/help", 0),
1139            Some(SlashCommandCompletion {
1140                source_range: 0..5,
1141                command: Some("help".to_string()),
1142                argument: None,
1143            })
1144        );
1145
1146        assert_eq!(
1147            SlashCommandCompletion::try_parse("/help ", 0),
1148            Some(SlashCommandCompletion {
1149                source_range: 0..5,
1150                command: Some("help".to_string()),
1151                argument: None,
1152            })
1153        );
1154
1155        assert_eq!(
1156            SlashCommandCompletion::try_parse("/help arg1", 0),
1157            Some(SlashCommandCompletion {
1158                source_range: 0..10,
1159                command: Some("help".to_string()),
1160                argument: Some("arg1".to_string()),
1161            })
1162        );
1163
1164        assert_eq!(
1165            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1166            Some(SlashCommandCompletion {
1167                source_range: 0..15,
1168                command: Some("help".to_string()),
1169                argument: Some("arg1 arg2".to_string()),
1170            })
1171        );
1172
1173        assert_eq!(
1174            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1175            Some(SlashCommandCompletion {
1176                source_range: 0..30,
1177                command: Some("拿不到命令".to_string()),
1178                argument: Some("拿不到命令".to_string()),
1179            })
1180        );
1181
1182        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1183
1184        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1185
1186        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1187
1188        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1189
1190        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1191    }
1192
1193    #[test]
1194    fn test_mention_completion_parse() {
1195        assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
1196
1197        assert_eq!(
1198            MentionCompletion::try_parse(true, "Lorem @", 0),
1199            Some(MentionCompletion {
1200                source_range: 6..7,
1201                mode: None,
1202                argument: None,
1203            })
1204        );
1205
1206        assert_eq!(
1207            MentionCompletion::try_parse(true, "Lorem @file", 0),
1208            Some(MentionCompletion {
1209                source_range: 6..11,
1210                mode: Some(ContextPickerMode::File),
1211                argument: None,
1212            })
1213        );
1214
1215        assert_eq!(
1216            MentionCompletion::try_parse(true, "Lorem @file ", 0),
1217            Some(MentionCompletion {
1218                source_range: 6..12,
1219                mode: Some(ContextPickerMode::File),
1220                argument: None,
1221            })
1222        );
1223
1224        assert_eq!(
1225            MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
1226            Some(MentionCompletion {
1227                source_range: 6..19,
1228                mode: Some(ContextPickerMode::File),
1229                argument: Some("main.rs".to_string()),
1230            })
1231        );
1232
1233        assert_eq!(
1234            MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
1235            Some(MentionCompletion {
1236                source_range: 6..19,
1237                mode: Some(ContextPickerMode::File),
1238                argument: Some("main.rs".to_string()),
1239            })
1240        );
1241
1242        assert_eq!(
1243            MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
1244            Some(MentionCompletion {
1245                source_range: 6..19,
1246                mode: Some(ContextPickerMode::File),
1247                argument: Some("main.rs".to_string()),
1248            })
1249        );
1250
1251        assert_eq!(
1252            MentionCompletion::try_parse(true, "Lorem @main", 0),
1253            Some(MentionCompletion {
1254                source_range: 6..11,
1255                mode: None,
1256                argument: Some("main".to_string()),
1257            })
1258        );
1259
1260        assert_eq!(
1261            MentionCompletion::try_parse(true, "Lorem @main ", 0),
1262            Some(MentionCompletion {
1263                source_range: 6..12,
1264                mode: None,
1265                argument: Some("main".to_string()),
1266            })
1267        );
1268
1269        assert_eq!(MentionCompletion::try_parse(true, "Lorem @main m", 0), None);
1270
1271        assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
1272
1273        // Allowed non-file mentions
1274
1275        assert_eq!(
1276            MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
1277            Some(MentionCompletion {
1278                source_range: 6..18,
1279                mode: Some(ContextPickerMode::Symbol),
1280                argument: Some("main".to_string()),
1281            })
1282        );
1283
1284        // Disallowed non-file mentions
1285        assert_eq!(
1286            MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1287            None
1288        );
1289
1290        assert_eq!(
1291            MentionCompletion::try_parse(true, "Lorem@symbol", 0),
1292            None,
1293            "Should not parse mention inside word"
1294        );
1295
1296        assert_eq!(
1297            MentionCompletion::try_parse(true, "Lorem @ file", 0),
1298            None,
1299            "Should not parse with a space after @"
1300        );
1301
1302        assert_eq!(
1303            MentionCompletion::try_parse(true, "@ file", 0),
1304            None,
1305            "Should not parse with a space after @ at the start of the line"
1306        );
1307    }
1308}