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