1use std::cell::RefCell;
2use std::ops::Range;
3use std::path::PathBuf;
4use std::rc::Rc;
5use std::sync::Arc;
6use std::sync::atomic::AtomicBool;
7
8use acp_thread::MentionUri;
9use agent_client_protocol as acp;
10use agent2::{HistoryEntry, HistoryStore};
11use anyhow::Result;
12use editor::{CompletionProvider, Editor, ExcerptId};
13use fuzzy::{StringMatch, StringMatchCandidate};
14use gpui::{App, Entity, Task, WeakEntity};
15use language::{Buffer, CodeLabel, CodeLabelBuilder, HighlightId};
16use lsp::CompletionContext;
17use project::lsp_store::{CompletionDocumentation, SymbolLocation};
18use project::{
19 Completion, CompletionDisplayOptions, CompletionIntent, CompletionResponse, Project,
20 ProjectPath, Symbol, WorktreeId,
21};
22use prompt_store::PromptStore;
23use rope::Point;
24use text::{Anchor, ToPoint as _};
25use ui::prelude::*;
26use util::rel_path::RelPath;
27use workspace::Workspace;
28
29use crate::AgentPanel;
30use crate::acp::message_editor::MessageEditor;
31use crate::context_picker::file_context_picker::{FileMatch, search_files};
32use crate::context_picker::rules_context_picker::{RulesContextEntry, search_rules};
33use crate::context_picker::symbol_context_picker::SymbolMatch;
34use crate::context_picker::symbol_context_picker::search_symbols;
35use crate::context_picker::{
36 ContextPickerAction, ContextPickerEntry, ContextPickerMode, selection_ranges,
37};
38
39pub(crate) enum Match {
40 File(FileMatch),
41 Symbol(SymbolMatch),
42 Thread(HistoryEntry),
43 RecentThread(HistoryEntry),
44 Fetch(SharedString),
45 Rules(RulesContextEntry),
46 Entry(EntryMatch),
47}
48
49pub struct EntryMatch {
50 mat: Option<StringMatch>,
51 entry: ContextPickerEntry,
52}
53
54impl Match {
55 pub fn score(&self) -> f64 {
56 match self {
57 Match::File(file) => file.mat.score,
58 Match::Entry(mode) => mode.mat.as_ref().map(|mat| mat.score).unwrap_or(1.),
59 Match::Thread(_) => 1.,
60 Match::RecentThread(_) => 1.,
61 Match::Symbol(_) => 1.,
62 Match::Rules(_) => 1.,
63 Match::Fetch(_) => 1.,
64 }
65 }
66}
67
68pub struct ContextPickerCompletionProvider {
69 message_editor: WeakEntity<MessageEditor>,
70 workspace: WeakEntity<Workspace>,
71 history_store: Entity<HistoryStore>,
72 prompt_store: Option<Entity<PromptStore>>,
73 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
74 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
75}
76
77impl ContextPickerCompletionProvider {
78 pub fn new(
79 message_editor: WeakEntity<MessageEditor>,
80 workspace: WeakEntity<Workspace>,
81 history_store: Entity<HistoryStore>,
82 prompt_store: Option<Entity<PromptStore>>,
83 prompt_capabilities: Rc<RefCell<acp::PromptCapabilities>>,
84 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
85 ) -> Self {
86 Self {
87 message_editor,
88 workspace,
89 history_store,
90 prompt_store,
91 prompt_capabilities,
92 available_commands,
93 }
94 }
95
96 fn completion_for_entry(
97 entry: ContextPickerEntry,
98 source_range: Range<Anchor>,
99 message_editor: WeakEntity<MessageEditor>,
100 workspace: &Entity<Workspace>,
101 cx: &mut App,
102 ) -> Option<Completion> {
103 match entry {
104 ContextPickerEntry::Mode(mode) => Some(Completion {
105 replace_range: source_range,
106 new_text: format!("@{} ", mode.keyword()),
107 label: CodeLabel::plain(mode.label().to_string(), None),
108 icon_path: Some(mode.icon().path().into()),
109 documentation: None,
110 source: project::CompletionSource::Custom,
111 buffer_match: None,
112 insert_text_mode: None,
113 // This ensures that when a user accepts this completion, the
114 // completion menu will still be shown after "@category " is
115 // inserted
116 confirm: Some(Arc::new(|_, _, _| true)),
117 }),
118 ContextPickerEntry::Action(action) => {
119 Self::completion_for_action(action, source_range, message_editor, workspace, cx)
120 }
121 }
122 }
123
124 fn completion_for_thread(
125 thread_entry: HistoryEntry,
126 source_range: Range<Anchor>,
127 recent: bool,
128 editor: WeakEntity<MessageEditor>,
129 cx: &mut App,
130 ) -> Completion {
131 let uri = thread_entry.mention_uri();
132
133 let icon_for_completion = if recent {
134 IconName::HistoryRerun.path().into()
135 } else {
136 uri.icon_path(cx)
137 };
138
139 let new_text = format!("{} ", uri.as_link());
140
141 let new_text_len = new_text.len();
142 Completion {
143 replace_range: source_range.clone(),
144 new_text,
145 label: CodeLabel::plain(thread_entry.title().to_string(), None),
146 documentation: None,
147 insert_text_mode: None,
148 source: project::CompletionSource::Custom,
149 buffer_match: None,
150 icon_path: Some(icon_for_completion),
151 confirm: Some(confirm_completion_callback(
152 thread_entry.title().clone(),
153 source_range.start,
154 new_text_len - 1,
155 editor,
156 uri,
157 )),
158 }
159 }
160
161 fn completion_for_rules(
162 rule: RulesContextEntry,
163 source_range: Range<Anchor>,
164 editor: WeakEntity<MessageEditor>,
165 cx: &mut App,
166 ) -> Completion {
167 let uri = MentionUri::Rule {
168 id: rule.prompt_id.into(),
169 name: rule.title.to_string(),
170 };
171 let new_text = format!("{} ", uri.as_link());
172 let new_text_len = new_text.len();
173 let icon_path = uri.icon_path(cx);
174 Completion {
175 replace_range: source_range.clone(),
176 new_text,
177 label: CodeLabel::plain(rule.title.to_string(), None),
178 documentation: None,
179 insert_text_mode: None,
180 source: project::CompletionSource::Custom,
181 buffer_match: None,
182 icon_path: Some(icon_path),
183 confirm: Some(confirm_completion_callback(
184 rule.title,
185 source_range.start,
186 new_text_len - 1,
187 editor,
188 uri,
189 )),
190 }
191 }
192
193 pub(crate) fn completion_for_path(
194 project_path: ProjectPath,
195 path_prefix: &RelPath,
196 is_recent: bool,
197 is_directory: bool,
198 source_range: Range<Anchor>,
199 message_editor: WeakEntity<MessageEditor>,
200 project: Entity<Project>,
201 cx: &mut App,
202 ) -> Option<Completion> {
203 let path_style = project.read(cx).path_style(cx);
204 let (file_name, directory) =
205 crate::context_picker::file_context_picker::extract_file_name_and_directory(
206 &project_path.path,
207 path_prefix,
208 path_style,
209 );
210
211 let label =
212 build_code_label_for_full_path(&file_name, directory.as_ref().map(|s| s.as_ref()), cx);
213
214 let abs_path = project.read(cx).absolute_path(&project_path, cx)?;
215
216 let uri = if is_directory {
217 MentionUri::Directory { abs_path }
218 } else {
219 MentionUri::File { abs_path }
220 };
221
222 let crease_icon_path = uri.icon_path(cx);
223 let completion_icon_path = if is_recent {
224 IconName::HistoryRerun.path().into()
225 } else {
226 crease_icon_path
227 };
228
229 let new_text = format!("{} ", uri.as_link());
230 let new_text_len = new_text.len();
231 Some(Completion {
232 replace_range: source_range.clone(),
233 new_text,
234 label,
235 documentation: None,
236 source: project::CompletionSource::Custom,
237 icon_path: Some(completion_icon_path),
238 buffer_match: None,
239 insert_text_mode: None,
240 confirm: Some(confirm_completion_callback(
241 file_name,
242 source_range.start,
243 new_text_len - 1,
244 message_editor,
245 uri,
246 )),
247 })
248 }
249
250 fn completion_for_symbol(
251 symbol: Symbol,
252 source_range: Range<Anchor>,
253 message_editor: WeakEntity<MessageEditor>,
254 workspace: Entity<Workspace>,
255 cx: &mut App,
256 ) -> Option<Completion> {
257 let project = workspace.read(cx).project().clone();
258
259 let label = CodeLabel::plain(symbol.name.clone(), None);
260
261 let abs_path = match &symbol.path {
262 SymbolLocation::InProject(project_path) => {
263 project.read(cx).absolute_path(&project_path, cx)?
264 }
265 SymbolLocation::OutsideProject {
266 abs_path,
267 signature: _,
268 } => PathBuf::from(abs_path.as_ref()),
269 };
270 let uri = MentionUri::Symbol {
271 abs_path,
272 name: symbol.name.clone(),
273 line_range: symbol.range.start.0.row..=symbol.range.end.0.row,
274 };
275 let new_text = format!("{} ", uri.as_link());
276 let new_text_len = new_text.len();
277 let icon_path = uri.icon_path(cx);
278 Some(Completion {
279 replace_range: source_range.clone(),
280 new_text,
281 label,
282 documentation: None,
283 source: project::CompletionSource::Custom,
284 icon_path: Some(icon_path),
285 buffer_match: None,
286 insert_text_mode: None,
287 confirm: Some(confirm_completion_callback(
288 symbol.name.into(),
289 source_range.start,
290 new_text_len - 1,
291 message_editor,
292 uri,
293 )),
294 })
295 }
296
297 fn completion_for_fetch(
298 source_range: Range<Anchor>,
299 url_to_fetch: SharedString,
300 message_editor: WeakEntity<MessageEditor>,
301 cx: &mut App,
302 ) -> Option<Completion> {
303 let new_text = format!("@fetch {} ", url_to_fetch);
304 let url_to_fetch = url::Url::parse(url_to_fetch.as_ref())
305 .or_else(|_| url::Url::parse(&format!("https://{url_to_fetch}")))
306 .ok()?;
307 let mention_uri = MentionUri::Fetch {
308 url: url_to_fetch.clone(),
309 };
310 let icon_path = mention_uri.icon_path(cx);
311 Some(Completion {
312 replace_range: source_range.clone(),
313 new_text: new_text.clone(),
314 label: CodeLabel::plain(url_to_fetch.to_string(), None),
315 documentation: None,
316 source: project::CompletionSource::Custom,
317 icon_path: Some(icon_path),
318 buffer_match: None,
319 insert_text_mode: None,
320 confirm: Some(confirm_completion_callback(
321 url_to_fetch.to_string().into(),
322 source_range.start,
323 new_text.len() - 1,
324 message_editor,
325 mention_uri,
326 )),
327 })
328 }
329
330 pub(crate) fn completion_for_action(
331 action: ContextPickerAction,
332 source_range: Range<Anchor>,
333 message_editor: WeakEntity<MessageEditor>,
334 workspace: &Entity<Workspace>,
335 cx: &mut App,
336 ) -> Option<Completion> {
337 let (new_text, on_action) = match action {
338 ContextPickerAction::AddSelections => {
339 const PLACEHOLDER: &str = "selection ";
340 let selections = selection_ranges(workspace, cx)
341 .into_iter()
342 .enumerate()
343 .map(|(ix, (buffer, range))| {
344 (
345 buffer,
346 range,
347 (PLACEHOLDER.len() * ix)..(PLACEHOLDER.len() * (ix + 1) - 1),
348 )
349 })
350 .collect::<Vec<_>>();
351
352 let new_text: String = PLACEHOLDER.repeat(selections.len());
353
354 let callback = Arc::new({
355 let source_range = source_range.clone();
356 move |_, window: &mut Window, cx: &mut App| {
357 let selections = selections.clone();
358 let message_editor = message_editor.clone();
359 let source_range = source_range.clone();
360 window.defer(cx, move |window, cx| {
361 message_editor
362 .update(cx, |message_editor, cx| {
363 message_editor.confirm_mention_for_selection(
364 source_range,
365 selections,
366 window,
367 cx,
368 )
369 })
370 .ok();
371 });
372 false
373 }
374 });
375
376 (new_text, callback)
377 }
378 };
379
380 Some(Completion {
381 replace_range: source_range,
382 new_text,
383 label: CodeLabel::plain(action.label().to_string(), None),
384 icon_path: Some(action.icon().path().into()),
385 documentation: None,
386 source: project::CompletionSource::Custom,
387 buffer_match: None,
388 insert_text_mode: None,
389 // This ensures that when a user accepts this completion, the
390 // completion menu will still be shown after "@category " is
391 // inserted
392 confirm: Some(on_action),
393 })
394 }
395
396 fn search_slash_commands(
397 &self,
398 query: String,
399 cx: &mut App,
400 ) -> Task<Vec<acp::AvailableCommand>> {
401 let commands = self.available_commands.borrow().clone();
402 if commands.is_empty() {
403 return Task::ready(Vec::new());
404 }
405
406 cx.spawn(async move |cx| {
407 let candidates = commands
408 .iter()
409 .enumerate()
410 .map(|(id, command)| StringMatchCandidate::new(id, &command.name))
411 .collect::<Vec<_>>();
412
413 let matches = fuzzy::match_strings(
414 &candidates,
415 &query,
416 false,
417 true,
418 100,
419 &Arc::new(AtomicBool::default()),
420 cx.background_executor().clone(),
421 )
422 .await;
423
424 matches
425 .into_iter()
426 .map(|mat| commands[mat.candidate_id].clone())
427 .collect()
428 })
429 }
430
431 fn search_mentions(
432 &self,
433 mode: Option<ContextPickerMode>,
434 query: String,
435 cancellation_flag: Arc<AtomicBool>,
436 cx: &mut App,
437 ) -> Task<Vec<Match>> {
438 let Some(workspace) = self.workspace.upgrade() else {
439 return Task::ready(Vec::default());
440 };
441 match mode {
442 Some(ContextPickerMode::File) => {
443 let search_files_task = search_files(query, cancellation_flag, &workspace, cx);
444 cx.background_spawn(async move {
445 search_files_task
446 .await
447 .into_iter()
448 .map(Match::File)
449 .collect()
450 })
451 }
452
453 Some(ContextPickerMode::Symbol) => {
454 let search_symbols_task = search_symbols(query, cancellation_flag, &workspace, cx);
455 cx.background_spawn(async move {
456 search_symbols_task
457 .await
458 .into_iter()
459 .map(Match::Symbol)
460 .collect()
461 })
462 }
463
464 Some(ContextPickerMode::Thread) => {
465 let search_threads_task =
466 search_threads(query, cancellation_flag, &self.history_store, cx);
467 cx.background_spawn(async move {
468 search_threads_task
469 .await
470 .into_iter()
471 .map(Match::Thread)
472 .collect()
473 })
474 }
475
476 Some(ContextPickerMode::Fetch) => {
477 if !query.is_empty() {
478 Task::ready(vec![Match::Fetch(query.into())])
479 } else {
480 Task::ready(Vec::new())
481 }
482 }
483
484 Some(ContextPickerMode::Rules) => {
485 if let Some(prompt_store) = self.prompt_store.as_ref() {
486 let search_rules_task =
487 search_rules(query, cancellation_flag, prompt_store, cx);
488 cx.background_spawn(async move {
489 search_rules_task
490 .await
491 .into_iter()
492 .map(Match::Rules)
493 .collect::<Vec<_>>()
494 })
495 } else {
496 Task::ready(Vec::new())
497 }
498 }
499
500 None if query.is_empty() => {
501 let mut matches = self.recent_context_picker_entries(&workspace, cx);
502
503 matches.extend(
504 self.available_context_picker_entries(&workspace, cx)
505 .into_iter()
506 .map(|mode| {
507 Match::Entry(EntryMatch {
508 entry: mode,
509 mat: None,
510 })
511 }),
512 );
513
514 Task::ready(matches)
515 }
516 None => {
517 let executor = cx.background_executor().clone();
518
519 let search_files_task =
520 search_files(query.clone(), cancellation_flag, &workspace, cx);
521
522 let entries = self.available_context_picker_entries(&workspace, cx);
523 let entry_candidates = entries
524 .iter()
525 .enumerate()
526 .map(|(ix, entry)| StringMatchCandidate::new(ix, entry.keyword()))
527 .collect::<Vec<_>>();
528
529 cx.background_spawn(async move {
530 let mut matches = search_files_task
531 .await
532 .into_iter()
533 .map(Match::File)
534 .collect::<Vec<_>>();
535
536 let entry_matches = fuzzy::match_strings(
537 &entry_candidates,
538 &query,
539 false,
540 true,
541 100,
542 &Arc::new(AtomicBool::default()),
543 executor,
544 )
545 .await;
546
547 matches.extend(entry_matches.into_iter().map(|mat| {
548 Match::Entry(EntryMatch {
549 entry: entries[mat.candidate_id],
550 mat: Some(mat),
551 })
552 }));
553
554 matches.sort_by(|a, b| {
555 b.score()
556 .partial_cmp(&a.score())
557 .unwrap_or(std::cmp::Ordering::Equal)
558 });
559
560 matches
561 })
562 }
563 }
564 }
565
566 fn recent_context_picker_entries(
567 &self,
568 workspace: &Entity<Workspace>,
569 cx: &mut App,
570 ) -> Vec<Match> {
571 let mut recent = Vec::with_capacity(6);
572
573 let mut mentions = self
574 .message_editor
575 .read_with(cx, |message_editor, _cx| message_editor.mentions())
576 .unwrap_or_default();
577 let workspace = workspace.read(cx);
578 let project = workspace.project().read(cx);
579
580 if let Some(agent_panel) = workspace.panel::<AgentPanel>(cx)
581 && let Some(thread) = agent_panel.read(cx).active_agent_thread(cx)
582 {
583 let thread = thread.read(cx);
584 mentions.insert(MentionUri::Thread {
585 id: thread.session_id().clone(),
586 name: thread.title().into(),
587 });
588 }
589
590 recent.extend(
591 workspace
592 .recent_navigation_history_iter(cx)
593 .filter(|(_, abs_path)| {
594 abs_path.as_ref().is_none_or(|path| {
595 !mentions.contains(&MentionUri::File {
596 abs_path: path.clone(),
597 })
598 })
599 })
600 .take(4)
601 .filter_map(|(project_path, _)| {
602 project
603 .worktree_for_id(project_path.worktree_id, cx)
604 .map(|worktree| {
605 let path_prefix = worktree.read(cx).root_name().into();
606 Match::File(FileMatch {
607 mat: fuzzy::PathMatch {
608 score: 1.,
609 positions: Vec::new(),
610 worktree_id: project_path.worktree_id.to_usize(),
611 path: project_path.path,
612 path_prefix,
613 is_dir: false,
614 distance_to_relative_ancestor: 0,
615 },
616 is_recent: true,
617 })
618 })
619 }),
620 );
621
622 if self.prompt_capabilities.borrow().embedded_context {
623 const RECENT_COUNT: usize = 2;
624 let threads = self
625 .history_store
626 .read(cx)
627 .recently_opened_entries(cx)
628 .into_iter()
629 .filter(|thread| !mentions.contains(&thread.mention_uri()))
630 .take(RECENT_COUNT)
631 .collect::<Vec<_>>();
632
633 recent.extend(threads.into_iter().map(Match::RecentThread));
634 }
635
636 recent
637 }
638
639 fn available_context_picker_entries(
640 &self,
641 workspace: &Entity<Workspace>,
642 cx: &mut App,
643 ) -> Vec<ContextPickerEntry> {
644 let embedded_context = self.prompt_capabilities.borrow().embedded_context;
645 let mut entries = if embedded_context {
646 vec![
647 ContextPickerEntry::Mode(ContextPickerMode::File),
648 ContextPickerEntry::Mode(ContextPickerMode::Symbol),
649 ContextPickerEntry::Mode(ContextPickerMode::Thread),
650 ]
651 } else {
652 // File is always available, but we don't need a mode entry
653 vec![]
654 };
655
656 let has_selection = workspace
657 .read(cx)
658 .active_item(cx)
659 .and_then(|item| item.downcast::<Editor>())
660 .is_some_and(|editor| {
661 editor.update(cx, |editor, cx| editor.has_non_empty_selection(cx))
662 });
663 if has_selection {
664 entries.push(ContextPickerEntry::Action(
665 ContextPickerAction::AddSelections,
666 ));
667 }
668
669 if embedded_context {
670 if self.prompt_store.is_some() {
671 entries.push(ContextPickerEntry::Mode(ContextPickerMode::Rules));
672 }
673
674 entries.push(ContextPickerEntry::Mode(ContextPickerMode::Fetch));
675 }
676
677 entries
678 }
679}
680
681fn build_code_label_for_full_path(file_name: &str, directory: Option<&str>, cx: &App) -> CodeLabel {
682 let comment_id = cx.theme().syntax().highlight_id("comment").map(HighlightId);
683 let mut label = CodeLabelBuilder::default();
684
685 label.push_str(file_name, None);
686 label.push_str(" ", None);
687
688 if let Some(directory) = directory {
689 label.push_str(directory, comment_id);
690 }
691
692 label.build()
693}
694
695impl CompletionProvider for ContextPickerCompletionProvider {
696 fn completions(
697 &self,
698 _excerpt_id: ExcerptId,
699 buffer: &Entity<Buffer>,
700 buffer_position: Anchor,
701 _trigger: CompletionContext,
702 _snippets_only: bool,
703 _window: &mut Window,
704 cx: &mut Context<Editor>,
705 ) -> Task<Result<Vec<CompletionResponse>>> {
706 let state = buffer.update(cx, |buffer, _cx| {
707 let position = buffer_position.to_point(buffer);
708 let line_start = Point::new(position.row, 0);
709 let offset_to_line = buffer.point_to_offset(line_start);
710 let mut lines = buffer.text_for_range(line_start..position).lines();
711 let line = lines.next()?;
712 ContextCompletion::try_parse(
713 line,
714 offset_to_line,
715 self.prompt_capabilities.borrow().embedded_context,
716 )
717 });
718 let Some(state) = state else {
719 return Task::ready(Ok(Vec::new()));
720 };
721
722 let Some(workspace) = self.workspace.upgrade() else {
723 return Task::ready(Ok(Vec::new()));
724 };
725
726 let project = workspace.read(cx).project().clone();
727 let snapshot = buffer.read(cx).snapshot();
728 let source_range = snapshot.anchor_before(state.source_range().start)
729 ..snapshot.anchor_after(state.source_range().end);
730
731 let editor = self.message_editor.clone();
732
733 match state {
734 ContextCompletion::SlashCommand(SlashCommandCompletion {
735 command, argument, ..
736 }) => {
737 let search_task = self.search_slash_commands(command.unwrap_or_default(), cx);
738 cx.background_spawn(async move {
739 let completions = search_task
740 .await
741 .into_iter()
742 .map(|command| {
743 let new_text = if let Some(argument) = argument.as_ref() {
744 format!("/{} {}", command.name, argument)
745 } else {
746 format!("/{} ", command.name)
747 };
748
749 let is_missing_argument = argument.is_none() && command.input.is_some();
750 Completion {
751 replace_range: source_range.clone(),
752 new_text,
753 label: CodeLabel::plain(command.name.to_string(), None),
754 documentation: Some(CompletionDocumentation::MultiLinePlainText(
755 command.description.into(),
756 )),
757 source: project::CompletionSource::Custom,
758 icon_path: None,
759 buffer_match: None, // todo! is this right?
760 insert_text_mode: None,
761 confirm: Some(Arc::new({
762 let editor = editor.clone();
763 move |intent, _window, cx| {
764 if !is_missing_argument {
765 cx.defer({
766 let editor = editor.clone();
767 move |cx| {
768 editor
769 .update(cx, |editor, cx| {
770 match intent {
771 CompletionIntent::Complete
772 | CompletionIntent::CompleteWithInsert
773 | CompletionIntent::CompleteWithReplace => {
774 if !is_missing_argument {
775 editor.send(cx);
776 }
777 }
778 CompletionIntent::Compose => {}
779 }
780 })
781 .ok();
782 }
783 });
784 }
785 false
786 }
787 })),
788 }
789 })
790 .collect();
791
792 Ok(vec![CompletionResponse {
793 completions,
794 display_options: CompletionDisplayOptions {
795 dynamic_width: true,
796 },
797 // Since this does its own filtering (see `filter_completions()` returns false),
798 // there is no benefit to computing whether this set of completions is incomplete.
799 is_incomplete: true,
800 }])
801 })
802 }
803 ContextCompletion::Mention(MentionCompletion { mode, argument, .. }) => {
804 let query = argument.unwrap_or_default();
805 let search_task =
806 self.search_mentions(mode, query, Arc::<AtomicBool>::default(), cx);
807
808 cx.spawn(async move |_, cx| {
809 let matches = search_task.await;
810
811 let completions = cx.update(|cx| {
812 matches
813 .into_iter()
814 .filter_map(|mat| match mat {
815 Match::File(FileMatch { mat, is_recent }) => {
816 let project_path = ProjectPath {
817 worktree_id: WorktreeId::from_usize(mat.worktree_id),
818 path: mat.path.clone(),
819 };
820
821 Self::completion_for_path(
822 project_path,
823 &mat.path_prefix,
824 is_recent,
825 mat.is_dir,
826 source_range.clone(),
827 editor.clone(),
828 project.clone(),
829 cx,
830 )
831 }
832
833 Match::Symbol(SymbolMatch { symbol, .. }) => {
834 Self::completion_for_symbol(
835 symbol,
836 source_range.clone(),
837 editor.clone(),
838 workspace.clone(),
839 cx,
840 )
841 }
842
843 Match::Thread(thread) => Some(Self::completion_for_thread(
844 thread,
845 source_range.clone(),
846 false,
847 editor.clone(),
848 cx,
849 )),
850
851 Match::RecentThread(thread) => Some(Self::completion_for_thread(
852 thread,
853 source_range.clone(),
854 true,
855 editor.clone(),
856 cx,
857 )),
858
859 Match::Rules(user_rules) => Some(Self::completion_for_rules(
860 user_rules,
861 source_range.clone(),
862 editor.clone(),
863 cx,
864 )),
865
866 Match::Fetch(url) => Self::completion_for_fetch(
867 source_range.clone(),
868 url,
869 editor.clone(),
870 cx,
871 ),
872
873 Match::Entry(EntryMatch { entry, .. }) => {
874 Self::completion_for_entry(
875 entry,
876 source_range.clone(),
877 editor.clone(),
878 &workspace,
879 cx,
880 )
881 }
882 })
883 .collect()
884 })?;
885
886 Ok(vec![CompletionResponse {
887 completions,
888 display_options: CompletionDisplayOptions {
889 dynamic_width: true,
890 },
891 // Since this does its own filtering (see `filter_completions()` returns false),
892 // there is no benefit to computing whether this set of completions is incomplete.
893 is_incomplete: true,
894 }])
895 })
896 }
897 }
898 }
899
900 fn is_completion_trigger(
901 &self,
902 buffer: &Entity<language::Buffer>,
903 position: language::Anchor,
904 _text: &str,
905 _trigger_in_words: bool,
906 _menu_is_open: bool,
907 cx: &mut Context<Editor>,
908 ) -> bool {
909 let buffer = buffer.read(cx);
910 let position = position.to_point(buffer);
911 let line_start = Point::new(position.row, 0);
912 let offset_to_line = buffer.point_to_offset(line_start);
913 let mut lines = buffer.text_for_range(line_start..position).lines();
914 if let Some(line) = lines.next() {
915 ContextCompletion::try_parse(
916 line,
917 offset_to_line,
918 self.prompt_capabilities.borrow().embedded_context,
919 )
920 .filter(|completion| {
921 // Right now we don't support completing arguments of slash commands
922 let is_slash_command_with_argument = matches!(
923 completion,
924 ContextCompletion::SlashCommand(SlashCommandCompletion {
925 argument: Some(_),
926 ..
927 })
928 );
929 !is_slash_command_with_argument
930 })
931 .map(|completion| {
932 completion.source_range().start <= offset_to_line + position.column as usize
933 && completion.source_range().end >= offset_to_line + position.column as usize
934 })
935 .unwrap_or(false)
936 } else {
937 false
938 }
939 }
940
941 fn sort_completions(&self) -> bool {
942 false
943 }
944
945 fn filter_completions(&self) -> bool {
946 false
947 }
948}
949
950pub(crate) fn search_threads(
951 query: String,
952 cancellation_flag: Arc<AtomicBool>,
953 history_store: &Entity<HistoryStore>,
954 cx: &mut App,
955) -> Task<Vec<HistoryEntry>> {
956 let threads = history_store.read(cx).entries().collect();
957 if query.is_empty() {
958 return Task::ready(threads);
959 }
960
961 let executor = cx.background_executor().clone();
962 cx.background_spawn(async move {
963 let candidates = threads
964 .iter()
965 .enumerate()
966 .map(|(id, thread)| StringMatchCandidate::new(id, thread.title()))
967 .collect::<Vec<_>>();
968 let matches = fuzzy::match_strings(
969 &candidates,
970 &query,
971 false,
972 true,
973 100,
974 &cancellation_flag,
975 executor,
976 )
977 .await;
978
979 matches
980 .into_iter()
981 .map(|mat| threads[mat.candidate_id].clone())
982 .collect()
983 })
984}
985
986fn confirm_completion_callback(
987 crease_text: SharedString,
988 start: Anchor,
989 content_len: usize,
990 message_editor: WeakEntity<MessageEditor>,
991 mention_uri: MentionUri,
992) -> Arc<dyn Fn(CompletionIntent, &mut Window, &mut App) -> bool + Send + Sync> {
993 Arc::new(move |_, window, cx| {
994 let message_editor = message_editor.clone();
995 let crease_text = crease_text.clone();
996 let mention_uri = mention_uri.clone();
997 window.defer(cx, move |window, cx| {
998 message_editor
999 .clone()
1000 .update(cx, |message_editor, cx| {
1001 message_editor
1002 .confirm_mention_completion(
1003 crease_text,
1004 start,
1005 content_len,
1006 mention_uri,
1007 window,
1008 cx,
1009 )
1010 .detach();
1011 })
1012 .ok();
1013 });
1014 false
1015 })
1016}
1017
1018enum ContextCompletion {
1019 SlashCommand(SlashCommandCompletion),
1020 Mention(MentionCompletion),
1021}
1022
1023impl ContextCompletion {
1024 fn source_range(&self) -> Range<usize> {
1025 match self {
1026 Self::SlashCommand(completion) => completion.source_range.clone(),
1027 Self::Mention(completion) => completion.source_range.clone(),
1028 }
1029 }
1030
1031 fn try_parse(line: &str, offset_to_line: usize, allow_non_file_mentions: bool) -> Option<Self> {
1032 if let Some(command) = SlashCommandCompletion::try_parse(line, offset_to_line) {
1033 Some(Self::SlashCommand(command))
1034 } else if let Some(mention) =
1035 MentionCompletion::try_parse(allow_non_file_mentions, line, offset_to_line)
1036 {
1037 Some(Self::Mention(mention))
1038 } else {
1039 None
1040 }
1041 }
1042}
1043
1044#[derive(Debug, Default, PartialEq)]
1045pub struct SlashCommandCompletion {
1046 pub source_range: Range<usize>,
1047 pub command: Option<String>,
1048 pub argument: Option<String>,
1049}
1050
1051impl SlashCommandCompletion {
1052 pub fn try_parse(line: &str, offset_to_line: usize) -> Option<Self> {
1053 // If we decide to support commands that are not at the beginning of the prompt, we can remove this check
1054 if !line.starts_with('/') || offset_to_line != 0 {
1055 return None;
1056 }
1057
1058 let (prefix, last_command) = line.rsplit_once('/')?;
1059 if prefix.chars().last().is_some_and(|c| !c.is_whitespace())
1060 || last_command.starts_with(char::is_whitespace)
1061 {
1062 return None;
1063 }
1064
1065 let mut argument = None;
1066 let mut command = None;
1067 if let Some((command_text, args)) = last_command.split_once(char::is_whitespace) {
1068 if !args.is_empty() {
1069 argument = Some(args.trim_end().to_string());
1070 }
1071 command = Some(command_text.to_string());
1072 } else if !last_command.is_empty() {
1073 command = Some(last_command.to_string());
1074 };
1075
1076 Some(Self {
1077 source_range: prefix.len() + offset_to_line
1078 ..line
1079 .rfind(|c: char| !c.is_whitespace())
1080 .unwrap_or_else(|| line.len())
1081 + 1
1082 + offset_to_line,
1083 command,
1084 argument,
1085 })
1086 }
1087}
1088
1089#[derive(Debug, Default, PartialEq)]
1090struct MentionCompletion {
1091 source_range: Range<usize>,
1092 mode: Option<ContextPickerMode>,
1093 argument: Option<String>,
1094}
1095
1096impl MentionCompletion {
1097 fn try_parse(allow_non_file_mentions: bool, line: &str, offset_to_line: usize) -> Option<Self> {
1098 let last_mention_start = line.rfind('@')?;
1099
1100 // No whitespace immediately after '@'
1101 if line[last_mention_start + 1..]
1102 .chars()
1103 .next()
1104 .is_some_and(|c| c.is_whitespace())
1105 {
1106 return None;
1107 }
1108
1109 // Must be a word boundary before '@'
1110 if last_mention_start > 0
1111 && line[..last_mention_start]
1112 .chars()
1113 .last()
1114 .is_some_and(|c| !c.is_whitespace())
1115 {
1116 return None;
1117 }
1118
1119 let rest_of_line = &line[last_mention_start + 1..];
1120
1121 let mut mode = None;
1122 let mut argument = None;
1123
1124 let mut parts = rest_of_line.split_whitespace();
1125 let mut end = last_mention_start + 1;
1126
1127 if let Some(mode_text) = parts.next() {
1128 // Safe since we check no leading whitespace above
1129 end += mode_text.len();
1130
1131 if let Some(parsed_mode) = ContextPickerMode::try_from(mode_text).ok()
1132 && (allow_non_file_mentions || matches!(parsed_mode, ContextPickerMode::File))
1133 {
1134 mode = Some(parsed_mode);
1135 } else {
1136 argument = Some(mode_text.to_string());
1137 }
1138 match rest_of_line[mode_text.len()..].find(|c: char| !c.is_whitespace()) {
1139 Some(whitespace_count) => {
1140 if let Some(argument_text) = parts.next() {
1141 // If mode wasn't recognized but we have an argument, don't suggest completions
1142 // (e.g. '@something word')
1143 if mode.is_none() && !argument_text.is_empty() {
1144 return None;
1145 }
1146
1147 argument = Some(argument_text.to_string());
1148 end += whitespace_count + argument_text.len();
1149 }
1150 }
1151 None => {
1152 // Rest of line is entirely whitespace
1153 end += rest_of_line.len() - mode_text.len();
1154 }
1155 }
1156 }
1157
1158 Some(Self {
1159 source_range: last_mention_start + offset_to_line..end + offset_to_line,
1160 mode,
1161 argument,
1162 })
1163 }
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168 use super::*;
1169
1170 #[test]
1171 fn test_slash_command_completion_parse() {
1172 assert_eq!(
1173 SlashCommandCompletion::try_parse("/", 0),
1174 Some(SlashCommandCompletion {
1175 source_range: 0..1,
1176 command: None,
1177 argument: None,
1178 })
1179 );
1180
1181 assert_eq!(
1182 SlashCommandCompletion::try_parse("/help", 0),
1183 Some(SlashCommandCompletion {
1184 source_range: 0..5,
1185 command: Some("help".to_string()),
1186 argument: None,
1187 })
1188 );
1189
1190 assert_eq!(
1191 SlashCommandCompletion::try_parse("/help ", 0),
1192 Some(SlashCommandCompletion {
1193 source_range: 0..5,
1194 command: Some("help".to_string()),
1195 argument: None,
1196 })
1197 );
1198
1199 assert_eq!(
1200 SlashCommandCompletion::try_parse("/help arg1", 0),
1201 Some(SlashCommandCompletion {
1202 source_range: 0..10,
1203 command: Some("help".to_string()),
1204 argument: Some("arg1".to_string()),
1205 })
1206 );
1207
1208 assert_eq!(
1209 SlashCommandCompletion::try_parse("/help arg1 arg2", 0),
1210 Some(SlashCommandCompletion {
1211 source_range: 0..15,
1212 command: Some("help".to_string()),
1213 argument: Some("arg1 arg2".to_string()),
1214 })
1215 );
1216
1217 assert_eq!(
1218 SlashCommandCompletion::try_parse("/拿不到命令 拿不到命令 ", 0),
1219 Some(SlashCommandCompletion {
1220 source_range: 0..30,
1221 command: Some("拿不到命令".to_string()),
1222 argument: Some("拿不到命令".to_string()),
1223 })
1224 );
1225
1226 assert_eq!(SlashCommandCompletion::try_parse("Lorem Ipsum", 0), None);
1227
1228 assert_eq!(SlashCommandCompletion::try_parse("Lorem /", 0), None);
1229
1230 assert_eq!(SlashCommandCompletion::try_parse("Lorem /help", 0), None);
1231
1232 assert_eq!(SlashCommandCompletion::try_parse("Lorem/", 0), None);
1233
1234 assert_eq!(SlashCommandCompletion::try_parse("/ ", 0), None);
1235 }
1236
1237 #[test]
1238 fn test_mention_completion_parse() {
1239 assert_eq!(MentionCompletion::try_parse(true, "Lorem Ipsum", 0), None);
1240
1241 assert_eq!(
1242 MentionCompletion::try_parse(true, "Lorem @", 0),
1243 Some(MentionCompletion {
1244 source_range: 6..7,
1245 mode: None,
1246 argument: None,
1247 })
1248 );
1249
1250 assert_eq!(
1251 MentionCompletion::try_parse(true, "Lorem @file", 0),
1252 Some(MentionCompletion {
1253 source_range: 6..11,
1254 mode: Some(ContextPickerMode::File),
1255 argument: None,
1256 })
1257 );
1258
1259 assert_eq!(
1260 MentionCompletion::try_parse(true, "Lorem @file ", 0),
1261 Some(MentionCompletion {
1262 source_range: 6..12,
1263 mode: Some(ContextPickerMode::File),
1264 argument: None,
1265 })
1266 );
1267
1268 assert_eq!(
1269 MentionCompletion::try_parse(true, "Lorem @file main.rs", 0),
1270 Some(MentionCompletion {
1271 source_range: 6..19,
1272 mode: Some(ContextPickerMode::File),
1273 argument: Some("main.rs".to_string()),
1274 })
1275 );
1276
1277 assert_eq!(
1278 MentionCompletion::try_parse(true, "Lorem @file main.rs ", 0),
1279 Some(MentionCompletion {
1280 source_range: 6..19,
1281 mode: Some(ContextPickerMode::File),
1282 argument: Some("main.rs".to_string()),
1283 })
1284 );
1285
1286 assert_eq!(
1287 MentionCompletion::try_parse(true, "Lorem @file main.rs Ipsum", 0),
1288 Some(MentionCompletion {
1289 source_range: 6..19,
1290 mode: Some(ContextPickerMode::File),
1291 argument: Some("main.rs".to_string()),
1292 })
1293 );
1294
1295 assert_eq!(
1296 MentionCompletion::try_parse(true, "Lorem @main", 0),
1297 Some(MentionCompletion {
1298 source_range: 6..11,
1299 mode: None,
1300 argument: Some("main".to_string()),
1301 })
1302 );
1303
1304 assert_eq!(
1305 MentionCompletion::try_parse(true, "Lorem @main ", 0),
1306 Some(MentionCompletion {
1307 source_range: 6..12,
1308 mode: None,
1309 argument: Some("main".to_string()),
1310 })
1311 );
1312
1313 assert_eq!(MentionCompletion::try_parse(true, "Lorem @main m", 0), None);
1314
1315 assert_eq!(MentionCompletion::try_parse(true, "test@", 0), None);
1316
1317 // Allowed non-file mentions
1318
1319 assert_eq!(
1320 MentionCompletion::try_parse(true, "Lorem @symbol main", 0),
1321 Some(MentionCompletion {
1322 source_range: 6..18,
1323 mode: Some(ContextPickerMode::Symbol),
1324 argument: Some("main".to_string()),
1325 })
1326 );
1327
1328 // Disallowed non-file mentions
1329 assert_eq!(
1330 MentionCompletion::try_parse(false, "Lorem @symbol main", 0),
1331 None
1332 );
1333
1334 assert_eq!(
1335 MentionCompletion::try_parse(true, "Lorem@symbol", 0),
1336 None,
1337 "Should not parse mention inside word"
1338 );
1339
1340 assert_eq!(
1341 MentionCompletion::try_parse(true, "Lorem @ file", 0),
1342 None,
1343 "Should not parse with a space after @"
1344 );
1345
1346 assert_eq!(
1347 MentionCompletion::try_parse(true, "@ file", 0),
1348 None,
1349 "Should not parse with a space after @ at the start of the line"
1350 );
1351 }
1352}