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