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