completion_provider.rs

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