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