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