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