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 const 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| {
 656                    editor.has_non_empty_selection(&editor.display_snapshot(cx))
 657                })
 658            });
 659        if has_selection {
 660            entries.push(ContextPickerEntry::Action(
 661                ContextPickerAction::AddSelections,
 662            ));
 663        }
 664
 665        if embedded_context {
 666            if self.prompt_store.is_some() {
 667                entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
 668            }
 669
 670            entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
 671        }
 672
 673        entries
 674    }
 675}
 676
 677fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
 678    let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 679    let mut label = CodeLabelBuilder::default();
 680
 681    label.push_str(file_name, None);
 682    label.push_str(" ", None);
 683
 684    if let Some(directory) = directory {
 685        label.push_str(directory, comment_id);
 686    }
 687
 688    label.build()
 689}
 690
 691impl CompletionProvider for ContextPickerCompletionProvider {
 692    fn completions(
 693        &self,
 694        _excerpt_id: ExcerptId,
 695        buffer: &Entity<Buffer>,
 696        buffer_position: Anchor,
 697        _trigger: CompletionContext,
 698        _window: &mut Window,
 699        cx: &mut Context<Editor>,
 700    ) -> Task<Result<Vec<CompletionResponse>>> {
 701        let state = buffer.update(cx, |buffer, _cx| {
 702            let position = buffer_position.to_point(buffer);
 703            let line_start = Point::new(position.row, 0);
 704            let offset_to_line = buffer.point_to_offset(line_start);
 705            let mut lines = buffer.text_for_range(line_start..position).lines();
 706            let line = lines.next()?;
 707            ContextCompletion::try_parse(
 708                line,
 709                offset_to_line,
 710                self.prompt_capabilities.borrow().embedded_context,
 711            )
 712        });
 713        let Some(state) = state else {
 714            return Task::ready(Ok(Vec::new()));
 715        };
 716
 717        let Some(workspace) = self.workspace.upgrade() else {
 718            return Task::ready(Ok(Vec::new()));
 719        };
 720
 721        let project = workspace.read(cx).project().clone();
 722        let snapshot = buffer.read(cx).snapshot();
 723        let source_range = snapshot.anchor_before(state.source_range().start)
 724            ..snapshot.anchor_after(state.source_range().end);
 725
 726        let editor = self.message_editor.clone();
 727
 728        match state {
 729            ContextCompletion::SlashCommand(SlashCommandCompletion {
 730                command, argument, ..
 731            }) => {
 732                let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
 733                cx.background_spawn(async move {
 734                    let completions = search_task
 735                        .await
 736                        .into_iter()
 737                        .map(|command| {
 738                            let new_text = if let Some(argument) = argument.as_ref() {
 739                                format!("/{} {}", command.name, argument)
 740                            } else {
 741                                format!("/{} ", command.name)
 742                            };
 743
 744                            let is_missing_argument = argument.is_none() && command.input.is_some();
 745                            Completion {
 746                                replace_range: source_range.clone(),
 747                                new_text,
 748                                label: CodeLabel::plain(command.name.to_string(), None),
 749                                documentation: Some(CompletionDocumentation::MultiLinePlainText(
 750                                    command.description.into(),
 751                                )),
 752                                source: project::CompletionSource::Custom,
 753                                icon_path: None,
 754                                insert_text_mode: None,
 755                                confirm: Some(Arc::new({
 756                                    let editor = editor.clone();
 757                                    move |intent, _window, cx| {
 758                                        if !is_missing_argument {
 759                                            cx.defer({
 760                                                let editor = editor.clone();
 761                                                move |cx| {
 762                                                    editor
 763                                                        .update(cx, |editor, cx| {
 764                                                            match intent {
 765                                                                CompletionIntent::Complete
 766                                                                | CompletionIntent::CompleteWithInsert
 767                                                                | CompletionIntent::CompleteWithReplace => {
 768                                                                    if !is_missing_argument {
 769                                                                        editor.send(cx);
 770                                                                    }
 771                                                                }
 772                                                                CompletionIntent::Compose => {}
 773                                                            }
 774                                                        })
 775                                                        .ok();
 776                                                }
 777                                            });
 778                                        }
 779                                        false
 780                                    }
 781                                })),
 782                            }
 783                        })
 784                        .collect();
 785
 786                    Ok(vec![CompletionResponse {
 787                        completions,
 788                        display_options: CompletionDisplayOptions {
 789                            dynamic_width: true,
 790                        },
 791                        // Since this does its own filtering (see `filter_completions()` returns false),
 792                        // there is no benefit to computing whether this set of completions is incomplete.
 793                        is_incomplete: true,
 794                    }])
 795                })
 796            }
 797            ContextCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
 798                let query = argument.unwrap_or_default();
 799                let search_task =
 800                    self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
 801
 802                cx.spawn(async move |_, cx| {
 803                    let matches = search_task.await;
 804
 805                    let completions = cx.update(|cx| {
 806                        matches
 807                            .into_iter()
 808                            .filter_map(|mat| match mat {
 809                                Match::File(FileMatch { mat, is_recent }) => {
 810                                    let project_path = ProjectPath {
 811                                        worktree_id: WorktreeId::from_usize(mat.worktree_id),
 812                                        path: mat.path.clone(),
 813                                    };
 814
 815                                    Self::completion_for_path(
 816                                        project_path,
 817                                        &mat.path_prefix,
 818                                        is_recent,
 819                                        mat.is_dir,
 820                                        source_range.clone(),
 821                                        editor.clone(),
 822                                        project.clone(),
 823                                        cx,
 824                                    )
 825                                }
 826
 827                                Match::Symbol(SymbolMatch { symbol, .. }) => {
 828                                    Self::completion_for_symbol(
 829                                        symbol,
 830                                        source_range.clone(),
 831                                        editor.clone(),
 832                                        workspace.clone(),
 833                                        cx,
 834                                    )
 835                                }
 836
 837                                Match::Thread(thread) => Some(Self::completion_for_thread(
 838                                    thread,
 839                                    source_range.clone(),
 840                                    false,
 841                                    editor.clone(),
 842                                    cx,
 843                                )),
 844
 845                                Match::RecentThread(thread) => Some(Self::completion_for_thread(
 846                                    thread,
 847                                    source_range.clone(),
 848                                    true,
 849                                    editor.clone(),
 850                                    cx,
 851                                )),
 852
 853                                Match::Rules(user_rules) => Some(Self::completion_for_rules(
 854                                    user_rules,
 855                                    source_range.clone(),
 856                                    editor.clone(),
 857                                    cx,
 858                                )),
 859
 860                                Match::Fetch(url) => Self::completion_for_fetch(
 861                                    source_range.clone(),
 862                                    url,
 863                                    editor.clone(),
 864                                    cx,
 865                                ),
 866
 867                                Match::Entry(EntryMatch { entry, .. }) => {
 868                                    Self::completion_for_entry(
 869                                        entry,
 870                                        source_range.clone(),
 871                                        editor.clone(),
 872                                        &workspace,
 873                                        cx,
 874                                    )
 875                                }
 876                            })
 877                            .collect()
 878                    })?;
 879
 880                    Ok(vec![CompletionResponse {
 881                        completions,
 882                        display_options: CompletionDisplayOptions {
 883                            dynamic_width: true,
 884                        },
 885                        // Since this does its own filtering (see `filter_completions()` returns false),
 886                        // there is no benefit to computing whether this set of completions is incomplete.
 887                        is_incomplete: true,
 888                    }])
 889                })
 890            }
 891        }
 892    }
 893
 894    fn is_completion_trigger(
 895        &self,
 896        buffer: &Entity<language::Buffer>,
 897        position: language::Anchor,
 898        _text: &str,
 899        _trigger_in_words: bool,
 900        _menu_is_open: bool,
 901        cx: &mut Context<Editor>,
 902    ) -> bool {
 903        let buffer = buffer.read(cx);
 904        let position = position.to_point(buffer);
 905        let line_start = Point::new(position.row, 0);
 906        let offset_to_line = buffer.point_to_offset(line_start);
 907        let mut lines = buffer.text_for_range(line_start..position).lines();
 908        if let Some(line) = lines.next() {
 909            ContextCompletion::try_parse(
 910                line,
 911                offset_to_line,
 912                self.prompt_capabilities.borrow().embedded_context,
 913            )
 914            .filter(|completion| {
 915                // Right now we don't support completing arguments of slash commands
 916                let is_slash_command_with_argument = matches!(
 917                    completion,
 918                    ContextCompletion::SlashCommand(SlashCommandCompletion {
 919                        argument: Some(_),
 920                        ..
 921                    })
 922                );
 923                !is_slash_command_with_argument
 924            })
 925            .map(|completion| {
 926                completion.source_range().start <= offset_to_line + position.column as usize
 927                    && completion.source_range().end >= offset_to_line + position.column as usize
 928            })
 929            .unwrap_or(false)
 930        } else {
 931            false
 932        }
 933    }
 934
 935    fn sort_completions(&self) -> bool {
 936        false
 937    }
 938
 939    fn filter_completions(&self) -> bool {
 940        false
 941    }
 942}
 943
 944fn confirm_completion_callback(
 945    crease_text: SharedString,
 946    start: Anchor,
 947    content_len: usize,
 948    message_editor: WeakEntity<MessageEditor>,
 949    mention_uri: MentionUri,
 950) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 951    Arc::new(move |_, window, cx| {
 952        let message_editor = message_editor.clone();
 953        let crease_text = crease_text.clone();
 954        let mention_uri = mention_uri.clone();
 955        window.defer(cx, move |window, cx| {
 956            message_editor
 957                .clone()
 958                .update(cx, |message_editor, cx| {
 959                    message_editor
 960                        .confirm_mention_completion(
 961                            crease_text,
 962                            start,
 963                            content_len,
 964                            mention_uri,
 965                            window,
 966                            cx,
 967                        )
 968                        .detach();
 969                })
 970                .ok();
 971        });
 972        false
 973    })
 974}
 975
 976enum ContextCompletion {
 977    SlashCommand(SlashCommandCompletion),
 978    Mention(MentionCompletion),
 979}
 980
 981impl ContextCompletion {
 982    fn source_range(&self) -> Range<usize> {
 983        match self {
 984            Self::SlashCommand(completion) => completion.source_range.clone(),
 985            Self::Mention(completion) => completion.source_range.clone(),
 986        }
 987    }
 988
 989    fn try_parse(line: &str, offset_to_line: usize, allow_non_file_mentions: bool) -> Option<Self> {
 990        if let Some(command) = SlashCommandCompletion::try_parse(line, offset_to_line) {
 991            Some(Self::SlashCommand(command))
 992        } else if let Some(mention) =
 993            MentionCompletion::try_parse(allow_non_file_mentions, line, offset_to_line)
 994        {
 995            Some(Self::Mention(mention))
 996        } else {
 997            None
 998        }
 999    }
1000}
1001
1002#[derive(Debug, Default, PartialEq)]
1003pub struct SlashCommandCompletion {
1004    pub source_range: Range<usize>,
1005    pub command: Option<String>,
1006    pub argument: Option<String>,
1007}
1008
1009impl SlashCommandCompletion {
1010    pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1011        // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1012        if !line.starts_with('/') || offset_to_line != 0 {
1013            return None;
1014        }
1015
1016        let (prefix, last_command) = line.rsplit_once('/')?;
1017        if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1018            || last_command.starts_with(char::is_whitespace)
1019        {
1020            return None;
1021        }
1022
1023        let mut argument = None;
1024        let mut command = None;
1025        if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1026            if !args.is_empty() {
1027                argument = Some(args.trim_end().to_string());
1028            }
1029            command = Some(command_text.to_string());
1030        } else if !last_command.is_empty() {
1031            command = Some(last_command.to_string());
1032        };
1033
1034        Some(Self {
1035            source_range: prefix.len() + offset_to_line
1036                ..line
1037                    .rfind(|c: char| !c.is_whitespace())
1038                    .unwrap_or_else(|| line.len())
1039                    + 1
1040                    + offset_to_line,
1041            command,
1042            argument,
1043        })
1044    }
1045}
1046
1047#[derive(Debug, Default, PartialEq)]
1048struct MentionCompletion {
1049    source_range: Range<usize>,
1050    mode: Option<ContextPickerMode>,
1051    argument: Option<String>,
1052}
1053
1054impl MentionCompletion {
1055    fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
1056        let last_mention_start = line.rfind('@')?;
1057
1058        // No whitespace immediately after '@'
1059        if line[last_mention_start + 1..]
1060            .chars()
1061            .next()
1062            .is_some_and(|c| c.is_whitespace())
1063        {
1064            return None;
1065        }
1066
1067        //  Must be a word boundary before '@'
1068        if last_mention_start > 0
1069            && line[..last_mention_start]
1070                .chars()
1071                .last()
1072                .is_some_and(|c| !c.is_whitespace())
1073        {
1074            return None;
1075        }
1076
1077        let rest_of_line = &line[last_mention_start + 1..];
1078
1079        let mut mode = None;
1080        let mut argument = None;
1081
1082        let mut parts = rest_of_line.split_whitespace();
1083        let mut end = last_mention_start + 1;
1084
1085        if let Some(mode_text) = parts.next() {
1086            // Safe since we check no leading whitespace above
1087            end += mode_text.len();
1088
1089            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
1090                && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
1091            {
1092                mode = Some(parsed_mode);
1093            } else {
1094                argument = Some(mode_text.to_string());
1095            }
1096            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1097                Some(whitespace_count) => {
1098                    if let Some(argument_text) = parts.next() {
1099                        // If mode wasn't recognized but we have an argument, don't suggest completions
1100                        // (e.g. '@something word')
1101                        if mode.is_none() && !argument_text.is_empty() {
1102                            return None;
1103                        }
1104
1105                        argument = Some(argument_text.to_string());
1106                        end += whitespace_count + argument_text.len();
1107                    }
1108                }
1109                None => {
1110                    // Rest of line is entirely whitespace
1111                    end += rest_of_line.len() - mode_text.len();
1112                }
1113            }
1114        }
1115
1116        Some(Self {
1117            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1118            mode,
1119            argument,
1120        })
1121    }
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126    use super::*;
1127
1128    #[test]
1129    fn test_slash_command_completion_parse() {
1130        assert_eq!(
1131            SlashCommandCompletion::try_parse("/", 0),
1132            Some(SlashCommandCompletion {
1133                source_range: 0..1,
1134                command: None,
1135                argument: None,
1136            })
1137        );
1138
1139        assert_eq!(
1140            SlashCommandCompletion::try_parse("/help", 0),
1141            Some(SlashCommandCompletion {
1142                source_range: 0..5,
1143                command: Some("help".to_string()),
1144                argument: None,
1145            })
1146        );
1147
1148        assert_eq!(
1149            SlashCommandCompletion::try_parse("/help ", 0),
1150            Some(SlashCommandCompletion {
1151                source_range: 0..5,
1152                command: Some("help".to_string()),
1153                argument: None,
1154            })
1155        );
1156
1157        assert_eq!(
1158            SlashCommandCompletion::try_parse("/help arg1", 0),
1159            Some(SlashCommandCompletion {
1160                source_range: 0..10,
1161                command: Some("help".to_string()),
1162                argument: Some("arg1".to_string()),
1163            })
1164        );
1165
1166        assert_eq!(
1167            SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1168            Some(SlashCommandCompletion {
1169                source_range: 0..15,
1170                command: Some("help".to_string()),
1171                argument: Some("arg1 arg2".to_string()),
1172            })
1173        );
1174
1175        assert_eq!(
1176            SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1177            Some(SlashCommandCompletion {
1178                source_range: 0..30,
1179                command: Some("拿不到命令".to_string()),
1180                argument: Some("拿不到命令".to_string()),
1181            })
1182        );
1183
1184        assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1185
1186        assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1187
1188        assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1189
1190        assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1191
1192        assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1193    }
1194
1195    #[test]
1196    fn test_mention_completion_parse() {
1197        assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
1198
1199        assert_eq!(
1200            MentionCompletion::try_parse(true, "Lorem @", 0),
1201            Some(MentionCompletion {
1202                source_range: 6..7,
1203                mode: None,
1204                argument: None,
1205            })
1206        );
1207
1208        assert_eq!(
1209            MentionCompletion::try_parse(true, "Lorem @file", 0),
1210            Some(MentionCompletion {
1211                source_range: 6..11,
1212                mode: Some(ContextPickerMode::File),
1213                argument: None,
1214            })
1215        );
1216
1217        assert_eq!(
1218            MentionCompletion::try_parse(true, "Lorem @file ", 0),
1219            Some(MentionCompletion {
1220                source_range: 6..12,
1221                mode: Some(ContextPickerMode::File),
1222                argument: None,
1223            })
1224        );
1225
1226        assert_eq!(
1227            MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
1228            Some(MentionCompletion {
1229                source_range: 6..19,
1230                mode: Some(ContextPickerMode::File),
1231                argument: Some("main.rs".to_string()),
1232            })
1233        );
1234
1235        assert_eq!(
1236            MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
1237            Some(MentionCompletion {
1238                source_range: 6..19,
1239                mode: Some(ContextPickerMode::File),
1240                argument: Some("main.rs".to_string()),
1241            })
1242        );
1243
1244        assert_eq!(
1245            MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
1246            Some(MentionCompletion {
1247                source_range: 6..19,
1248                mode: Some(ContextPickerMode::File),
1249                argument: Some("main.rs".to_string()),
1250            })
1251        );
1252
1253        assert_eq!(
1254            MentionCompletion::try_parse(true, "Lorem @main", 0),
1255            Some(MentionCompletion {
1256                source_range: 6..11,
1257                mode: None,
1258                argument: Some("main".to_string()),
1259            })
1260        );
1261
1262        assert_eq!(
1263            MentionCompletion::try_parse(true, "Lorem @main ", 0),
1264            Some(MentionCompletion {
1265                source_range: 6..12,
1266                mode: None,
1267                argument: Some("main".to_string()),
1268            })
1269        );
1270
1271        assert_eq!(MentionCompletion::try_parse(true, "Lorem @main m", 0), None);
1272
1273        assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
1274
1275        // Allowed non-file mentions
1276
1277        assert_eq!(
1278            MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
1279            Some(MentionCompletion {
1280                source_range: 6..18,
1281                mode: Some(ContextPickerMode::Symbol),
1282                argument: Some("main".to_string()),
1283            })
1284        );
1285
1286        // Disallowed non-file mentions
1287        assert_eq!(
1288            MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1289            None
1290        );
1291
1292        assert_eq!(
1293            MentionCompletion::try_parse(true, "Lorem@symbol", 0),
1294            None,
1295            "Should not parse mention inside word"
1296        );
1297
1298        assert_eq!(
1299            MentionCompletion::try_parse(true, "Lorem @ file", 0),
1300            None,
1301            "Should not parse with a space after @"
1302        );
1303
1304        assert_eq!(
1305            MentionCompletion::try_parse(true, "@ file", 0),
1306            None,
1307            "Should not parse with a space after @ at the start of the line"
1308        );
1309    }
1310}