completion_provider.rs

   1use std::cell::RefCell;
   2use std::ops::Range;
   3use std::path::{Path, PathBuf};
   4use std::rc::Rc;
   5use std::sync::Arc;
   6use std::sync::atomic::AtomicBool;
   7
   8use anyhow::Result;
   9use editor::{CompletionProvider, Editor, ExcerptId, ToOffset as _};
  10use file_icons::FileIcons;
  11use fuzzy::{StringMatch, StringMatchCandidate};
  12use gpui::{App, Entity, Task, WeakEntity};
  13use http_client::HttpClientWithUrl;
  14use itertools::Itertools;
  15use language::{Buffer, CodeLabel, HighlightId};
  16use lsp::CompletionContext;
  17use project::{Completion, CompletionIntent, CompletionResponse, ProjectPath, Symbol, WorktreeId};
  18use prompt_store::PromptStore;
  19use rope::Point;
  20use text::{Anchor, OffsetRangeExt, ToPoint};
  21use ui::prelude::*;
  22use util::ResultExt as _;
  23use workspace::Workspace;
  24
  25use crate::Thread;
  26use crate::context::{AgentContextHandle, AgentContextKey, ContextCreasesAddon, RULES_ICON};
  27use crate::context_store::ContextStore;
  28use crate::thread_store::{TextThreadStore, ThreadStore};
  29
  30use super::fetch_context_picker::fetch_url_content;
  31use super::file_context_picker::{FileMatch, search_files};
  32use super::rules_context_picker::{RulesContextEntry, search_rules};
  33use super::symbol_context_picker::SymbolMatch;
  34use super::symbol_context_picker::search_symbols;
  35use super::thread_context_picker::{ThreadContextEntry, ThreadMatch, search_threads};
  36use super::{
  37    ContextPickerAction, ContextPickerEntry, ContextPickerMode, MentionLink, RecentEntry,
  38    available_context_picker_entries, recent_context_picker_entries, selection_ranges,
  39};
  40
  41pub(crate) enum Match {
  42    File(FileMatch),
  43    Symbol(SymbolMatch),
  44    Thread(ThreadMatch),
  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::Symbol(_) => 1.,
  62            Match::Fetch(_) => 1.,
  63            Match::Rules(_) => 1.,
  64        }
  65    }
  66}
  67
  68fn search(
  69    mode: Option<ContextPickerMode>,
  70    query: String,
  71    cancellation_flag: Arc<AtomicBool>,
  72    recent_entries: Vec<RecentEntry>,
  73    prompt_store: Option<Entity<PromptStore>>,
  74    thread_store: Option<WeakEntity<ThreadStore>>,
  75    text_thread_context_store: Option<WeakEntity<assistant_context_editor::ContextStore>>,
  76    workspace: Entity<Workspace>,
  77    cx: &mut App,
  78) -> Task<Vec<Match>> {
  79    match mode {
  80        Some(ContextPickerMode::File) => {
  81            let search_files_task =
  82                search_files(query.clone(), cancellation_flag.clone(), &workspace, cx);
  83            cx.background_spawn(async move {
  84                search_files_task
  85                    .await
  86                    .into_iter()
  87                    .map(Match::File)
  88                    .collect()
  89            })
  90        }
  91
  92        Some(ContextPickerMode::Symbol) => {
  93            let search_symbols_task =
  94                search_symbols(query.clone(), cancellation_flag.clone(), &workspace, cx);
  95            cx.background_spawn(async move {
  96                search_symbols_task
  97                    .await
  98                    .into_iter()
  99                    .map(Match::Symbol)
 100                    .collect()
 101            })
 102        }
 103
 104        Some(ContextPickerMode::Thread) => {
 105            if let Some((thread_store, context_store)) = thread_store
 106                .as_ref()
 107                .and_then(|t| t.upgrade())
 108                .zip(text_thread_context_store.as_ref().and_then(|t| t.upgrade()))
 109            {
 110                let search_threads_task = search_threads(
 111                    query.clone(),
 112                    cancellation_flag.clone(),
 113                    thread_store,
 114                    context_store,
 115                    cx,
 116                );
 117                cx.background_spawn(async move {
 118                    search_threads_task
 119                        .await
 120                        .into_iter()
 121                        .map(Match::Thread)
 122                        .collect()
 123                })
 124            } else {
 125                Task::ready(Vec::new())
 126            }
 127        }
 128
 129        Some(ContextPickerMode::Fetch) => {
 130            if !query.is_empty() {
 131                Task::ready(vec![Match::Fetch(query.into())])
 132            } else {
 133                Task::ready(Vec::new())
 134            }
 135        }
 136
 137        Some(ContextPickerMode::Rules) => {
 138            if let Some(prompt_store) = prompt_store.as_ref() {
 139                let search_rules_task =
 140                    search_rules(query.clone(), cancellation_flag.clone(), prompt_store, cx);
 141                cx.background_spawn(async move {
 142                    search_rules_task
 143                        .await
 144                        .into_iter()
 145                        .map(Match::Rules)
 146                        .collect::<Vec<_>>()
 147                })
 148            } else {
 149                Task::ready(Vec::new())
 150            }
 151        }
 152
 153        None => {
 154            if query.is_empty() {
 155                let mut matches = recent_entries
 156                    .into_iter()
 157                    .map(|entry| match entry {
 158                        super::RecentEntry::File {
 159                            project_path,
 160                            path_prefix,
 161                        } => Match::File(FileMatch {
 162                            mat: fuzzy::PathMatch {
 163                                score: 1.,
 164                                positions: Vec::new(),
 165                                worktree_id: project_path.worktree_id.to_usize(),
 166                                path: project_path.path,
 167                                path_prefix,
 168                                is_dir: false,
 169                                distance_to_relative_ancestor: 0,
 170                            },
 171                            is_recent: true,
 172                        }),
 173                        super::RecentEntry::Thread(thread_context_entry) => {
 174                            Match::Thread(ThreadMatch {
 175                                thread: thread_context_entry,
 176                                is_recent: true,
 177                            })
 178                        }
 179                    })
 180                    .collect::<Vec<_>>();
 181
 182                matches.extend(
 183                    available_context_picker_entries(&prompt_store, &thread_store, &workspace, cx)
 184                        .into_iter()
 185                        .map(|mode| {
 186                            Match::Entry(EntryMatch {
 187                                entry: mode,
 188                                mat: None,
 189                            })
 190                        }),
 191                );
 192
 193                Task::ready(matches)
 194            } else {
 195                let executor = cx.background_executor().clone();
 196
 197                let search_files_task =
 198                    search_files(query.clone(), cancellation_flag.clone(), &workspace, cx);
 199
 200                let entries =
 201                    available_context_picker_entries(&prompt_store, &thread_store, &workspace, cx);
 202                let entry_candidates = entries
 203                    .iter()
 204                    .enumerate()
 205                    .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
 206                    .collect::<Vec<_>>();
 207
 208                cx.background_spawn(async move {
 209                    let mut matches = search_files_task
 210                        .await
 211                        .into_iter()
 212                        .map(Match::File)
 213                        .collect::<Vec<_>>();
 214
 215                    let entry_matches = fuzzy::match_strings(
 216                        &entry_candidates,
 217                        &query,
 218                        false,
 219                        100,
 220                        &Arc::new(AtomicBool::default()),
 221                        executor,
 222                    )
 223                    .await;
 224
 225                    matches.extend(entry_matches.into_iter().map(|mat| {
 226                        Match::Entry(EntryMatch {
 227                            entry: entries[mat.candidate_id],
 228                            mat: Some(mat),
 229                        })
 230                    }));
 231
 232                    matches.sort_by(|a, b| {
 233                        b.score()
 234                            .partial_cmp(&a.score())
 235                            .unwrap_or(std::cmp::Ordering::Equal)
 236                    });
 237
 238                    matches
 239                })
 240            }
 241        }
 242    }
 243}
 244
 245pub struct ContextPickerCompletionProvider {
 246    workspace: WeakEntity<Workspace>,
 247    context_store: WeakEntity<ContextStore>,
 248    thread_store: Option<WeakEntity<ThreadStore>>,
 249    text_thread_store: Option<WeakEntity<TextThreadStore>>,
 250    editor: WeakEntity<Editor>,
 251    excluded_buffer: Option<WeakEntity<Buffer>>,
 252}
 253
 254impl ContextPickerCompletionProvider {
 255    pub fn new(
 256        workspace: WeakEntity<Workspace>,
 257        context_store: WeakEntity<ContextStore>,
 258        thread_store: Option<WeakEntity<ThreadStore>>,
 259        text_thread_store: Option<WeakEntity<TextThreadStore>>,
 260        editor: WeakEntity<Editor>,
 261        exclude_buffer: Option<WeakEntity<Buffer>>,
 262    ) -> Self {
 263        Self {
 264            workspace,
 265            context_store,
 266            thread_store,
 267            text_thread_store,
 268            editor,
 269            excluded_buffer: exclude_buffer,
 270        }
 271    }
 272
 273    fn completion_for_entry(
 274        entry: ContextPickerEntry,
 275        excerpt_id: ExcerptId,
 276        source_range: Range<Anchor>,
 277        editor: Entity<Editor>,
 278        context_store: Entity<ContextStore>,
 279        workspace: &Entity<Workspace>,
 280        cx: &mut App,
 281    ) -> Option<Completion> {
 282        match entry {
 283            ContextPickerEntry::Mode(mode) => Some(Completion {
 284                replace_range: source_range.clone(),
 285                new_text: format!("@{} ", mode.keyword()),
 286                label: CodeLabel::plain(mode.label().to_string(), None),
 287                icon_path: Some(mode.icon().path().into()),
 288                documentation: None,
 289                source: project::CompletionSource::Custom,
 290                insert_text_mode: None,
 291                // This ensures that when a user accepts this completion, the
 292                // completion menu will still be shown after "@category " is
 293                // inserted
 294                confirm: Some(Arc::new(|_, _, _| true)),
 295            }),
 296            ContextPickerEntry::Action(action) => {
 297                let (new_text, on_action) = match action {
 298                    ContextPickerAction::AddSelections => {
 299                        let selections = selection_ranges(workspace, cx);
 300
 301                        let selection_infos = selections
 302                            .iter()
 303                            .map(|(buffer, range)| {
 304                                let full_path = buffer
 305                                    .read(cx)
 306                                    .file()
 307                                    .map(|file| file.full_path(cx))
 308                                    .unwrap_or_else(|| PathBuf::from("untitled"));
 309                                let file_name = full_path
 310                                    .file_name()
 311                                    .unwrap_or_default()
 312                                    .to_string_lossy()
 313                                    .to_string();
 314                                let line_range = range.to_point(&buffer.read(cx).snapshot());
 315
 316                                let link = MentionLink::for_selection(
 317                                    &file_name,
 318                                    &full_path.to_string_lossy(),
 319                                    line_range.start.row as usize..line_range.end.row as usize,
 320                                );
 321                                (file_name, link, line_range)
 322                            })
 323                            .collect::<Vec<_>>();
 324
 325                        let new_text = format!(
 326                            "{} ",
 327                            selection_infos.iter().map(|(_, link, _)| link).join(" ")
 328                        );
 329
 330                        let callback = Arc::new({
 331                            let context_store = context_store.clone();
 332                            let selections = selections.clone();
 333                            let selection_infos = selection_infos.clone();
 334                            move |_, window: &mut Window, cx: &mut App| {
 335                                context_store.update(cx, |context_store, cx| {
 336                                    for (buffer, range) in &selections {
 337                                        context_store.add_selection(
 338                                            buffer.clone(),
 339                                            range.clone(),
 340                                            cx,
 341                                        );
 342                                    }
 343                                });
 344
 345                                let editor = editor.clone();
 346                                let selection_infos = selection_infos.clone();
 347                                window.defer(cx, move |window, cx| {
 348                                    let mut current_offset = 0;
 349                                    for (file_name, link, line_range) in selection_infos.iter() {
 350                                        let snapshot =
 351                                            editor.read(cx).buffer().read(cx).snapshot(cx);
 352                                        let Some(start) = snapshot
 353                                            .anchor_in_excerpt(excerpt_id, source_range.start)
 354                                        else {
 355                                            return;
 356                                        };
 357
 358                                        let offset = start.to_offset(&snapshot) + current_offset;
 359                                        let text_len = link.len();
 360
 361                                        let range = snapshot.anchor_after(offset)
 362                                            ..snapshot.anchor_after(offset + text_len);
 363
 364                                        let crease = super::crease_for_mention(
 365                                            format!(
 366                                                "{} ({}-{})",
 367                                                file_name,
 368                                                line_range.start.row + 1,
 369                                                line_range.end.row + 1
 370                                            )
 371                                            .into(),
 372                                            IconName::Context.path().into(),
 373                                            range,
 374                                            editor.downgrade(),
 375                                        );
 376
 377                                        editor.update(cx, |editor, cx| {
 378                                            editor.insert_creases(vec![crease.clone()], cx);
 379                                            editor.fold_creases(vec![crease], false, window, cx);
 380                                        });
 381
 382                                        current_offset += text_len + 1;
 383                                    }
 384                                });
 385
 386                                false
 387                            }
 388                        });
 389
 390                        (new_text, callback)
 391                    }
 392                };
 393
 394                Some(Completion {
 395                    replace_range: source_range.clone(),
 396                    new_text,
 397                    label: CodeLabel::plain(action.label().to_string(), None),
 398                    icon_path: Some(action.icon().path().into()),
 399                    documentation: None,
 400                    source: project::CompletionSource::Custom,
 401                    insert_text_mode: None,
 402                    // This ensures that when a user accepts this completion, the
 403                    // completion menu will still be shown after "@category " is
 404                    // inserted
 405                    confirm: Some(on_action),
 406                })
 407            }
 408        }
 409    }
 410
 411    fn completion_for_thread(
 412        thread_entry: ThreadContextEntry,
 413        excerpt_id: ExcerptId,
 414        source_range: Range<Anchor>,
 415        recent: bool,
 416        editor: Entity<Editor>,
 417        context_store: Entity<ContextStore>,
 418        thread_store: Entity<ThreadStore>,
 419        text_thread_store: Entity<TextThreadStore>,
 420    ) -> Completion {
 421        let icon_for_completion = if recent {
 422            IconName::HistoryRerun
 423        } else {
 424            IconName::MessageBubbles
 425        };
 426        let new_text = format!("{} ", MentionLink::for_thread(&thread_entry));
 427        let new_text_len = new_text.len();
 428        Completion {
 429            replace_range: source_range.clone(),
 430            new_text,
 431            label: CodeLabel::plain(thread_entry.title().to_string(), None),
 432            documentation: None,
 433            insert_text_mode: None,
 434            source: project::CompletionSource::Custom,
 435            icon_path: Some(icon_for_completion.path().into()),
 436            confirm: Some(confirm_completion_callback(
 437                IconName::MessageBubbles.path().into(),
 438                thread_entry.title().clone(),
 439                excerpt_id,
 440                source_range.start,
 441                new_text_len - 1,
 442                editor.clone(),
 443                context_store.clone(),
 444                move |window, cx| match &thread_entry {
 445                    ThreadContextEntry::Thread { id, .. } => {
 446                        let thread_id = id.clone();
 447                        let context_store = context_store.clone();
 448                        let thread_store = thread_store.clone();
 449                        window.spawn::<_, Option<_>>(cx, async move |cx| {
 450                            let thread: Entity<Thread> = thread_store
 451                                .update_in(cx, |thread_store, window, cx| {
 452                                    thread_store.open_thread(&thread_id, window, cx)
 453                                })
 454                                .ok()?
 455                                .await
 456                                .log_err()?;
 457                            let context = context_store
 458                                .update(cx, |context_store, cx| {
 459                                    context_store.add_thread(thread, false, cx)
 460                                })
 461                                .ok()??;
 462                            Some(context)
 463                        })
 464                    }
 465                    ThreadContextEntry::Context { path, .. } => {
 466                        let path = path.clone();
 467                        let context_store = context_store.clone();
 468                        let text_thread_store = text_thread_store.clone();
 469                        cx.spawn::<_, Option<_>>(async move |cx| {
 470                            let thread = text_thread_store
 471                                .update(cx, |store, cx| store.open_local_context(path, cx))
 472                                .ok()?
 473                                .await
 474                                .log_err()?;
 475                            let context = context_store
 476                                .update(cx, |context_store, cx| {
 477                                    context_store.add_text_thread(thread, false, cx)
 478                                })
 479                                .ok()??;
 480                            Some(context)
 481                        })
 482                    }
 483                },
 484            )),
 485        }
 486    }
 487
 488    fn completion_for_rules(
 489        rules: RulesContextEntry,
 490        excerpt_id: ExcerptId,
 491        source_range: Range<Anchor>,
 492        editor: Entity<Editor>,
 493        context_store: Entity<ContextStore>,
 494    ) -> Completion {
 495        let new_text = format!("{} ", MentionLink::for_rule(&rules));
 496        let new_text_len = new_text.len();
 497        Completion {
 498            replace_range: source_range.clone(),
 499            new_text,
 500            label: CodeLabel::plain(rules.title.to_string(), None),
 501            documentation: None,
 502            insert_text_mode: None,
 503            source: project::CompletionSource::Custom,
 504            icon_path: Some(RULES_ICON.path().into()),
 505            confirm: Some(confirm_completion_callback(
 506                RULES_ICON.path().into(),
 507                rules.title.clone(),
 508                excerpt_id,
 509                source_range.start,
 510                new_text_len - 1,
 511                editor.clone(),
 512                context_store.clone(),
 513                move |_, cx| {
 514                    let user_prompt_id = rules.prompt_id;
 515                    let context = context_store.update(cx, |context_store, cx| {
 516                        context_store.add_rules(user_prompt_id, false, cx)
 517                    });
 518                    Task::ready(context)
 519                },
 520            )),
 521        }
 522    }
 523
 524    fn completion_for_fetch(
 525        source_range: Range<Anchor>,
 526        url_to_fetch: SharedString,
 527        excerpt_id: ExcerptId,
 528        editor: Entity<Editor>,
 529        context_store: Entity<ContextStore>,
 530        http_client: Arc<HttpClientWithUrl>,
 531    ) -> Completion {
 532        let new_text = format!("{} ", MentionLink::for_fetch(&url_to_fetch));
 533        let new_text_len = new_text.len();
 534        Completion {
 535            replace_range: source_range.clone(),
 536            new_text,
 537            label: CodeLabel::plain(url_to_fetch.to_string(), None),
 538            documentation: None,
 539            source: project::CompletionSource::Custom,
 540            icon_path: Some(IconName::Globe.path().into()),
 541            insert_text_mode: None,
 542            confirm: Some(confirm_completion_callback(
 543                IconName::Globe.path().into(),
 544                url_to_fetch.clone(),
 545                excerpt_id,
 546                source_range.start,
 547                new_text_len - 1,
 548                editor.clone(),
 549                context_store.clone(),
 550                move |_, cx| {
 551                    let context_store = context_store.clone();
 552                    let http_client = http_client.clone();
 553                    let url_to_fetch = url_to_fetch.clone();
 554                    cx.spawn(async move |cx| {
 555                        if let Some(context) = context_store
 556                            .read_with(cx, |context_store, _| {
 557                                context_store.get_url_context(url_to_fetch.clone())
 558                            })
 559                            .ok()?
 560                        {
 561                            return Some(context);
 562                        }
 563                        let content = cx
 564                            .background_spawn(fetch_url_content(
 565                                http_client,
 566                                url_to_fetch.to_string(),
 567                            ))
 568                            .await
 569                            .log_err()?;
 570                        context_store
 571                            .update(cx, |context_store, cx| {
 572                                context_store.add_fetched_url(url_to_fetch.to_string(), content, cx)
 573                            })
 574                            .ok()
 575                    })
 576                },
 577            )),
 578        }
 579    }
 580
 581    fn completion_for_path(
 582        project_path: ProjectPath,
 583        path_prefix: &str,
 584        is_recent: bool,
 585        is_directory: bool,
 586        excerpt_id: ExcerptId,
 587        source_range: Range<Anchor>,
 588        editor: Entity<Editor>,
 589        context_store: Entity<ContextStore>,
 590        cx: &App,
 591    ) -> Completion {
 592        let (file_name, directory) = super::file_context_picker::extract_file_name_and_directory(
 593            &project_path.path,
 594            path_prefix,
 595        );
 596
 597        let label =
 598            build_code_label_for_full_path(&file_name, directory.as_ref().map(|s| s.as_ref()), cx);
 599        let full_path = if let Some(directory) = directory {
 600            format!("{}{}", directory, file_name)
 601        } else {
 602            file_name.to_string()
 603        };
 604
 605        let crease_icon_path = if is_directory {
 606            FileIcons::get_folder_icon(false, cx).unwrap_or_else(|| IconName::Folder.path().into())
 607        } else {
 608            FileIcons::get_icon(Path::new(&full_path), cx)
 609                .unwrap_or_else(|| IconName::File.path().into())
 610        };
 611        let completion_icon_path = if is_recent {
 612            IconName::HistoryRerun.path().into()
 613        } else {
 614            crease_icon_path.clone()
 615        };
 616
 617        let new_text = format!("{} ", MentionLink::for_file(&file_name, &full_path));
 618        let new_text_len = new_text.len();
 619        Completion {
 620            replace_range: source_range.clone(),
 621            new_text,
 622            label,
 623            documentation: None,
 624            source: project::CompletionSource::Custom,
 625            icon_path: Some(completion_icon_path),
 626            insert_text_mode: None,
 627            confirm: Some(confirm_completion_callback(
 628                crease_icon_path,
 629                file_name,
 630                excerpt_id,
 631                source_range.start,
 632                new_text_len - 1,
 633                editor,
 634                context_store.clone(),
 635                move |_, cx| {
 636                    if is_directory {
 637                        Task::ready(
 638                            context_store
 639                                .update(cx, |context_store, cx| {
 640                                    context_store.add_directory(&project_path, false, cx)
 641                                })
 642                                .log_err()
 643                                .flatten(),
 644                        )
 645                    } else {
 646                        let result = context_store.update(cx, |context_store, cx| {
 647                            context_store.add_file_from_path(project_path.clone(), false, cx)
 648                        });
 649                        cx.spawn(async move |_| result.await.log_err().flatten())
 650                    }
 651                },
 652            )),
 653        }
 654    }
 655
 656    fn completion_for_symbol(
 657        symbol: Symbol,
 658        excerpt_id: ExcerptId,
 659        source_range: Range<Anchor>,
 660        editor: Entity<Editor>,
 661        context_store: Entity<ContextStore>,
 662        workspace: Entity<Workspace>,
 663        cx: &mut App,
 664    ) -> Option<Completion> {
 665        let path_prefix = workspace
 666            .read(cx)
 667            .project()
 668            .read(cx)
 669            .worktree_for_id(symbol.path.worktree_id, cx)?
 670            .read(cx)
 671            .root_name();
 672
 673        let (file_name, directory) = super::file_context_picker::extract_file_name_and_directory(
 674            &symbol.path.path,
 675            path_prefix,
 676        );
 677        let full_path = if let Some(directory) = directory {
 678            format!("{}{}", directory, file_name)
 679        } else {
 680            file_name.to_string()
 681        };
 682
 683        let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 684        let mut label = CodeLabel::plain(symbol.name.clone(), None);
 685        label.push_str(" ", None);
 686        label.push_str(&file_name, comment_id);
 687
 688        let new_text = format!("{} ", MentionLink::for_symbol(&symbol.name, &full_path));
 689        let new_text_len = new_text.len();
 690        Some(Completion {
 691            replace_range: source_range.clone(),
 692            new_text,
 693            label,
 694            documentation: None,
 695            source: project::CompletionSource::Custom,
 696            icon_path: Some(IconName::Code.path().into()),
 697            insert_text_mode: None,
 698            confirm: Some(confirm_completion_callback(
 699                IconName::Code.path().into(),
 700                symbol.name.clone().into(),
 701                excerpt_id,
 702                source_range.start,
 703                new_text_len - 1,
 704                editor.clone(),
 705                context_store.clone(),
 706                move |_, cx| {
 707                    let symbol = symbol.clone();
 708                    let context_store = context_store.clone();
 709                    let workspace = workspace.clone();
 710                    let result = super::symbol_context_picker::add_symbol(
 711                        symbol.clone(),
 712                        false,
 713                        workspace.clone(),
 714                        context_store.downgrade(),
 715                        cx,
 716                    );
 717                    cx.spawn(async move |_| result.await.log_err()?.0)
 718                },
 719            )),
 720        })
 721    }
 722}
 723
 724fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
 725    let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 726    let mut label = CodeLabel::default();
 727
 728    label.push_str(&file_name, None);
 729    label.push_str(" ", None);
 730
 731    if let Some(directory) = directory {
 732        label.push_str(&directory, comment_id);
 733    }
 734
 735    label.filter_range = 0..label.text().len();
 736
 737    label
 738}
 739
 740impl CompletionProvider for ContextPickerCompletionProvider {
 741    fn completions(
 742        &self,
 743        excerpt_id: ExcerptId,
 744        buffer: &Entity<Buffer>,
 745        buffer_position: Anchor,
 746        _trigger: CompletionContext,
 747        _window: &mut Window,
 748        cx: &mut Context<Editor>,
 749    ) -> Task<Result<Vec<CompletionResponse>>> {
 750        let state = buffer.update(cx, |buffer, _cx| {
 751            let position = buffer_position.to_point(buffer);
 752            let line_start = Point::new(position.row, 0);
 753            let offset_to_line = buffer.point_to_offset(line_start);
 754            let mut lines = buffer.text_for_range(line_start..position).lines();
 755            let line = lines.next()?;
 756            MentionCompletion::try_parse(line, offset_to_line)
 757        });
 758        let Some(state) = state else {
 759            return Task::ready(Ok(Vec::new()));
 760        };
 761
 762        let Some((workspace, context_store)) =
 763            self.workspace.upgrade().zip(self.context_store.upgrade())
 764        else {
 765            return Task::ready(Ok(Vec::new()));
 766        };
 767
 768        let snapshot = buffer.read(cx).snapshot();
 769        let source_range = snapshot.anchor_before(state.source_range.start)
 770            ..snapshot.anchor_before(state.source_range.end);
 771
 772        let thread_store = self.thread_store.clone();
 773        let text_thread_store = self.text_thread_store.clone();
 774        let editor = self.editor.clone();
 775        let http_client = workspace.read(cx).client().http_client();
 776
 777        let MentionCompletion { mode, argument, .. } = state;
 778        let query = argument.unwrap_or_else(|| "".to_string());
 779
 780        let excluded_path = self
 781            .excluded_buffer
 782            .as_ref()
 783            .and_then(WeakEntity::upgrade)
 784            .and_then(|b| b.read(cx).file())
 785            .map(|file| ProjectPath::from_file(file.as_ref(), cx));
 786
 787        let recent_entries = recent_context_picker_entries(
 788            context_store.clone(),
 789            thread_store.clone(),
 790            text_thread_store.clone(),
 791            workspace.clone(),
 792            excluded_path.clone(),
 793            cx,
 794        );
 795
 796        let prompt_store = thread_store.as_ref().and_then(|thread_store| {
 797            thread_store
 798                .read_with(cx, |thread_store, _cx| thread_store.prompt_store().clone())
 799                .ok()
 800                .flatten()
 801        });
 802
 803        let search_task = search(
 804            mode,
 805            query,
 806            Arc::<AtomicBool>::default(),
 807            recent_entries,
 808            prompt_store,
 809            thread_store.clone(),
 810            text_thread_store.clone(),
 811            workspace.clone(),
 812            cx,
 813        );
 814
 815        cx.spawn(async move |_, cx| {
 816            let matches = search_task.await;
 817            let Some(editor) = editor.upgrade() else {
 818                return Ok(Vec::new());
 819            };
 820
 821            let completions = cx.update(|cx| {
 822                matches
 823                    .into_iter()
 824                    .filter_map(|mat| match mat {
 825                        Match::File(FileMatch { mat, is_recent }) => {
 826                            let project_path = ProjectPath {
 827                                worktree_id: WorktreeId::from_usize(mat.worktree_id),
 828                                path: mat.path.clone(),
 829                            };
 830
 831                            if excluded_path.as_ref() == Some(&project_path) {
 832                                return None;
 833                            }
 834
 835                            Some(Self::completion_for_path(
 836                                project_path,
 837                                &mat.path_prefix,
 838                                is_recent,
 839                                mat.is_dir,
 840                                excerpt_id,
 841                                source_range.clone(),
 842                                editor.clone(),
 843                                context_store.clone(),
 844                                cx,
 845                            ))
 846                        }
 847
 848                        Match::Symbol(SymbolMatch { symbol, .. }) => Self::completion_for_symbol(
 849                            symbol,
 850                            excerpt_id,
 851                            source_range.clone(),
 852                            editor.clone(),
 853                            context_store.clone(),
 854                            workspace.clone(),
 855                            cx,
 856                        ),
 857
 858                        Match::Thread(ThreadMatch {
 859                            thread, is_recent, ..
 860                        }) => {
 861                            let thread_store = thread_store.as_ref().and_then(|t| t.upgrade())?;
 862                            let text_thread_store =
 863                                text_thread_store.as_ref().and_then(|t| t.upgrade())?;
 864                            Some(Self::completion_for_thread(
 865                                thread,
 866                                excerpt_id,
 867                                source_range.clone(),
 868                                is_recent,
 869                                editor.clone(),
 870                                context_store.clone(),
 871                                thread_store,
 872                                text_thread_store,
 873                            ))
 874                        }
 875
 876                        Match::Rules(user_rules) => Some(Self::completion_for_rules(
 877                            user_rules,
 878                            excerpt_id,
 879                            source_range.clone(),
 880                            editor.clone(),
 881                            context_store.clone(),
 882                        )),
 883
 884                        Match::Fetch(url) => Some(Self::completion_for_fetch(
 885                            source_range.clone(),
 886                            url,
 887                            excerpt_id,
 888                            editor.clone(),
 889                            context_store.clone(),
 890                            http_client.clone(),
 891                        )),
 892
 893                        Match::Entry(EntryMatch { entry, .. }) => Self::completion_for_entry(
 894                            entry,
 895                            excerpt_id,
 896                            source_range.clone(),
 897                            editor.clone(),
 898                            context_store.clone(),
 899                            &workspace,
 900                            cx,
 901                        ),
 902                    })
 903                    .collect()
 904            })?;
 905
 906            Ok(vec![CompletionResponse {
 907                completions,
 908                // Since this does its own filtering (see `filter_completions()` returns false),
 909                // there is no benefit to computing whether this set of completions is incomplete.
 910                is_incomplete: true,
 911            }])
 912        })
 913    }
 914
 915    fn resolve_completions(
 916        &self,
 917        _buffer: Entity<Buffer>,
 918        _completion_indices: Vec<usize>,
 919        _completions: Rc<RefCell<Box<[Completion]>>>,
 920        _cx: &mut Context<Editor>,
 921    ) -> Task<Result<bool>> {
 922        Task::ready(Ok(true))
 923    }
 924
 925    fn is_completion_trigger(
 926        &self,
 927        buffer: &Entity<language::Buffer>,
 928        position: language::Anchor,
 929        _: &str,
 930        _: bool,
 931        cx: &mut Context<Editor>,
 932    ) -> bool {
 933        let buffer = buffer.read(cx);
 934        let position = position.to_point(buffer);
 935        let line_start = Point::new(position.row, 0);
 936        let offset_to_line = buffer.point_to_offset(line_start);
 937        let mut lines = buffer.text_for_range(line_start..position).lines();
 938        if let Some(line) = lines.next() {
 939            MentionCompletion::try_parse(line, offset_to_line)
 940                .map(|completion| {
 941                    completion.source_range.start <= offset_to_line + position.column as usize
 942                        && completion.source_range.end >= offset_to_line + position.column as usize
 943                })
 944                .unwrap_or(false)
 945        } else {
 946            false
 947        }
 948    }
 949
 950    fn sort_completions(&self) -> bool {
 951        false
 952    }
 953
 954    fn filter_completions(&self) -> bool {
 955        false
 956    }
 957}
 958
 959fn confirm_completion_callback(
 960    crease_icon_path: SharedString,
 961    crease_text: SharedString,
 962    excerpt_id: ExcerptId,
 963    start: Anchor,
 964    content_len: usize,
 965    editor: Entity<Editor>,
 966    context_store: Entity<ContextStore>,
 967    add_context_fn: impl Fn(&mut Window, &mut App) -> Task<Option<AgentContextHandle>>
 968    + Send
 969    + Sync
 970    + 'static,
 971) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 972    Arc::new(move |_, window, cx| {
 973        let context = add_context_fn(window, cx);
 974
 975        let crease_text = crease_text.clone();
 976        let crease_icon_path = crease_icon_path.clone();
 977        let editor = editor.clone();
 978        let context_store = context_store.clone();
 979        window.defer(cx, move |window, cx| {
 980            let crease_id = crate::context_picker::insert_crease_for_mention(
 981                excerpt_id,
 982                start,
 983                content_len,
 984                crease_text.clone(),
 985                crease_icon_path,
 986                editor.clone(),
 987                window,
 988                cx,
 989            );
 990            cx.spawn(async move |cx| {
 991                let crease_id = crease_id?;
 992                let context = context.await?;
 993                editor
 994                    .update(cx, |editor, cx| {
 995                        if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
 996                            addon.add_creases(
 997                                &context_store,
 998                                AgentContextKey(context),
 999                                [(crease_id, crease_text)],
1000                                cx,
1001                            );
1002                        }
1003                    })
1004                    .ok()
1005            })
1006            .detach();
1007        });
1008        false
1009    })
1010}
1011
1012#[derive(Debug, Default, PartialEq)]
1013struct MentionCompletion {
1014    source_range: Range<usize>,
1015    mode: Option<ContextPickerMode>,
1016    argument: Option<String>,
1017}
1018
1019impl MentionCompletion {
1020    fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1021        let last_mention_start = line.rfind('@')?;
1022        if last_mention_start >= line.len() {
1023            return Some(Self::default());
1024        }
1025        if last_mention_start > 0
1026            && line
1027                .chars()
1028                .nth(last_mention_start - 1)
1029                .map_or(false, |c| !c.is_whitespace())
1030        {
1031            return None;
1032        }
1033
1034        let rest_of_line = &line[last_mention_start + 1..];
1035
1036        let mut mode = None;
1037        let mut argument = None;
1038
1039        let mut parts = rest_of_line.split_whitespace();
1040        let mut end = last_mention_start + 1;
1041        if let Some(mode_text) = parts.next() {
1042            end += mode_text.len();
1043
1044            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok() {
1045                mode = Some(parsed_mode);
1046            } else {
1047                argument = Some(mode_text.to_string());
1048            }
1049            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1050                Some(whitespace_count) => {
1051                    if let Some(argument_text) = parts.next() {
1052                        argument = Some(argument_text.to_string());
1053                        end += whitespace_count + argument_text.len();
1054                    }
1055                }
1056                None => {
1057                    // Rest of line is entirely whitespace
1058                    end += rest_of_line.len() - mode_text.len();
1059                }
1060            }
1061        }
1062
1063        Some(Self {
1064            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1065            mode,
1066            argument,
1067        })
1068    }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073    use super::*;
1074    use editor::AnchorRangeExt;
1075    use gpui::{EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext};
1076    use project::{Project, ProjectPath};
1077    use serde_json::json;
1078    use settings::SettingsStore;
1079    use std::ops::Deref;
1080    use util::{path, separator};
1081    use workspace::{AppState, Item};
1082
1083    #[test]
1084    fn test_mention_completion_parse() {
1085        assert_eq!(MentionCompletion::try_parse("Lorem Ipsum", 0), None);
1086
1087        assert_eq!(
1088            MentionCompletion::try_parse("Lorem @", 0),
1089            Some(MentionCompletion {
1090                source_range: 6..7,
1091                mode: None,
1092                argument: None,
1093            })
1094        );
1095
1096        assert_eq!(
1097            MentionCompletion::try_parse("Lorem @file", 0),
1098            Some(MentionCompletion {
1099                source_range: 6..11,
1100                mode: Some(ContextPickerMode::File),
1101                argument: None,
1102            })
1103        );
1104
1105        assert_eq!(
1106            MentionCompletion::try_parse("Lorem @file ", 0),
1107            Some(MentionCompletion {
1108                source_range: 6..12,
1109                mode: Some(ContextPickerMode::File),
1110                argument: None,
1111            })
1112        );
1113
1114        assert_eq!(
1115            MentionCompletion::try_parse("Lorem @file main.rs", 0),
1116            Some(MentionCompletion {
1117                source_range: 6..19,
1118                mode: Some(ContextPickerMode::File),
1119                argument: Some("main.rs".to_string()),
1120            })
1121        );
1122
1123        assert_eq!(
1124            MentionCompletion::try_parse("Lorem @file main.rs ", 0),
1125            Some(MentionCompletion {
1126                source_range: 6..19,
1127                mode: Some(ContextPickerMode::File),
1128                argument: Some("main.rs".to_string()),
1129            })
1130        );
1131
1132        assert_eq!(
1133            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0),
1134            Some(MentionCompletion {
1135                source_range: 6..19,
1136                mode: Some(ContextPickerMode::File),
1137                argument: Some("main.rs".to_string()),
1138            })
1139        );
1140
1141        assert_eq!(
1142            MentionCompletion::try_parse("Lorem @main", 0),
1143            Some(MentionCompletion {
1144                source_range: 6..11,
1145                mode: None,
1146                argument: Some("main".to_string()),
1147            })
1148        );
1149
1150        assert_eq!(MentionCompletion::try_parse("test@", 0), None);
1151    }
1152
1153    struct AtMentionEditor(Entity<Editor>);
1154
1155    impl Item for AtMentionEditor {
1156        type Event = ();
1157
1158        fn include_in_nav_history() -> bool {
1159            false
1160        }
1161
1162        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1163            "Test".into()
1164        }
1165    }
1166
1167    impl EventEmitter<()> for AtMentionEditor {}
1168
1169    impl Focusable for AtMentionEditor {
1170        fn focus_handle(&self, cx: &App) -> FocusHandle {
1171            self.0.read(cx).focus_handle(cx).clone()
1172        }
1173    }
1174
1175    impl Render for AtMentionEditor {
1176        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1177            self.0.clone().into_any_element()
1178        }
1179    }
1180
1181    #[gpui::test]
1182    async fn test_context_completion_provider(cx: &mut TestAppContext) {
1183        init_test(cx);
1184
1185        let app_state = cx.update(AppState::test);
1186
1187        cx.update(|cx| {
1188            language::init(cx);
1189            editor::init(cx);
1190            workspace::init(app_state.clone(), cx);
1191            Project::init_settings(cx);
1192        });
1193
1194        app_state
1195            .fs
1196            .as_fake()
1197            .insert_tree(
1198                path!("/dir"),
1199                json!({
1200                    "editor": "",
1201                    "a": {
1202                        "one.txt": "",
1203                        "two.txt": "",
1204                        "three.txt": "",
1205                        "four.txt": ""
1206                    },
1207                    "b": {
1208                        "five.txt": "",
1209                        "six.txt": "",
1210                        "seven.txt": "",
1211                        "eight.txt": "",
1212                    }
1213                }),
1214            )
1215            .await;
1216
1217        let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1218        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1219        let workspace = window.root(cx).unwrap();
1220
1221        let worktree = project.update(cx, |project, cx| {
1222            let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
1223            assert_eq!(worktrees.len(), 1);
1224            worktrees.pop().unwrap()
1225        });
1226        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
1227
1228        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
1229
1230        let paths = vec![
1231            separator!("a/one.txt"),
1232            separator!("a/two.txt"),
1233            separator!("a/three.txt"),
1234            separator!("a/four.txt"),
1235            separator!("b/five.txt"),
1236            separator!("b/six.txt"),
1237            separator!("b/seven.txt"),
1238            separator!("b/eight.txt"),
1239        ];
1240
1241        let mut opened_editors = Vec::new();
1242        for path in paths {
1243            let buffer = workspace
1244                .update_in(&mut cx, |workspace, window, cx| {
1245                    workspace.open_path(
1246                        ProjectPath {
1247                            worktree_id,
1248                            path: Path::new(path).into(),
1249                        },
1250                        None,
1251                        false,
1252                        window,
1253                        cx,
1254                    )
1255                })
1256                .await
1257                .unwrap();
1258            opened_editors.push(buffer);
1259        }
1260
1261        let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1262            let editor = cx.new(|cx| {
1263                Editor::new(
1264                    editor::EditorMode::full(),
1265                    multi_buffer::MultiBuffer::build_simple("", cx),
1266                    None,
1267                    window,
1268                    cx,
1269                )
1270            });
1271            workspace.active_pane().update(cx, |pane, cx| {
1272                pane.add_item(
1273                    Box::new(cx.new(|_| AtMentionEditor(editor.clone()))),
1274                    true,
1275                    true,
1276                    None,
1277                    window,
1278                    cx,
1279                );
1280            });
1281            editor
1282        });
1283
1284        let context_store = cx.new(|_| ContextStore::new(project.downgrade(), None));
1285
1286        let editor_entity = editor.downgrade();
1287        editor.update_in(&mut cx, |editor, window, cx| {
1288            let last_opened_buffer = opened_editors.last().and_then(|editor| {
1289                editor
1290                    .downcast::<Editor>()?
1291                    .read(cx)
1292                    .buffer()
1293                    .read(cx)
1294                    .as_singleton()
1295                    .as_ref()
1296                    .map(Entity::downgrade)
1297            });
1298            window.focus(&editor.focus_handle(cx));
1299            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
1300                workspace.downgrade(),
1301                context_store.downgrade(),
1302                None,
1303                None,
1304                editor_entity,
1305                last_opened_buffer,
1306            ))));
1307        });
1308
1309        cx.simulate_input("Lorem ");
1310
1311        editor.update(&mut cx, |editor, cx| {
1312            assert_eq!(editor.text(cx), "Lorem ");
1313            assert!(!editor.has_visible_completions_menu());
1314        });
1315
1316        cx.simulate_input("@");
1317
1318        editor.update(&mut cx, |editor, cx| {
1319            assert_eq!(editor.text(cx), "Lorem @");
1320            assert!(editor.has_visible_completions_menu());
1321            assert_eq!(
1322                current_completion_labels(editor),
1323                &[
1324                    "seven.txt dir/b/",
1325                    "six.txt dir/b/",
1326                    "five.txt dir/b/",
1327                    "four.txt dir/a/",
1328                    "Files & Directories",
1329                    "Symbols",
1330                    "Fetch"
1331                ]
1332            );
1333        });
1334
1335        // Select and confirm "File"
1336        editor.update_in(&mut cx, |editor, window, cx| {
1337            assert!(editor.has_visible_completions_menu());
1338            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1339            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1340            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1341            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1342            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1343        });
1344
1345        cx.run_until_parked();
1346
1347        editor.update(&mut cx, |editor, cx| {
1348            assert_eq!(editor.text(cx), "Lorem @file ");
1349            assert!(editor.has_visible_completions_menu());
1350        });
1351
1352        cx.simulate_input("one");
1353
1354        editor.update(&mut cx, |editor, cx| {
1355            assert_eq!(editor.text(cx), "Lorem @file one");
1356            assert!(editor.has_visible_completions_menu());
1357            assert_eq!(current_completion_labels(editor), vec!["one.txt dir/a/"]);
1358        });
1359
1360        editor.update_in(&mut cx, |editor, window, cx| {
1361            assert!(editor.has_visible_completions_menu());
1362            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1363        });
1364
1365        editor.update(&mut cx, |editor, cx| {
1366            assert_eq!(editor.text(cx), "Lorem [@one.txt](@file:dir/a/one.txt) ");
1367            assert!(!editor.has_visible_completions_menu());
1368            assert_eq!(
1369                fold_ranges(editor, cx),
1370                vec![Point::new(0, 6)..Point::new(0, 37)]
1371            );
1372        });
1373
1374        cx.simulate_input(" ");
1375
1376        editor.update(&mut cx, |editor, cx| {
1377            assert_eq!(editor.text(cx), "Lorem [@one.txt](@file:dir/a/one.txt)  ");
1378            assert!(!editor.has_visible_completions_menu());
1379            assert_eq!(
1380                fold_ranges(editor, cx),
1381                vec![Point::new(0, 6)..Point::new(0, 37)]
1382            );
1383        });
1384
1385        cx.simulate_input("Ipsum ");
1386
1387        editor.update(&mut cx, |editor, cx| {
1388            assert_eq!(
1389                editor.text(cx),
1390                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum ",
1391            );
1392            assert!(!editor.has_visible_completions_menu());
1393            assert_eq!(
1394                fold_ranges(editor, cx),
1395                vec![Point::new(0, 6)..Point::new(0, 37)]
1396            );
1397        });
1398
1399        cx.simulate_input("@file ");
1400
1401        editor.update(&mut cx, |editor, cx| {
1402            assert_eq!(
1403                editor.text(cx),
1404                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum @file ",
1405            );
1406            assert!(editor.has_visible_completions_menu());
1407            assert_eq!(
1408                fold_ranges(editor, cx),
1409                vec![Point::new(0, 6)..Point::new(0, 37)]
1410            );
1411        });
1412
1413        editor.update_in(&mut cx, |editor, window, cx| {
1414            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1415        });
1416
1417        cx.run_until_parked();
1418
1419        editor.update(&mut cx, |editor, cx| {
1420            assert_eq!(
1421                editor.text(cx),
1422                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) "
1423            );
1424            assert!(!editor.has_visible_completions_menu());
1425            assert_eq!(
1426                fold_ranges(editor, cx),
1427                vec![
1428                    Point::new(0, 6)..Point::new(0, 37),
1429                    Point::new(0, 45)..Point::new(0, 80)
1430                ]
1431            );
1432        });
1433
1434        cx.simulate_input("\n@");
1435
1436        editor.update(&mut cx, |editor, cx| {
1437            assert_eq!(
1438                editor.text(cx),
1439                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) \n@"
1440            );
1441            assert!(editor.has_visible_completions_menu());
1442            assert_eq!(
1443                fold_ranges(editor, cx),
1444                vec![
1445                    Point::new(0, 6)..Point::new(0, 37),
1446                    Point::new(0, 45)..Point::new(0, 80)
1447                ]
1448            );
1449        });
1450
1451        editor.update_in(&mut cx, |editor, window, cx| {
1452            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1453        });
1454
1455        cx.run_until_parked();
1456
1457        editor.update(&mut cx, |editor, cx| {
1458            assert_eq!(
1459                editor.text(cx),
1460                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) \n[@six.txt](@file:dir/b/six.txt) "
1461            );
1462            assert!(!editor.has_visible_completions_menu());
1463            assert_eq!(
1464                fold_ranges(editor, cx),
1465                vec![
1466                    Point::new(0, 6)..Point::new(0, 37),
1467                    Point::new(0, 45)..Point::new(0, 80),
1468                    Point::new(1, 0)..Point::new(1, 31)
1469                ]
1470            );
1471        });
1472    }
1473
1474    fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
1475        let snapshot = editor.buffer().read(cx).snapshot(cx);
1476        editor.display_map.update(cx, |display_map, cx| {
1477            display_map
1478                .snapshot(cx)
1479                .folds_in_range(0..snapshot.len())
1480                .map(|fold| fold.range.to_point(&snapshot))
1481                .collect()
1482        })
1483    }
1484
1485    fn current_completion_labels(editor: &Editor) -> Vec<String> {
1486        let completions = editor.current_completions().expect("Missing completions");
1487        completions
1488            .into_iter()
1489            .map(|completion| completion.label.text.to_string())
1490            .collect::<Vec<_>>()
1491    }
1492
1493    pub(crate) fn init_test(cx: &mut TestAppContext) {
1494        cx.update(|cx| {
1495            let store = SettingsStore::test(cx);
1496            cx.set_global(store);
1497            theme::init(theme::LoadThemes::JustBase, cx);
1498            client::init_settings(cx);
1499            language::init(cx);
1500            Project::init_settings(cx);
1501            workspace::init_settings(cx);
1502            editor::init_settings(cx);
1503        });
1504    }
1505}