1use crate::assistant_panel::ContextEditor;
2use anyhow::Result;
3use assistant_slash_command::AfterCompletion;
4pub use assistant_slash_command::{SlashCommand, SlashCommandOutput, SlashCommandRegistry};
5use editor::{CompletionProvider, Editor};
6use fuzzy::{match_strings, StringMatchCandidate};
7use gpui::{AppContext, Model, Task, ViewContext, WeakView, WindowContext};
8use language::{Anchor, Buffer, CodeLabel, Documentation, HighlightId, LanguageServerId, ToPoint};
9use parking_lot::{Mutex, RwLock};
10use project::CompletionIntent;
11use rope::Point;
12use std::{
13 ops::Range,
14 sync::{
15 atomic::{AtomicBool, Ordering::SeqCst},
16 Arc,
17 },
18};
19use ui::ActiveTheme;
20use workspace::Workspace;
21
22pub mod context_server_command;
23pub mod default_command;
24pub mod diagnostics_command;
25pub mod docs_command;
26pub mod fetch_command;
27pub mod file_command;
28pub mod now_command;
29pub mod project_command;
30pub mod prompt_command;
31pub mod search_command;
32pub mod symbols_command;
33pub mod tab_command;
34pub mod terminal_command;
35pub mod workflow_command;
36
37pub(crate) struct SlashCommandCompletionProvider {
38 cancel_flag: Mutex<Arc<AtomicBool>>,
39 editor: Option<WeakView<ContextEditor>>,
40 workspace: Option<WeakView<Workspace>>,
41}
42
43pub(crate) struct SlashCommandLine {
44 /// The range within the line containing the command name.
45 pub name: Range<usize>,
46 /// Ranges within the line containing the command arguments.
47 pub arguments: Vec<Range<usize>>,
48}
49
50impl SlashCommandCompletionProvider {
51 pub fn new(
52 editor: Option<WeakView<ContextEditor>>,
53 workspace: Option<WeakView<Workspace>>,
54 ) -> Self {
55 Self {
56 cancel_flag: Mutex::new(Arc::new(AtomicBool::new(false))),
57 editor,
58 workspace,
59 }
60 }
61
62 fn complete_command_name(
63 &self,
64 command_name: &str,
65 command_range: Range<Anchor>,
66 name_range: Range<Anchor>,
67 cx: &mut WindowContext,
68 ) -> Task<Result<Vec<project::Completion>>> {
69 let commands = SlashCommandRegistry::global(cx);
70 let candidates = commands
71 .command_names()
72 .into_iter()
73 .enumerate()
74 .map(|(ix, def)| StringMatchCandidate {
75 id: ix,
76 string: def.to_string(),
77 char_bag: def.as_ref().into(),
78 })
79 .collect::<Vec<_>>();
80 let command_name = command_name.to_string();
81 let editor = self.editor.clone();
82 let workspace = self.workspace.clone();
83 cx.spawn(|mut cx| async move {
84 let matches = match_strings(
85 &candidates,
86 &command_name,
87 true,
88 usize::MAX,
89 &Default::default(),
90 cx.background_executor().clone(),
91 )
92 .await;
93
94 cx.update(|cx| {
95 matches
96 .into_iter()
97 .filter_map(|mat| {
98 let command = commands.command(&mat.string)?;
99 let mut new_text = mat.string.clone();
100 let requires_argument = command.requires_argument();
101 let accepts_arguments = command.accepts_arguments();
102 if requires_argument || accepts_arguments {
103 new_text.push(' ');
104 }
105
106 let confirm =
107 editor
108 .clone()
109 .zip(workspace.clone())
110 .map(|(editor, workspace)| {
111 let command_name = mat.string.clone();
112 let command_range = command_range.clone();
113 let editor = editor.clone();
114 let workspace = workspace.clone();
115 Arc::new(
116 move |intent: CompletionIntent, cx: &mut WindowContext| {
117 if !requires_argument
118 && (!accepts_arguments || intent.is_complete())
119 {
120 editor
121 .update(cx, |editor, cx| {
122 editor.run_command(
123 command_range.clone(),
124 &command_name,
125 &[],
126 true,
127 workspace.clone(),
128 cx,
129 );
130 })
131 .ok();
132 false
133 } else {
134 requires_argument || accepts_arguments
135 }
136 },
137 ) as Arc<_>
138 });
139 Some(project::Completion {
140 old_range: name_range.clone(),
141 documentation: Some(Documentation::SingleLine(command.description())),
142 new_text,
143 label: command.label(cx),
144 server_id: LanguageServerId(0),
145 lsp_completion: Default::default(),
146 confirm,
147 })
148 })
149 .collect()
150 })
151 })
152 }
153
154 fn complete_command_argument(
155 &self,
156 command_name: &str,
157 arguments: &[String],
158 command_range: Range<Anchor>,
159 argument_range: Range<Anchor>,
160 last_argument_range: Range<Anchor>,
161 cx: &mut WindowContext,
162 ) -> Task<Result<Vec<project::Completion>>> {
163 let new_cancel_flag = Arc::new(AtomicBool::new(false));
164 let mut flag = self.cancel_flag.lock();
165 flag.store(true, SeqCst);
166 *flag = new_cancel_flag.clone();
167 let commands = SlashCommandRegistry::global(cx);
168 if let Some(command) = commands.command(command_name) {
169 let completions = command.complete_argument(
170 arguments,
171 new_cancel_flag.clone(),
172 self.workspace.clone(),
173 cx,
174 );
175 let command_name: Arc<str> = command_name.into();
176 let editor = self.editor.clone();
177 let workspace = self.workspace.clone();
178 let arguments = arguments.to_vec();
179 cx.background_executor().spawn(async move {
180 Ok(completions
181 .await?
182 .into_iter()
183 .map(|new_argument| {
184 let confirm =
185 editor
186 .clone()
187 .zip(workspace.clone())
188 .map(|(editor, workspace)| {
189 Arc::new({
190 let mut completed_arguments = arguments.clone();
191 if new_argument.replace_previous_arguments {
192 completed_arguments.clear();
193 } else {
194 completed_arguments.pop();
195 }
196 completed_arguments.push(new_argument.new_text.clone());
197
198 let command_range = command_range.clone();
199 let command_name = command_name.clone();
200 move |intent: CompletionIntent, cx: &mut WindowContext| {
201 if new_argument.after_completion.run()
202 || intent.is_complete()
203 {
204 editor
205 .update(cx, |editor, cx| {
206 editor.run_command(
207 command_range.clone(),
208 &command_name,
209 &completed_arguments,
210 true,
211 workspace.clone(),
212 cx,
213 );
214 })
215 .ok();
216 false
217 } else {
218 !new_argument.after_completion.run()
219 }
220 }
221 }) as Arc<_>
222 });
223
224 let mut new_text = new_argument.new_text.clone();
225 if new_argument.after_completion == AfterCompletion::Continue {
226 new_text.push(' ');
227 }
228
229 project::Completion {
230 old_range: if new_argument.replace_previous_arguments {
231 argument_range.clone()
232 } else {
233 last_argument_range.clone()
234 },
235 label: new_argument.label,
236 new_text,
237 documentation: None,
238 server_id: LanguageServerId(0),
239 lsp_completion: Default::default(),
240 confirm,
241 }
242 })
243 .collect())
244 })
245 } else {
246 Task::ready(Ok(Vec::new()))
247 }
248 }
249}
250
251impl CompletionProvider for SlashCommandCompletionProvider {
252 fn completions(
253 &self,
254 buffer: &Model<Buffer>,
255 buffer_position: Anchor,
256 _: editor::CompletionContext,
257 cx: &mut ViewContext<Editor>,
258 ) -> Task<Result<Vec<project::Completion>>> {
259 let Some((name, arguments, command_range, last_argument_range)) =
260 buffer.update(cx, |buffer, _cx| {
261 let position = buffer_position.to_point(buffer);
262 let line_start = Point::new(position.row, 0);
263 let mut lines = buffer.text_for_range(line_start..position).lines();
264 let line = lines.next()?;
265 let call = SlashCommandLine::parse(line)?;
266
267 let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
268 let command_range_end = Point::new(
269 position.row,
270 call.arguments.last().map_or(call.name.end, |arg| arg.end) as u32,
271 );
272 let command_range = buffer.anchor_after(command_range_start)
273 ..buffer.anchor_after(command_range_end);
274
275 let name = line[call.name.clone()].to_string();
276 let (arguments, last_argument_range) = if let Some(argument) = call.arguments.last()
277 {
278 let last_arg_start =
279 buffer.anchor_after(Point::new(position.row, argument.start as u32));
280 let first_arg_start = call.arguments.first().expect("we have the last element");
281 let first_arg_start =
282 buffer.anchor_after(Point::new(position.row, first_arg_start.start as u32));
283 let arguments = call
284 .arguments
285 .iter()
286 .filter_map(|argument| Some(line.get(argument.clone())?.to_string()))
287 .collect::<Vec<_>>();
288 let argument_range = first_arg_start..buffer_position;
289 (
290 Some((arguments, argument_range)),
291 last_arg_start..buffer_position,
292 )
293 } else {
294 let start =
295 buffer.anchor_after(Point::new(position.row, call.name.start as u32));
296 (None, start..buffer_position)
297 };
298
299 Some((name, arguments, command_range, last_argument_range))
300 })
301 else {
302 return Task::ready(Ok(Vec::new()));
303 };
304
305 if let Some((arguments, argument_range)) = arguments {
306 self.complete_command_argument(
307 &name,
308 &arguments,
309 command_range,
310 argument_range,
311 last_argument_range,
312 cx,
313 )
314 } else {
315 self.complete_command_name(&name, command_range, last_argument_range, cx)
316 }
317 }
318
319 fn resolve_completions(
320 &self,
321 _: Model<Buffer>,
322 _: Vec<usize>,
323 _: Arc<RwLock<Box<[project::Completion]>>>,
324 _: &mut ViewContext<Editor>,
325 ) -> Task<Result<bool>> {
326 Task::ready(Ok(true))
327 }
328
329 fn apply_additional_edits_for_completion(
330 &self,
331 _: Model<Buffer>,
332 _: project::Completion,
333 _: bool,
334 _: &mut ViewContext<Editor>,
335 ) -> Task<Result<Option<language::Transaction>>> {
336 Task::ready(Ok(None))
337 }
338
339 fn is_completion_trigger(
340 &self,
341 buffer: &Model<Buffer>,
342 position: language::Anchor,
343 _text: &str,
344 _trigger_in_words: bool,
345 cx: &mut ViewContext<Editor>,
346 ) -> bool {
347 let buffer = buffer.read(cx);
348 let position = position.to_point(buffer);
349 let line_start = Point::new(position.row, 0);
350 let mut lines = buffer.text_for_range(line_start..position).lines();
351 if let Some(line) = lines.next() {
352 SlashCommandLine::parse(line).is_some()
353 } else {
354 false
355 }
356 }
357
358 fn sort_completions(&self) -> bool {
359 false
360 }
361}
362
363impl SlashCommandLine {
364 pub(crate) fn parse(line: &str) -> Option<Self> {
365 let mut call: Option<Self> = None;
366 let mut ix = 0;
367 for c in line.chars() {
368 let next_ix = ix + c.len_utf8();
369 if let Some(call) = &mut call {
370 // The command arguments start at the first non-whitespace character
371 // after the command name, and continue until the end of the line.
372 if let Some(argument) = call.arguments.last_mut() {
373 if c.is_whitespace() {
374 if (*argument).is_empty() {
375 argument.start = next_ix;
376 argument.end = next_ix;
377 } else {
378 argument.end = ix;
379 call.arguments.push(next_ix..next_ix);
380 }
381 } else {
382 argument.end = next_ix;
383 }
384 }
385 // The command name ends at the first whitespace character.
386 else if !call.name.is_empty() {
387 if c.is_whitespace() {
388 call.arguments = vec![next_ix..next_ix];
389 } else {
390 call.name.end = next_ix;
391 }
392 }
393 // The command name must begin with a letter.
394 else if c.is_alphabetic() {
395 call.name.end = next_ix;
396 } else {
397 return None;
398 }
399 }
400 // Commands start with a slash.
401 else if c == '/' {
402 call = Some(SlashCommandLine {
403 name: next_ix..next_ix,
404 arguments: Vec::new(),
405 });
406 }
407 // The line can't contain anything before the slash except for whitespace.
408 else if !c.is_whitespace() {
409 return None;
410 }
411 ix = next_ix;
412 }
413 call
414 }
415}
416
417pub fn create_label_for_command(
418 command_name: &str,
419 arguments: &[&str],
420 cx: &AppContext,
421) -> CodeLabel {
422 let mut label = CodeLabel::default();
423 label.push_str(command_name, None);
424 label.push_str(" ", None);
425 label.push_str(
426 &arguments.join(" "),
427 cx.theme().syntax().highlight_id("comment").map(HighlightId),
428 );
429 label.filter_range = 0..command_name.len();
430 label
431}