slash_command.rs

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