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