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