slash_command.rs

  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                                                            false,
128                                                            workspace.clone(),
129                                                            cx,
130                                                        );
131                                                    })
132                                                    .ok();
133                                                false
134                                            } else {
135                                                requires_argument || accepts_arguments
136                                            }
137                                        },
138                                    ) as Arc<_>
139                                });
140                        Some(project::Completion {
141                            old_range: name_range.clone(),
142                            documentation: Some(Documentation::SingleLine(command.description())),
143                            new_text,
144                            label: command.label(cx),
145                            server_id: LanguageServerId(0),
146                            lsp_completion: Default::default(),
147                            confirm,
148                        })
149                    })
150                    .collect()
151            })
152        })
153    }
154
155    fn complete_command_argument(
156        &self,
157        command_name: &str,
158        arguments: &[String],
159        command_range: Range<Anchor>,
160        argument_range: Range<Anchor>,
161        last_argument_range: Range<Anchor>,
162        cx: &mut WindowContext,
163    ) -> Task<Result<Vec<project::Completion>>> {
164        let new_cancel_flag = Arc::new(AtomicBool::new(false));
165        let mut flag = self.cancel_flag.lock();
166        flag.store(true, SeqCst);
167        *flag = new_cancel_flag.clone();
168        let commands = SlashCommandRegistry::global(cx);
169        if let Some(command) = commands.command(command_name) {
170            let completions = command.complete_argument(
171                arguments,
172                new_cancel_flag.clone(),
173                self.workspace.clone(),
174                cx,
175            );
176            let command_name: Arc<str> = command_name.into();
177            let editor = self.editor.clone();
178            let workspace = self.workspace.clone();
179            let arguments = arguments.to_vec();
180            cx.background_executor().spawn(async move {
181                Ok(completions
182                    .await?
183                    .into_iter()
184                    .map(|new_argument| {
185                        let confirm =
186                            editor
187                                .clone()
188                                .zip(workspace.clone())
189                                .map(|(editor, workspace)| {
190                                    Arc::new({
191                                        let mut completed_arguments = arguments.clone();
192                                        if new_argument.replace_previous_arguments {
193                                            completed_arguments.clear();
194                                        } else {
195                                            completed_arguments.pop();
196                                        }
197                                        completed_arguments.push(new_argument.new_text.clone());
198
199                                        let command_range = command_range.clone();
200                                        let command_name = command_name.clone();
201                                        move |intent: CompletionIntent, cx: &mut WindowContext| {
202                                            if new_argument.after_completion.run()
203                                                || intent.is_complete()
204                                            {
205                                                editor
206                                                    .update(cx, |editor, cx| {
207                                                        editor.run_command(
208                                                            command_range.clone(),
209                                                            &command_name,
210                                                            &completed_arguments,
211                                                            true,
212                                                            false,
213                                                            workspace.clone(),
214                                                            cx,
215                                                        );
216                                                    })
217                                                    .ok();
218                                                false
219                                            } else {
220                                                !new_argument.after_completion.run()
221                                            }
222                                        }
223                                    }) as Arc<_>
224                                });
225
226                        let mut new_text = new_argument.new_text.clone();
227                        if new_argument.after_completion == AfterCompletion::Continue {
228                            new_text.push(' ');
229                        }
230
231                        project::Completion {
232                            old_range: if new_argument.replace_previous_arguments {
233                                argument_range.clone()
234                            } else {
235                                last_argument_range.clone()
236                            },
237                            label: new_argument.label,
238                            new_text,
239                            documentation: None,
240                            server_id: LanguageServerId(0),
241                            lsp_completion: Default::default(),
242                            confirm,
243                        }
244                    })
245                    .collect())
246            })
247        } else {
248            Task::ready(Ok(Vec::new()))
249        }
250    }
251}
252
253impl CompletionProvider for SlashCommandCompletionProvider {
254    fn completions(
255        &self,
256        buffer: &Model<Buffer>,
257        buffer_position: Anchor,
258        _: editor::CompletionContext,
259        cx: &mut ViewContext<Editor>,
260    ) -> Task<Result<Vec<project::Completion>>> {
261        let Some((name, arguments, command_range, last_argument_range)) =
262            buffer.update(cx, |buffer, _cx| {
263                let position = buffer_position.to_point(buffer);
264                let line_start = Point::new(position.row, 0);
265                let mut lines = buffer.text_for_range(line_start..position).lines();
266                let line = lines.next()?;
267                let call = SlashCommandLine::parse(line)?;
268
269                let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
270                let command_range_end = Point::new(
271                    position.row,
272                    call.arguments.last().map_or(call.name.end, |arg| arg.end) as u32,
273                );
274                let command_range = buffer.anchor_after(command_range_start)
275                    ..buffer.anchor_after(command_range_end);
276
277                let name = line[call.name.clone()].to_string();
278                let (arguments, last_argument_range) = if let Some(argument) = call.arguments.last()
279                {
280                    let last_arg_start =
281                        buffer.anchor_after(Point::new(position.row, argument.start as u32));
282                    let first_arg_start = call.arguments.first().expect("we have the last element");
283                    let first_arg_start =
284                        buffer.anchor_after(Point::new(position.row, first_arg_start.start as u32));
285                    let arguments = call
286                        .arguments
287                        .iter()
288                        .filter_map(|argument| Some(line.get(argument.clone())?.to_string()))
289                        .collect::<Vec<_>>();
290                    let argument_range = first_arg_start..buffer_position;
291                    (
292                        Some((arguments, argument_range)),
293                        last_arg_start..buffer_position,
294                    )
295                } else {
296                    let start =
297                        buffer.anchor_after(Point::new(position.row, call.name.start as u32));
298                    (None, start..buffer_position)
299                };
300
301                Some((name, arguments, command_range, last_argument_range))
302            })
303        else {
304            return Task::ready(Ok(Vec::new()));
305        };
306
307        if let Some((arguments, argument_range)) = arguments {
308            self.complete_command_argument(
309                &name,
310                &arguments,
311                command_range,
312                argument_range,
313                last_argument_range,
314                cx,
315            )
316        } else {
317            self.complete_command_name(&name, command_range, last_argument_range, cx)
318        }
319    }
320
321    fn resolve_completions(
322        &self,
323        _: Model<Buffer>,
324        _: Vec<usize>,
325        _: Arc<RwLock<Box<[project::Completion]>>>,
326        _: &mut ViewContext<Editor>,
327    ) -> Task<Result<bool>> {
328        Task::ready(Ok(true))
329    }
330
331    fn apply_additional_edits_for_completion(
332        &self,
333        _: Model<Buffer>,
334        _: project::Completion,
335        _: bool,
336        _: &mut ViewContext<Editor>,
337    ) -> Task<Result<Option<language::Transaction>>> {
338        Task::ready(Ok(None))
339    }
340
341    fn is_completion_trigger(
342        &self,
343        buffer: &Model<Buffer>,
344        position: language::Anchor,
345        _text: &str,
346        _trigger_in_words: bool,
347        cx: &mut ViewContext<Editor>,
348    ) -> bool {
349        let buffer = buffer.read(cx);
350        let position = position.to_point(buffer);
351        let line_start = Point::new(position.row, 0);
352        let mut lines = buffer.text_for_range(line_start..position).lines();
353        if let Some(line) = lines.next() {
354            SlashCommandLine::parse(line).is_some()
355        } else {
356            false
357        }
358    }
359
360    fn sort_completions(&self) -> bool {
361        false
362    }
363}
364
365impl SlashCommandLine {
366    pub(crate) fn parse(line: &str) -> Option<Self> {
367        let mut call: Option<Self> = None;
368        let mut ix = 0;
369        for c in line.chars() {
370            let next_ix = ix + c.len_utf8();
371            if let Some(call) = &mut call {
372                // The command arguments start at the first non-whitespace character
373                // after the command name, and continue until the end of the line.
374                if let Some(argument) = call.arguments.last_mut() {
375                    if c.is_whitespace() {
376                        if (*argument).is_empty() {
377                            argument.start = next_ix;
378                            argument.end = next_ix;
379                        } else {
380                            argument.end = ix;
381                            call.arguments.push(next_ix..next_ix);
382                        }
383                    } else {
384                        argument.end = next_ix;
385                    }
386                }
387                // The command name ends at the first whitespace character.
388                else if !call.name.is_empty() {
389                    if c.is_whitespace() {
390                        call.arguments = vec![next_ix..next_ix];
391                    } else {
392                        call.name.end = next_ix;
393                    }
394                }
395                // The command name must begin with a letter.
396                else if c.is_alphabetic() {
397                    call.name.end = next_ix;
398                } else {
399                    return None;
400                }
401            }
402            // Commands start with a slash.
403            else if c == '/' {
404                call = Some(SlashCommandLine {
405                    name: next_ix..next_ix,
406                    arguments: Vec::new(),
407                });
408            }
409            // The line can't contain anything before the slash except for whitespace.
410            else if !c.is_whitespace() {
411                return None;
412            }
413            ix = next_ix;
414        }
415        call
416    }
417}
418
419pub fn create_label_for_command(
420    command_name: &str,
421    arguments: &[&str],
422    cx: &AppContext,
423) -> CodeLabel {
424    let mut label = CodeLabel::default();
425    label.push_str(command_name, None);
426    label.push_str(" ", None);
427    label.push_str(
428        &arguments.join(" "),
429        cx.theme().syntax().highlight_id("comment").map(HighlightId),
430    );
431    label.filter_range = 0..command_name.len();
432    label
433}