1use crate::context_editor::ContextEditor;
2use anyhow::Result;
3pub use assistant_slash_command::SlashCommand;
4use assistant_slash_command::{AfterCompletion, SlashCommandLine, SlashCommandWorkingSet};
5use editor::{CompletionProvider, Editor};
6use fuzzy::{match_strings, StringMatchCandidate};
7use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity, Window};
8use language::{Anchor, Buffer, ToPoint};
9use parking_lot::Mutex;
10use project::{lsp_store::CompletionDocumentation, CompletionIntent, CompletionSource};
11use rope::Point;
12use std::{
13 cell::RefCell,
14 ops::Range,
15 rc::Rc,
16 sync::{
17 atomic::{AtomicBool, Ordering::SeqCst},
18 Arc,
19 },
20};
21use workspace::Workspace;
22
23pub struct SlashCommandCompletionProvider {
24 cancel_flag: Mutex<Arc<AtomicBool>>,
25 slash_commands: Arc<SlashCommandWorkingSet>,
26 editor: Option<WeakEntity<ContextEditor>>,
27 workspace: Option<WeakEntity<Workspace>>,
28}
29
30impl SlashCommandCompletionProvider {
31 pub fn new(
32 slash_commands: Arc<SlashCommandWorkingSet>,
33 editor: Option<WeakEntity<ContextEditor>>,
34 workspace: Option<WeakEntity<Workspace>>,
35 ) -> Self {
36 Self {
37 cancel_flag: Mutex::new(Arc::new(AtomicBool::new(false))),
38 slash_commands,
39 editor,
40 workspace,
41 }
42 }
43
44 fn complete_command_name(
45 &self,
46 command_name: &str,
47 command_range: Range<Anchor>,
48 name_range: Range<Anchor>,
49 window: &mut Window,
50 cx: &mut App,
51 ) -> Task<Result<Vec<project::Completion>>> {
52 let slash_commands = self.slash_commands.clone();
53 let candidates = slash_commands
54 .command_names(cx)
55 .into_iter()
56 .enumerate()
57 .map(|(ix, def)| StringMatchCandidate::new(ix, &def))
58 .collect::<Vec<_>>();
59 let command_name = command_name.to_string();
60 let editor = self.editor.clone();
61 let workspace = self.workspace.clone();
62 window.spawn(cx, |mut cx| async move {
63 let matches = match_strings(
64 &candidates,
65 &command_name,
66 true,
67 usize::MAX,
68 &Default::default(),
69 cx.background_executor().clone(),
70 )
71 .await;
72
73 cx.update(|_, cx| {
74 matches
75 .into_iter()
76 .filter_map(|mat| {
77 let command = slash_commands.command(&mat.string, cx)?;
78 let mut new_text = mat.string.clone();
79 let requires_argument = command.requires_argument();
80 let accepts_arguments = command.accepts_arguments();
81 if requires_argument || accepts_arguments {
82 new_text.push(' ');
83 }
84
85 let confirm =
86 editor
87 .clone()
88 .zip(workspace.clone())
89 .map(|(editor, workspace)| {
90 let command_name = mat.string.clone();
91 let command_range = command_range.clone();
92 let editor = editor.clone();
93 let workspace = workspace.clone();
94 Arc::new(
95 move |intent: CompletionIntent,
96 window: &mut Window,
97 cx: &mut App| {
98 if !requires_argument
99 && (!accepts_arguments || intent.is_complete())
100 {
101 editor
102 .update(cx, |editor, cx| {
103 editor.run_command(
104 command_range.clone(),
105 &command_name,
106 &[],
107 true,
108 workspace.clone(),
109 window,
110 cx,
111 );
112 })
113 .ok();
114 false
115 } else {
116 requires_argument || accepts_arguments
117 }
118 },
119 ) as Arc<_>
120 });
121 Some(project::Completion {
122 old_range: name_range.clone(),
123 documentation: Some(CompletionDocumentation::SingleLine(
124 command.description().into(),
125 )),
126 new_text,
127 label: command.label(cx),
128 confirm,
129 source: CompletionSource::Custom,
130 })
131 })
132 .collect()
133 })
134 })
135 }
136
137 fn complete_command_argument(
138 &self,
139 command_name: &str,
140 arguments: &[String],
141 command_range: Range<Anchor>,
142 argument_range: Range<Anchor>,
143 last_argument_range: Range<Anchor>,
144 window: &mut Window,
145 cx: &mut App,
146 ) -> Task<Result<Vec<project::Completion>>> {
147 let new_cancel_flag = Arc::new(AtomicBool::new(false));
148 let mut flag = self.cancel_flag.lock();
149 flag.store(true, SeqCst);
150 *flag = new_cancel_flag.clone();
151 if let Some(command) = self.slash_commands.command(command_name, cx) {
152 let completions = command.complete_argument(
153 arguments,
154 new_cancel_flag.clone(),
155 self.workspace.clone(),
156 window,
157 cx,
158 );
159 let command_name: Arc<str> = command_name.into();
160 let editor = self.editor.clone();
161 let workspace = self.workspace.clone();
162 let arguments = arguments.to_vec();
163 cx.background_spawn(async move {
164 Ok(completions
165 .await?
166 .into_iter()
167 .map(|new_argument| {
168 let confirm =
169 editor
170 .clone()
171 .zip(workspace.clone())
172 .map(|(editor, workspace)| {
173 Arc::new({
174 let mut completed_arguments = arguments.clone();
175 if new_argument.replace_previous_arguments {
176 completed_arguments.clear();
177 } else {
178 completed_arguments.pop();
179 }
180 completed_arguments.push(new_argument.new_text.clone());
181
182 let command_range = command_range.clone();
183 let command_name = command_name.clone();
184 move |intent: CompletionIntent,
185 window: &mut Window,
186 cx: &mut App| {
187 if new_argument.after_completion.run()
188 || intent.is_complete()
189 {
190 editor
191 .update(cx, |editor, cx| {
192 editor.run_command(
193 command_range.clone(),
194 &command_name,
195 &completed_arguments,
196 true,
197 workspace.clone(),
198 window,
199 cx,
200 );
201 })
202 .ok();
203 false
204 } else {
205 !new_argument.after_completion.run()
206 }
207 }
208 }) as Arc<_>
209 });
210
211 let mut new_text = new_argument.new_text.clone();
212 if new_argument.after_completion == AfterCompletion::Continue {
213 new_text.push(' ');
214 }
215
216 project::Completion {
217 old_range: if new_argument.replace_previous_arguments {
218 argument_range.clone()
219 } else {
220 last_argument_range.clone()
221 },
222 label: new_argument.label,
223 new_text,
224 documentation: None,
225 confirm,
226 source: CompletionSource::Custom,
227 }
228 })
229 .collect())
230 })
231 } else {
232 Task::ready(Ok(Vec::new()))
233 }
234 }
235}
236
237impl CompletionProvider for SlashCommandCompletionProvider {
238 fn completions(
239 &self,
240 buffer: &Entity<Buffer>,
241 buffer_position: Anchor,
242 _: editor::CompletionContext,
243 window: &mut Window,
244 cx: &mut Context<Editor>,
245 ) -> Task<Result<Vec<project::Completion>>> {
246 let Some((name, arguments, command_range, last_argument_range)) =
247 buffer.update(cx, |buffer, _cx| {
248 let position = buffer_position.to_point(buffer);
249 let line_start = Point::new(position.row, 0);
250 let mut lines = buffer.text_for_range(line_start..position).lines();
251 let line = lines.next()?;
252 let call = SlashCommandLine::parse(line)?;
253
254 let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
255 let command_range_end = Point::new(
256 position.row,
257 call.arguments.last().map_or(call.name.end, |arg| arg.end) as u32,
258 );
259 let command_range = buffer.anchor_after(command_range_start)
260 ..buffer.anchor_after(command_range_end);
261
262 let name = line[call.name.clone()].to_string();
263 let (arguments, last_argument_range) = if let Some(argument) = call.arguments.last()
264 {
265 let last_arg_start =
266 buffer.anchor_after(Point::new(position.row, argument.start as u32));
267 let first_arg_start = call.arguments.first().expect("we have the last element");
268 let first_arg_start =
269 buffer.anchor_after(Point::new(position.row, first_arg_start.start as u32));
270 let arguments = call
271 .arguments
272 .iter()
273 .filter_map(|argument| Some(line.get(argument.clone())?.to_string()))
274 .collect::<Vec<_>>();
275 let argument_range = first_arg_start..buffer_position;
276 (
277 Some((arguments, argument_range)),
278 last_arg_start..buffer_position,
279 )
280 } else {
281 let start =
282 buffer.anchor_after(Point::new(position.row, call.name.start as u32));
283 (None, start..buffer_position)
284 };
285
286 Some((name, arguments, command_range, last_argument_range))
287 })
288 else {
289 return Task::ready(Ok(Vec::new()));
290 };
291
292 if let Some((arguments, argument_range)) = arguments {
293 self.complete_command_argument(
294 &name,
295 &arguments,
296 command_range,
297 argument_range,
298 last_argument_range,
299 window,
300 cx,
301 )
302 } else {
303 self.complete_command_name(&name, command_range, last_argument_range, window, cx)
304 }
305 }
306
307 fn resolve_completions(
308 &self,
309 _: Entity<Buffer>,
310 _: Vec<usize>,
311 _: Rc<RefCell<Box<[project::Completion]>>>,
312 _: &mut Context<Editor>,
313 ) -> Task<Result<bool>> {
314 Task::ready(Ok(true))
315 }
316
317 fn is_completion_trigger(
318 &self,
319 buffer: &Entity<Buffer>,
320 position: language::Anchor,
321 _text: &str,
322 _trigger_in_words: bool,
323 cx: &mut Context<Editor>,
324 ) -> bool {
325 let buffer = buffer.read(cx);
326 let position = position.to_point(buffer);
327 let line_start = Point::new(position.row, 0);
328 let mut lines = buffer.text_for_range(line_start..position).lines();
329 if let Some(line) = lines.next() {
330 SlashCommandLine::parse(line).is_some()
331 } else {
332 false
333 }
334 }
335
336 fn sort_completions(&self) -> bool {
337 false
338 }
339}