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 crease_icon_path = if is_directory {
 600            FileIcons::get_folder_icon(false, cx).unwrap_or_else(|| IconName::Folder.path().into())
 601        } else {
 602            FileIcons::get_icon(Path::new(&full_path), cx)
 603                .unwrap_or_else(|| IconName::File.path().into())
 604        };
 605        let completion_icon_path = if is_recent {
 606            IconName::HistoryRerun.path().into()
 607        } else {
 608            crease_icon_path.clone()
 609        };
 610
 611        let new_text = format!("{} ", MentionLink::for_file(&file_name, &full_path));
 612        let new_text_len = new_text.len();
 613        Completion {
 614            replace_range: source_range.clone(),
 615            new_text,
 616            label,
 617            documentation: None,
 618            source: project::CompletionSource::Custom,
 619            icon_path: Some(completion_icon_path),
 620            insert_text_mode: None,
 621            confirm: Some(confirm_completion_callback(
 622                crease_icon_path,
 623                file_name,
 624                excerpt_id,
 625                source_range.start,
 626                new_text_len - 1,
 627                editor,
 628                context_store.clone(),
 629                move |_, cx| {
 630                    if is_directory {
 631                        Task::ready(
 632                            context_store
 633                                .update(cx, |context_store, cx| {
 634                                    context_store.add_directory(&project_path, false, cx)
 635                                })
 636                                .log_err()
 637                                .flatten(),
 638                        )
 639                    } else {
 640                        let result = context_store.update(cx, |context_store, cx| {
 641                            context_store.add_file_from_path(project_path.clone(), false, cx)
 642                        });
 643                        cx.spawn(async move |_| result.await.log_err().flatten())
 644                    }
 645                },
 646            )),
 647        }
 648    }
 649
 650    fn completion_for_symbol(
 651        symbol: Symbol,
 652        excerpt_id: ExcerptId,
 653        source_range: Range<Anchor>,
 654        editor: Entity<Editor>,
 655        context_store: Entity<ContextStore>,
 656        workspace: Entity<Workspace>,
 657        cx: &mut App,
 658    ) -> Option<Completion> {
 659        let path_prefix = workspace
 660            .read(cx)
 661            .project()
 662            .read(cx)
 663            .worktree_for_id(symbol.path.worktree_id, cx)?
 664            .read(cx)
 665            .root_name();
 666
 667        let (file_name, directory) = super::file_context_picker::extract_file_name_and_directory(
 668            &symbol.path.path,
 669            path_prefix,
 670        );
 671        let full_path = if let Some(directory) = directory {
 672            format!("{}{}", directory, file_name)
 673        } else {
 674            file_name.to_string()
 675        };
 676
 677        let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 678        let mut label = CodeLabel::plain(symbol.name.clone(), None);
 679        label.push_str(" ", None);
 680        label.push_str(&file_name, comment_id);
 681        label.push_str(&format!(" L{}", symbol.range.start.0.row + 1), comment_id);
 682
 683        let new_text = format!("{} ", MentionLink::for_symbol(&symbol.name, &full_path));
 684        let new_text_len = new_text.len();
 685        Some(Completion {
 686            replace_range: source_range.clone(),
 687            new_text,
 688            label,
 689            documentation: None,
 690            source: project::CompletionSource::Custom,
 691            icon_path: Some(IconName::Code.path().into()),
 692            insert_text_mode: None,
 693            confirm: Some(confirm_completion_callback(
 694                IconName::Code.path().into(),
 695                symbol.name.clone().into(),
 696                excerpt_id,
 697                source_range.start,
 698                new_text_len - 1,
 699                editor,
 700                context_store.clone(),
 701                move |_, cx| {
 702                    let symbol = symbol.clone();
 703                    let context_store = context_store.clone();
 704                    let workspace = workspace.clone();
 705                    let result = super::symbol_context_picker::add_symbol(
 706                        symbol,
 707                        false,
 708                        workspace,
 709                        context_store.downgrade(),
 710                        cx,
 711                    );
 712                    cx.spawn(async move |_| result.await.log_err()?.0)
 713                },
 714            )),
 715        })
 716    }
 717}
 718
 719fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
 720    let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
 721    let mut label = CodeLabel::default();
 722
 723    label.push_str(file_name, None);
 724    label.push_str(" ", None);
 725
 726    if let Some(directory) = directory {
 727        label.push_str(directory, comment_id);
 728    }
 729
 730    label.filter_range = 0..label.text().len();
 731
 732    label
 733}
 734
 735impl CompletionProvider for ContextPickerCompletionProvider {
 736    fn completions(
 737        &self,
 738        excerpt_id: ExcerptId,
 739        buffer: &Entity<Buffer>,
 740        buffer_position: Anchor,
 741        _trigger: CompletionContext,
 742        _window: &mut Window,
 743        cx: &mut Context<Editor>,
 744    ) -> Task<Result<Vec<CompletionResponse>>> {
 745        let state = buffer.update(cx, |buffer, _cx| {
 746            let position = buffer_position.to_point(buffer);
 747            let line_start = Point::new(position.row, 0);
 748            let offset_to_line = buffer.point_to_offset(line_start);
 749            let mut lines = buffer.text_for_range(line_start..position).lines();
 750            let line = lines.next()?;
 751            MentionCompletion::try_parse(line, offset_to_line)
 752        });
 753        let Some(state) = state else {
 754            return Task::ready(Ok(Vec::new()));
 755        };
 756
 757        let Some((workspace, context_store)) =
 758            self.workspace.upgrade().zip(self.context_store.upgrade())
 759        else {
 760            return Task::ready(Ok(Vec::new()));
 761        };
 762
 763        let snapshot = buffer.read(cx).snapshot();
 764        let source_range = snapshot.anchor_before(state.source_range.start)
 765            ..snapshot.anchor_after(state.source_range.end);
 766
 767        let thread_store = self.thread_store.clone();
 768        let text_thread_store = self.text_thread_store.clone();
 769        let editor = self.editor.clone();
 770        let http_client = workspace.read(cx).client().http_client();
 771
 772        let MentionCompletion { mode, argument, .. } = state;
 773        let query = argument.unwrap_or_else(|| "".to_string());
 774
 775        let excluded_path = self
 776            .excluded_buffer
 777            .as_ref()
 778            .and_then(WeakEntity::upgrade)
 779            .and_then(|b| b.read(cx).file())
 780            .map(|file| ProjectPath::from_file(file.as_ref(), cx));
 781
 782        let recent_entries = recent_context_picker_entries_with_store(
 783            context_store.clone(),
 784            thread_store.clone(),
 785            text_thread_store.clone(),
 786            workspace.clone(),
 787            excluded_path.clone(),
 788            cx,
 789        );
 790
 791        let prompt_store = thread_store.as_ref().and_then(|thread_store| {
 792            thread_store
 793                .read_with(cx, |thread_store, _cx| thread_store.prompt_store().clone())
 794                .ok()
 795                .flatten()
 796        });
 797
 798        let search_task = search(
 799            mode,
 800            query,
 801            Arc::<AtomicBool>::default(),
 802            recent_entries,
 803            prompt_store,
 804            thread_store.clone(),
 805            text_thread_store.clone(),
 806            workspace.clone(),
 807            cx,
 808        );
 809
 810        cx.spawn(async move |_, cx| {
 811            let matches = search_task.await;
 812            let Some(editor) = editor.upgrade() else {
 813                return Ok(Vec::new());
 814            };
 815
 816            let completions = cx.update(|cx| {
 817                matches
 818                    .into_iter()
 819                    .filter_map(|mat| match mat {
 820                        Match::File(FileMatch { mat, is_recent }) => {
 821                            let project_path = ProjectPath {
 822                                worktree_id: WorktreeId::from_usize(mat.worktree_id),
 823                                path: mat.path.clone(),
 824                            };
 825
 826                            if excluded_path.as_ref() == Some(&project_path) {
 827                                return None;
 828                            }
 829
 830                            Some(Self::completion_for_path(
 831                                project_path,
 832                                &mat.path_prefix,
 833                                is_recent,
 834                                mat.is_dir,
 835                                excerpt_id,
 836                                source_range.clone(),
 837                                editor.clone(),
 838                                context_store.clone(),
 839                                cx,
 840                            ))
 841                        }
 842
 843                        Match::Symbol(SymbolMatch { symbol, .. }) => Self::completion_for_symbol(
 844                            symbol,
 845                            excerpt_id,
 846                            source_range.clone(),
 847                            editor.clone(),
 848                            context_store.clone(),
 849                            workspace.clone(),
 850                            cx,
 851                        ),
 852
 853                        Match::Thread(ThreadMatch {
 854                            thread, is_recent, ..
 855                        }) => {
 856                            let thread_store = thread_store.as_ref().and_then(|t| t.upgrade())?;
 857                            let text_thread_store =
 858                                text_thread_store.as_ref().and_then(|t| t.upgrade())?;
 859                            Some(Self::completion_for_thread(
 860                                thread,
 861                                excerpt_id,
 862                                source_range.clone(),
 863                                is_recent,
 864                                editor.clone(),
 865                                context_store.clone(),
 866                                thread_store,
 867                                text_thread_store,
 868                            ))
 869                        }
 870
 871                        Match::Rules(user_rules) => Some(Self::completion_for_rules(
 872                            user_rules,
 873                            excerpt_id,
 874                            source_range.clone(),
 875                            editor.clone(),
 876                            context_store.clone(),
 877                        )),
 878
 879                        Match::Fetch(url) => Some(Self::completion_for_fetch(
 880                            source_range.clone(),
 881                            url,
 882                            excerpt_id,
 883                            editor.clone(),
 884                            context_store.clone(),
 885                            http_client.clone(),
 886                        )),
 887
 888                        Match::Entry(EntryMatch { entry, .. }) => Self::completion_for_entry(
 889                            entry,
 890                            excerpt_id,
 891                            source_range.clone(),
 892                            editor.clone(),
 893                            context_store.clone(),
 894                            &workspace,
 895                            cx,
 896                        ),
 897                    })
 898                    .collect()
 899            })?;
 900
 901            Ok(vec![CompletionResponse {
 902                completions,
 903                display_options: CompletionDisplayOptions::default(),
 904                // Since this does its own filtering (see `filter_completions()` returns false),
 905                // there is no benefit to computing whether this set of completions is incomplete.
 906                is_incomplete: true,
 907            }])
 908        })
 909    }
 910
 911    fn is_completion_trigger(
 912        &self,
 913        buffer: &Entity<language::Buffer>,
 914        position: language::Anchor,
 915        _text: &str,
 916        _trigger_in_words: bool,
 917        _menu_is_open: bool,
 918        cx: &mut Context<Editor>,
 919    ) -> bool {
 920        let buffer = buffer.read(cx);
 921        let position = position.to_point(buffer);
 922        let line_start = Point::new(position.row, 0);
 923        let offset_to_line = buffer.point_to_offset(line_start);
 924        let mut lines = buffer.text_for_range(line_start..position).lines();
 925        if let Some(line) = lines.next() {
 926            MentionCompletion::try_parse(line, offset_to_line)
 927                .map(|completion| {
 928                    completion.source_range.start <= offset_to_line + position.column as usize
 929                        && completion.source_range.end >= offset_to_line + position.column as usize
 930                })
 931                .unwrap_or(false)
 932        } else {
 933            false
 934        }
 935    }
 936
 937    fn sort_completions(&self) -> bool {
 938        false
 939    }
 940
 941    fn filter_completions(&self) -> bool {
 942        false
 943    }
 944}
 945
 946fn confirm_completion_callback(
 947    crease_icon_path: SharedString,
 948    crease_text: SharedString,
 949    excerpt_id: ExcerptId,
 950    start: Anchor,
 951    content_len: usize,
 952    editor: Entity<Editor>,
 953    context_store: Entity<ContextStore>,
 954    add_context_fn: impl Fn(&mut Window, &mut App) -> Task<Option<AgentContextHandle>>
 955    + Send
 956    + Sync
 957    + 'static,
 958) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
 959    Arc::new(move |_, window, cx| {
 960        let context = add_context_fn(window, cx);
 961
 962        let crease_text = crease_text.clone();
 963        let crease_icon_path = crease_icon_path.clone();
 964        let editor = editor.clone();
 965        let context_store = context_store.clone();
 966        window.defer(cx, move |window, cx| {
 967            let crease_id = crate::context_picker::insert_crease_for_mention(
 968                excerpt_id,
 969                start,
 970                content_len,
 971                crease_text.clone(),
 972                crease_icon_path,
 973                editor.clone(),
 974                window,
 975                cx,
 976            );
 977            cx.spawn(async move |cx| {
 978                let crease_id = crease_id?;
 979                let context = context.await?;
 980                editor
 981                    .update(cx, |editor, cx| {
 982                        if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
 983                            addon.add_creases(
 984                                &context_store,
 985                                AgentContextKey(context),
 986                                [(crease_id, crease_text)],
 987                                cx,
 988                            );
 989                        }
 990                    })
 991                    .ok()
 992            })
 993            .detach();
 994        });
 995        false
 996    })
 997}
 998
 999#[derive(Debug, Default, PartialEq)]
1000struct MentionCompletion {
1001    source_range: Range<usize>,
1002    mode: Option<ContextPickerMode>,
1003    argument: Option<String>,
1004}
1005
1006impl MentionCompletion {
1007    fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1008        let last_mention_start = line.rfind('@')?;
1009        if last_mention_start >= line.len() {
1010            return Some(Self::default());
1011        }
1012        if last_mention_start > 0
1013            && line
1014                .chars()
1015                .nth(last_mention_start - 1)
1016                .is_some_and(|c| !c.is_whitespace())
1017        {
1018            return None;
1019        }
1020
1021        let rest_of_line = &line[last_mention_start + 1..];
1022
1023        let mut mode = None;
1024        let mut argument = None;
1025
1026        let mut parts = rest_of_line.split_whitespace();
1027        let mut end = last_mention_start + 1;
1028        if let Some(mode_text) = parts.next() {
1029            end += mode_text.len();
1030
1031            if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok() {
1032                mode = Some(parsed_mode);
1033            } else {
1034                argument = Some(mode_text.to_string());
1035            }
1036            match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1037                Some(whitespace_count) => {
1038                    if let Some(argument_text) = parts.next() {
1039                        argument = Some(argument_text.to_string());
1040                        end += whitespace_count + argument_text.len();
1041                    }
1042                }
1043                None => {
1044                    // Rest of line is entirely whitespace
1045                    end += rest_of_line.len() - mode_text.len();
1046                }
1047            }
1048        }
1049
1050        Some(Self {
1051            source_range: last_mention_start + offset_to_line..end + offset_to_line,
1052            mode,
1053            argument,
1054        })
1055    }
1056}
1057
1058#[cfg(test)]
1059mod tests {
1060    use super::*;
1061    use editor::AnchorRangeExt;
1062    use gpui::{EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext};
1063    use project::{Project, ProjectPath};
1064    use serde_json::json;
1065    use settings::SettingsStore;
1066    use std::{ops::Deref, rc::Rc};
1067    use util::path;
1068    use workspace::{AppState, Item};
1069
1070    #[test]
1071    fn test_mention_completion_parse() {
1072        assert_eq!(MentionCompletion::try_parse("Lorem Ipsum", 0), None);
1073
1074        assert_eq!(
1075            MentionCompletion::try_parse("Lorem @", 0),
1076            Some(MentionCompletion {
1077                source_range: 6..7,
1078                mode: None,
1079                argument: None,
1080            })
1081        );
1082
1083        assert_eq!(
1084            MentionCompletion::try_parse("Lorem @file", 0),
1085            Some(MentionCompletion {
1086                source_range: 6..11,
1087                mode: Some(ContextPickerMode::File),
1088                argument: None,
1089            })
1090        );
1091
1092        assert_eq!(
1093            MentionCompletion::try_parse("Lorem @file ", 0),
1094            Some(MentionCompletion {
1095                source_range: 6..12,
1096                mode: Some(ContextPickerMode::File),
1097                argument: None,
1098            })
1099        );
1100
1101        assert_eq!(
1102            MentionCompletion::try_parse("Lorem @file main.rs", 0),
1103            Some(MentionCompletion {
1104                source_range: 6..19,
1105                mode: Some(ContextPickerMode::File),
1106                argument: Some("main.rs".to_string()),
1107            })
1108        );
1109
1110        assert_eq!(
1111            MentionCompletion::try_parse("Lorem @file main.rs ", 0),
1112            Some(MentionCompletion {
1113                source_range: 6..19,
1114                mode: Some(ContextPickerMode::File),
1115                argument: Some("main.rs".to_string()),
1116            })
1117        );
1118
1119        assert_eq!(
1120            MentionCompletion::try_parse("Lorem @file main.rs Ipsum", 0),
1121            Some(MentionCompletion {
1122                source_range: 6..19,
1123                mode: Some(ContextPickerMode::File),
1124                argument: Some("main.rs".to_string()),
1125            })
1126        );
1127
1128        assert_eq!(
1129            MentionCompletion::try_parse("Lorem @main", 0),
1130            Some(MentionCompletion {
1131                source_range: 6..11,
1132                mode: None,
1133                argument: Some("main".to_string()),
1134            })
1135        );
1136
1137        assert_eq!(MentionCompletion::try_parse("test@", 0), None);
1138    }
1139
1140    struct AtMentionEditor(Entity<Editor>);
1141
1142    impl Item for AtMentionEditor {
1143        type Event = ();
1144
1145        fn include_in_nav_history() -> bool {
1146            false
1147        }
1148
1149        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1150            "Test".into()
1151        }
1152    }
1153
1154    impl EventEmitter<()> for AtMentionEditor {}
1155
1156    impl Focusable for AtMentionEditor {
1157        fn focus_handle(&self, cx: &App) -> FocusHandle {
1158            self.0.read(cx).focus_handle(cx)
1159        }
1160    }
1161
1162    impl Render for AtMentionEditor {
1163        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1164            self.0.clone().into_any_element()
1165        }
1166    }
1167
1168    #[gpui::test]
1169    async fn test_context_completion_provider(cx: &mut TestAppContext) {
1170        init_test(cx);
1171
1172        let app_state = cx.update(AppState::test);
1173
1174        cx.update(|cx| {
1175            language::init(cx);
1176            editor::init(cx);
1177            workspace::init(app_state.clone(), cx);
1178            Project::init_settings(cx);
1179        });
1180
1181        app_state
1182            .fs
1183            .as_fake()
1184            .insert_tree(
1185                path!("/dir"),
1186                json!({
1187                    "editor": "",
1188                    "a": {
1189                        "one.txt": "",
1190                        "two.txt": "",
1191                        "three.txt": "",
1192                        "four.txt": ""
1193                    },
1194                    "b": {
1195                        "five.txt": "",
1196                        "six.txt": "",
1197                        "seven.txt": "",
1198                        "eight.txt": "",
1199                    }
1200                }),
1201            )
1202            .await;
1203
1204        let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1205        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1206        let workspace = window.root(cx).unwrap();
1207
1208        let worktree = project.update(cx, |project, cx| {
1209            let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
1210            assert_eq!(worktrees.len(), 1);
1211            worktrees.pop().unwrap()
1212        });
1213        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
1214
1215        let mut cx = VisualTestContext::from_window(*window.deref(), cx);
1216
1217        let paths = vec![
1218            path!("a/one.txt"),
1219            path!("a/two.txt"),
1220            path!("a/three.txt"),
1221            path!("a/four.txt"),
1222            path!("b/five.txt"),
1223            path!("b/six.txt"),
1224            path!("b/seven.txt"),
1225            path!("b/eight.txt"),
1226        ];
1227
1228        let mut opened_editors = Vec::new();
1229        for path in paths {
1230            let buffer = workspace
1231                .update_in(&mut cx, |workspace, window, cx| {
1232                    workspace.open_path(
1233                        ProjectPath {
1234                            worktree_id,
1235                            path: Path::new(path).into(),
1236                        },
1237                        None,
1238                        false,
1239                        window,
1240                        cx,
1241                    )
1242                })
1243                .await
1244                .unwrap();
1245            opened_editors.push(buffer);
1246        }
1247
1248        let editor = workspace.update_in(&mut cx, |workspace, window, cx| {
1249            let editor = cx.new(|cx| {
1250                Editor::new(
1251                    editor::EditorMode::full(),
1252                    multi_buffer::MultiBuffer::build_simple("", cx),
1253                    None,
1254                    window,
1255                    cx,
1256                )
1257            });
1258            workspace.active_pane().update(cx, |pane, cx| {
1259                pane.add_item(
1260                    Box::new(cx.new(|_| AtMentionEditor(editor.clone()))),
1261                    true,
1262                    true,
1263                    None,
1264                    window,
1265                    cx,
1266                );
1267            });
1268            editor
1269        });
1270
1271        let context_store = cx.new(|_| ContextStore::new(project.downgrade(), None));
1272
1273        let editor_entity = editor.downgrade();
1274        editor.update_in(&mut cx, |editor, window, cx| {
1275            let last_opened_buffer = opened_editors.last().and_then(|editor| {
1276                editor
1277                    .downcast::<Editor>()?
1278                    .read(cx)
1279                    .buffer()
1280                    .read(cx)
1281                    .as_singleton()
1282                    .as_ref()
1283                    .map(Entity::downgrade)
1284            });
1285            window.focus(&editor.focus_handle(cx));
1286            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
1287                workspace.downgrade(),
1288                context_store.downgrade(),
1289                None,
1290                None,
1291                editor_entity,
1292                last_opened_buffer,
1293            ))));
1294        });
1295
1296        cx.simulate_input("Lorem ");
1297
1298        editor.update(&mut cx, |editor, cx| {
1299            assert_eq!(editor.text(cx), "Lorem ");
1300            assert!(!editor.has_visible_completions_menu());
1301        });
1302
1303        cx.simulate_input("@");
1304
1305        editor.update(&mut cx, |editor, cx| {
1306            assert_eq!(editor.text(cx), "Lorem @");
1307            assert!(editor.has_visible_completions_menu());
1308            assert_eq!(
1309                current_completion_labels(editor),
1310                &[
1311                    "seven.txt dir/b/",
1312                    "six.txt dir/b/",
1313                    "five.txt dir/b/",
1314                    "four.txt dir/a/",
1315                    "Files & Directories",
1316                    "Symbols",
1317                    "Fetch"
1318                ]
1319            );
1320        });
1321
1322        // Select and confirm "File"
1323        editor.update_in(&mut cx, |editor, window, cx| {
1324            assert!(editor.has_visible_completions_menu());
1325            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
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.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1330        });
1331
1332        cx.run_until_parked();
1333
1334        editor.update(&mut cx, |editor, cx| {
1335            assert_eq!(editor.text(cx), "Lorem @file ");
1336            assert!(editor.has_visible_completions_menu());
1337        });
1338
1339        cx.simulate_input("one");
1340
1341        editor.update(&mut cx, |editor, cx| {
1342            assert_eq!(editor.text(cx), "Lorem @file one");
1343            assert!(editor.has_visible_completions_menu());
1344            assert_eq!(current_completion_labels(editor), vec!["one.txt dir/a/"]);
1345        });
1346
1347        editor.update_in(&mut cx, |editor, window, cx| {
1348            assert!(editor.has_visible_completions_menu());
1349            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1350        });
1351
1352        editor.update(&mut cx, |editor, cx| {
1353            assert_eq!(editor.text(cx), "Lorem [@one.txt](@file:dir/a/one.txt) ");
1354            assert!(!editor.has_visible_completions_menu());
1355            assert_eq!(
1356                fold_ranges(editor, cx),
1357                vec![Point::new(0, 6)..Point::new(0, 37)]
1358            );
1359        });
1360
1361        cx.simulate_input(" ");
1362
1363        editor.update(&mut cx, |editor, cx| {
1364            assert_eq!(editor.text(cx), "Lorem [@one.txt](@file:dir/a/one.txt)  ");
1365            assert!(!editor.has_visible_completions_menu());
1366            assert_eq!(
1367                fold_ranges(editor, cx),
1368                vec![Point::new(0, 6)..Point::new(0, 37)]
1369            );
1370        });
1371
1372        cx.simulate_input("Ipsum ");
1373
1374        editor.update(&mut cx, |editor, cx| {
1375            assert_eq!(
1376                editor.text(cx),
1377                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum ",
1378            );
1379            assert!(!editor.has_visible_completions_menu());
1380            assert_eq!(
1381                fold_ranges(editor, cx),
1382                vec![Point::new(0, 6)..Point::new(0, 37)]
1383            );
1384        });
1385
1386        cx.simulate_input("@file ");
1387
1388        editor.update(&mut cx, |editor, cx| {
1389            assert_eq!(
1390                editor.text(cx),
1391                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum @file ",
1392            );
1393            assert!(editor.has_visible_completions_menu());
1394            assert_eq!(
1395                fold_ranges(editor, cx),
1396                vec![Point::new(0, 6)..Point::new(0, 37)]
1397            );
1398        });
1399
1400        editor.update_in(&mut cx, |editor, window, cx| {
1401            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1402        });
1403
1404        cx.run_until_parked();
1405
1406        editor.update(&mut cx, |editor, cx| {
1407            assert_eq!(
1408                editor.text(cx),
1409                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) "
1410            );
1411            assert!(!editor.has_visible_completions_menu());
1412            assert_eq!(
1413                fold_ranges(editor, cx),
1414                vec![
1415                    Point::new(0, 6)..Point::new(0, 37),
1416                    Point::new(0, 45)..Point::new(0, 80)
1417                ]
1418            );
1419        });
1420
1421        cx.simulate_input("\n@");
1422
1423        editor.update(&mut cx, |editor, cx| {
1424            assert_eq!(
1425                editor.text(cx),
1426                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) \n@"
1427            );
1428            assert!(editor.has_visible_completions_menu());
1429            assert_eq!(
1430                fold_ranges(editor, cx),
1431                vec![
1432                    Point::new(0, 6)..Point::new(0, 37),
1433                    Point::new(0, 45)..Point::new(0, 80)
1434                ]
1435            );
1436        });
1437
1438        editor.update_in(&mut cx, |editor, window, cx| {
1439            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1440        });
1441
1442        cx.run_until_parked();
1443
1444        editor.update(&mut cx, |editor, cx| {
1445            assert_eq!(
1446                editor.text(cx),
1447                "Lorem [@one.txt](@file:dir/a/one.txt)  Ipsum [@seven.txt](@file:dir/b/seven.txt) \n[@six.txt](@file:dir/b/six.txt) "
1448            );
1449            assert!(!editor.has_visible_completions_menu());
1450            assert_eq!(
1451                fold_ranges(editor, cx),
1452                vec![
1453                    Point::new(0, 6)..Point::new(0, 37),
1454                    Point::new(0, 45)..Point::new(0, 80),
1455                    Point::new(1, 0)..Point::new(1, 31)
1456                ]
1457            );
1458        });
1459    }
1460
1461    fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
1462        let snapshot = editor.buffer().read(cx).snapshot(cx);
1463        editor.display_map.update(cx, |display_map, cx| {
1464            display_map
1465                .snapshot(cx)
1466                .folds_in_range(0..snapshot.len())
1467                .map(|fold| fold.range.to_point(&snapshot))
1468                .collect()
1469        })
1470    }
1471
1472    fn current_completion_labels(editor: &Editor) -> Vec<String> {
1473        let completions = editor.current_completions().expect("Missing completions");
1474        completions
1475            .into_iter()
1476            .map(|completion| completion.label.text)
1477            .collect::<Vec<_>>()
1478    }
1479
1480    pub(crate) fn init_test(cx: &mut TestAppContext) {
1481        cx.update(|cx| {
1482            let store = SettingsStore::test(cx);
1483            cx.set_global(store);
1484            theme::init(theme::LoadThemes::JustBase, cx);
1485            client::init_settings(cx);
1486            language::init(cx);
1487            Project::init_settings(cx);
1488            workspace::init_settings(cx);
1489            editor::init_settings(cx);
1490        });
1491    }
1492}