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