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        _text: &str,
 930        _trigger_in_words: bool,
 931        _menu_is_open: bool,
 932        cx: &mut Context<Editor>,
 933    ) -> bool {
 934        let buffer = buffer.read(cx);
 935        let position = position.to_point(buffer);
 936        let line_start = Point::new(position.row, 0);
 937        let offset_to_line = buffer.point_to_offset(line_start);
 938        let mut lines = buffer.text_for_range(line_start..position).lines();
 939        if let Some(line) = lines.next() {
 940            MentionCompletion::try_parse(line, offset_to_line)
 941                .map(|completion| {
 942                    completion.source_range.start <= offset_to_line + position.column as usize
 943                        && completion.source_range.end >= offset_to_line + position.column as usize
 944                })
 945                .unwrap_or(false)
 946        } else {
 947            false
 948        }
 949    }
 950
 951    fn sort_completions(&self) -> bool {
 952        false
 953    }
 954
 955    fn filter_completions(&self) -> bool {
 956        false
 957    }
 958}
 959
 960fn confirm_completion_callback(
 961    crease_icon_path: SharedString,
 962    crease_text: SharedString,
 963    excerpt_id: ExcerptId,
 964    start: Anchor,
 965    content_len: usize,
 966    editor: Entity<Editor>,
 967    context_store: Entity<ContextStore>,
 968    add_context_fn: impl Fn(&mut Window, &mut App) -> Task<Option<AgentContextHandle>>
 969    + Send
 970    + Sync
 971    + 'static,
 972) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 973    Arc::new(move |_, window, cx| {
 974        let context = add_context_fn(window, cx);
 975
 976        let crease_text = crease_text.clone();
 977        let crease_icon_path = crease_icon_path.clone();
 978        let editor = editor.clone();
 979        let context_store = context_store.clone();
 980        window.defer(cx, move |window, cx| {
 981            let crease_id = crate::context_picker::insert_crease_for_mention(
 982                excerpt_id,
 983                start,
 984                content_len,
 985                crease_text.clone(),
 986                crease_icon_path,
 987                editor.clone(),
 988                window,
 989                cx,
 990            );
 991            cx.spawn(async move |cx| {
 992                let crease_id = crease_id?;
 993                let context = context.await?;
 994                editor
 995                    .update(cx, |editor, cx| {
 996                        if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
 997                            addon.add_creases(
 998                                &context_store,
 999                                AgentContextKey(context),
1000                                [(crease_id, crease_text)],
1001                                cx,
1002                            );
1003                        }
1004                    })
1005                    .ok()
1006            })
1007            .detach();
1008        });
1009        false
1010    })
1011}
1012
1013#[derive(Debug, Default, PartialEq)]
1014struct MentionCompletion {
1015    source_range: Range<usize>,
1016    mode: Option<ContextPickerMode>,
1017    argument: Option<String>,
1018}
1019
1020impl MentionCompletion {
1021    fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1022        let last_mention_start = line.rfind('@')?;
1023        if last_mention_start >= line.len() {
1024            return Some(Self::default());
1025        }
1026        if last_mention_start > 0
1027            && line
1028                .chars()
1029                .nth(last_mention_start - 1)
1030                .map_or(false, |c| !c.is_whitespace())
1031        {
1032            return None;
1033        }
1034
1035        let rest_of_line = &line[last_mention_start + 1..];
1036
1037        let mut mode = None;
1038        let mut argument = None;
1039
1040        let mut parts = rest_of_line.split_whitespace();
1041        let mut end = last_mention_start + 1;
1042        if let Some(mode_text) = parts.next() {
1043            end += mode_text.len();
1044
1045            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok() {
1046                mode = Some(parsed_mode);
1047            } else {
1048                argument = Some(mode_text.to_string());
1049            }
1050            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1051                Some(whitespace_count) => {
1052                    if let Some(argument_text) = parts.next() {
1053                        argument = Some(argument_text.to_string());
1054                        end += whitespace_count + argument_text.len();
1055                    }
1056                }
1057                None => {
1058                    // Rest of line is entirely whitespace
1059                    end += rest_of_line.len() - mode_text.len();
1060                }
1061            }
1062        }
1063
1064        Some(Self {
1065            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1066            mode,
1067            argument,
1068        })
1069    }
1070}
1071
1072#[cfg(test)]
1073mod tests {
1074    use super::*;
1075    use editor::AnchorRangeExt;
1076    use gpui::{EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext};
1077    use project::{Project, ProjectPath};
1078    use serde_json::json;
1079    use settings::SettingsStore;
1080    use std::ops::Deref;
1081    use util::{path, separator};
1082    use workspace::{AppState, Item};
1083
1084    #[test]
1085    fn test_mention_completion_parse() {
1086        assert_eq!(MentionCompletion::try_parse("Lorem Ipsum", 0), None);
1087
1088        assert_eq!(
1089            MentionCompletion::try_parse("Lorem @", 0),
1090            Some(MentionCompletion {
1091                source_range: 6..7,
1092                mode: None,
1093                argument: None,
1094            })
1095        );
1096
1097        assert_eq!(
1098            MentionCompletion::try_parse("Lorem @file", 0),
1099            Some(MentionCompletion {
1100                source_range: 6..11,
1101                mode: Some(ContextPickerMode::File),
1102                argument: None,
1103            })
1104        );
1105
1106        assert_eq!(
1107            MentionCompletion::try_parse("Lorem @file ", 0),
1108            Some(MentionCompletion {
1109                source_range: 6..12,
1110                mode: Some(ContextPickerMode::File),
1111                argument: None,
1112            })
1113        );
1114
1115        assert_eq!(
1116            MentionCompletion::try_parse("Lorem @file main.rs", 0),
1117            Some(MentionCompletion {
1118                source_range: 6..19,
1119                mode: Some(ContextPickerMode::File),
1120                argument: Some("main.rs".to_string()),
1121            })
1122        );
1123
1124        assert_eq!(
1125            MentionCompletion::try_parse("Lorem @file main.rs ", 0),
1126            Some(MentionCompletion {
1127                source_range: 6..19,
1128                mode: Some(ContextPickerMode::File),
1129                argument: Some("main.rs".to_string()),
1130            })
1131        );
1132
1133        assert_eq!(
1134            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0),
1135            Some(MentionCompletion {
1136                source_range: 6..19,
1137                mode: Some(ContextPickerMode::File),
1138                argument: Some("main.rs".to_string()),
1139            })
1140        );
1141
1142        assert_eq!(
1143            MentionCompletion::try_parse("Lorem @main", 0),
1144            Some(MentionCompletion {
1145                source_range: 6..11,
1146                mode: None,
1147                argument: Some("main".to_string()),
1148            })
1149        );
1150
1151        assert_eq!(MentionCompletion::try_parse("test@", 0), None);
1152    }
1153
1154    struct AtMentionEditor(Entity<Editor>);
1155
1156    impl Item for AtMentionEditor {
1157        type Event = ();
1158
1159        fn include_in_nav_history() -> bool {
1160            false
1161        }
1162
1163        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1164            "Test".into()
1165        }
1166    }
1167
1168    impl EventEmitter<()> for AtMentionEditor {}
1169
1170    impl Focusable for AtMentionEditor {
1171        fn focus_handle(&self, cx: &App) -> FocusHandle {
1172            self.0.read(cx).focus_handle(cx).clone()
1173        }
1174    }
1175
1176    impl Render for AtMentionEditor {
1177        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1178            self.0.clone().into_any_element()
1179        }
1180    }
1181
1182    #[gpui::test]
1183    async fn test_context_completion_provider(cx: &mut TestAppContext) {
1184        init_test(cx);
1185
1186        let app_state = cx.update(AppState::test);
1187
1188        cx.update(|cx| {
1189            language::init(cx);
1190            editor::init(cx);
1191            workspace::init(app_state.clone(), cx);
1192            Project::init_settings(cx);
1193        });
1194
1195        app_state
1196            .fs
1197            .as_fake()
1198            .insert_tree(
1199                path!("/dir"),
1200                json!({
1201                    "editor": "",
1202                    "a": {
1203                        "one.txt": "",
1204                        "two.txt": "",
1205                        "three.txt": "",
1206                        "four.txt": ""
1207                    },
1208                    "b": {
1209                        "five.txt": "",
1210                        "six.txt": "",
1211                        "seven.txt": "",
1212                        "eight.txt": "",
1213                    }
1214                }),
1215            )
1216            .await;
1217
1218        let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1219        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1220        let workspace = window.root(cx).unwrap();
1221
1222        let worktree = project.update(cx, |project, cx| {
1223            let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
1224            assert_eq!(worktrees.len(), 1);
1225            worktrees.pop().unwrap()
1226        });
1227        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
1228
1229        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
1230
1231        let paths = vec![
1232            separator!("a/one.txt"),
1233            separator!("a/two.txt"),
1234            separator!("a/three.txt"),
1235            separator!("a/four.txt"),
1236            separator!("b/five.txt"),
1237            separator!("b/six.txt"),
1238            separator!("b/seven.txt"),
1239            separator!("b/eight.txt"),
1240        ];
1241
1242        let mut opened_editors = Vec::new();
1243        for path in paths {
1244            let buffer = workspace
1245                .update_in(&mut cx, |workspace, window, cx| {
1246                    workspace.open_path(
1247                        ProjectPath {
1248                            worktree_id,
1249                            path: Path::new(path).into(),
1250                        },
1251                        None,
1252                        false,
1253                        window,
1254                        cx,
1255                    )
1256                })
1257                .await
1258                .unwrap();
1259            opened_editors.push(buffer);
1260        }
1261
1262        let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1263            let editor = cx.new(|cx| {
1264                Editor::new(
1265                    editor::EditorMode::full(),
1266                    multi_buffer::MultiBuffer::build_simple("", cx),
1267                    None,
1268                    window,
1269                    cx,
1270                )
1271            });
1272            workspace.active_pane().update(cx, |pane, cx| {
1273                pane.add_item(
1274                    Box::new(cx.new(|_| AtMentionEditor(editor.clone()))),
1275                    true,
1276                    true,
1277                    None,
1278                    window,
1279                    cx,
1280                );
1281            });
1282            editor
1283        });
1284
1285        let context_store = cx.new(|_| ContextStore::new(project.downgrade(), None));
1286
1287        let editor_entity = editor.downgrade();
1288        editor.update_in(&mut cx, |editor, window, cx| {
1289            let last_opened_buffer = opened_editors.last().and_then(|editor| {
1290                editor
1291                    .downcast::<Editor>()?
1292                    .read(cx)
1293                    .buffer()
1294                    .read(cx)
1295                    .as_singleton()
1296                    .as_ref()
1297                    .map(Entity::downgrade)
1298            });
1299            window.focus(&editor.focus_handle(cx));
1300            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
1301                workspace.downgrade(),
1302                context_store.downgrade(),
1303                None,
1304                None,
1305                editor_entity,
1306                last_opened_buffer,
1307            ))));
1308        });
1309
1310        cx.simulate_input("Lorem ");
1311
1312        editor.update(&mut cx, |editor, cx| {
1313            assert_eq!(editor.text(cx), "Lorem ");
1314            assert!(!editor.has_visible_completions_menu());
1315        });
1316
1317        cx.simulate_input("@");
1318
1319        editor.update(&mut cx, |editor, cx| {
1320            assert_eq!(editor.text(cx), "Lorem @");
1321            assert!(editor.has_visible_completions_menu());
1322            assert_eq!(
1323                current_completion_labels(editor),
1324                &[
1325                    "seven.txt dir/b/",
1326                    "six.txt dir/b/",
1327                    "five.txt dir/b/",
1328                    "four.txt dir/a/",
1329                    "Files & Directories",
1330                    "Symbols",
1331                    "Fetch"
1332                ]
1333            );
1334        });
1335
1336        // Select and confirm "File"
1337        editor.update_in(&mut cx, |editor, window, cx| {
1338            assert!(editor.has_visible_completions_menu());
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.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1343            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1344        });
1345
1346        cx.run_until_parked();
1347
1348        editor.update(&mut cx, |editor, cx| {
1349            assert_eq!(editor.text(cx), "Lorem @file ");
1350            assert!(editor.has_visible_completions_menu());
1351        });
1352
1353        cx.simulate_input("one");
1354
1355        editor.update(&mut cx, |editor, cx| {
1356            assert_eq!(editor.text(cx), "Lorem @file one");
1357            assert!(editor.has_visible_completions_menu());
1358            assert_eq!(current_completion_labels(editor), vec!["one.txt dir/a/"]);
1359        });
1360
1361        editor.update_in(&mut cx, |editor, window, cx| {
1362            assert!(editor.has_visible_completions_menu());
1363            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1364        });
1365
1366        editor.update(&mut cx, |editor, cx| {
1367            assert_eq!(editor.text(cx), "Lorem [@one.txt](@file:dir/a/one.txt) ");
1368            assert!(!editor.has_visible_completions_menu());
1369            assert_eq!(
1370                fold_ranges(editor, cx),
1371                vec![Point::new(0, 6)..Point::new(0, 37)]
1372            );
1373        });
1374
1375        cx.simulate_input(" ");
1376
1377        editor.update(&mut cx, |editor, cx| {
1378            assert_eq!(editor.text(cx), "Lorem [@one.txt](@file:dir/a/one.txt)  ");
1379            assert!(!editor.has_visible_completions_menu());
1380            assert_eq!(
1381                fold_ranges(editor, cx),
1382                vec![Point::new(0, 6)..Point::new(0, 37)]
1383            );
1384        });
1385
1386        cx.simulate_input("Ipsum ");
1387
1388        editor.update(&mut cx, |editor, cx| {
1389            assert_eq!(
1390                editor.text(cx),
1391                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum ",
1392            );
1393            assert!(!editor.has_visible_completions_menu());
1394            assert_eq!(
1395                fold_ranges(editor, cx),
1396                vec![Point::new(0, 6)..Point::new(0, 37)]
1397            );
1398        });
1399
1400        cx.simulate_input("@file ");
1401
1402        editor.update(&mut cx, |editor, cx| {
1403            assert_eq!(
1404                editor.text(cx),
1405                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum @file ",
1406            );
1407            assert!(editor.has_visible_completions_menu());
1408            assert_eq!(
1409                fold_ranges(editor, cx),
1410                vec![Point::new(0, 6)..Point::new(0, 37)]
1411            );
1412        });
1413
1414        editor.update_in(&mut cx, |editor, window, cx| {
1415            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1416        });
1417
1418        cx.run_until_parked();
1419
1420        editor.update(&mut cx, |editor, cx| {
1421            assert_eq!(
1422                editor.text(cx),
1423                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) "
1424            );
1425            assert!(!editor.has_visible_completions_menu());
1426            assert_eq!(
1427                fold_ranges(editor, cx),
1428                vec![
1429                    Point::new(0, 6)..Point::new(0, 37),
1430                    Point::new(0, 45)..Point::new(0, 80)
1431                ]
1432            );
1433        });
1434
1435        cx.simulate_input("\n@");
1436
1437        editor.update(&mut cx, |editor, cx| {
1438            assert_eq!(
1439                editor.text(cx),
1440                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) \n@"
1441            );
1442            assert!(editor.has_visible_completions_menu());
1443            assert_eq!(
1444                fold_ranges(editor, cx),
1445                vec![
1446                    Point::new(0, 6)..Point::new(0, 37),
1447                    Point::new(0, 45)..Point::new(0, 80)
1448                ]
1449            );
1450        });
1451
1452        editor.update_in(&mut cx, |editor, window, cx| {
1453            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1454        });
1455
1456        cx.run_until_parked();
1457
1458        editor.update(&mut cx, |editor, cx| {
1459            assert_eq!(
1460                editor.text(cx),
1461                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) \n[@six.txt](@file:dir/b/six.txt) "
1462            );
1463            assert!(!editor.has_visible_completions_menu());
1464            assert_eq!(
1465                fold_ranges(editor, cx),
1466                vec![
1467                    Point::new(0, 6)..Point::new(0, 37),
1468                    Point::new(0, 45)..Point::new(0, 80),
1469                    Point::new(1, 0)..Point::new(1, 31)
1470                ]
1471            );
1472        });
1473    }
1474
1475    fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
1476        let snapshot = editor.buffer().read(cx).snapshot(cx);
1477        editor.display_map.update(cx, |display_map, cx| {
1478            display_map
1479                .snapshot(cx)
1480                .folds_in_range(0..snapshot.len())
1481                .map(|fold| fold.range.to_point(&snapshot))
1482                .collect()
1483        })
1484    }
1485
1486    fn current_completion_labels(editor: &Editor) -> Vec<String> {
1487        let completions = editor.current_completions().expect("Missing completions");
1488        completions
1489            .into_iter()
1490            .map(|completion| completion.label.text.to_string())
1491            .collect::<Vec<_>>()
1492    }
1493
1494    pub(crate) fn init_test(cx: &mut TestAppContext) {
1495        cx.update(|cx| {
1496            let store = SettingsStore::test(cx);
1497            cx.set_global(store);
1498            theme::init(theme::LoadThemes::JustBase, cx);
1499            client::init_settings(cx);
1500            language::init(cx);
1501            Project::init_settings(cx);
1502            workspace::init_settings(cx);
1503            editor::init_settings(cx);
1504        });
1505    }
1506}