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 symbols_command;
 31pub mod tabs_command;
 32pub mod term_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    /// The range within the line containing the command argument.
 45    pub argument: Option<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(move |cx: &mut WindowContext| {
111                                        editor
112                                            .update(cx, |editor, cx| {
113                                                editor.run_command(
114                                                    command_range.clone(),
115                                                    &command_name,
116                                                    None,
117                                                    true,
118                                                    workspace.clone(),
119                                                    cx,
120                                                );
121                                            })
122                                            .ok();
123                                    }) as Arc<_>
124                                })
125                            },
126                        );
127                        Some(project::Completion {
128                            old_range: name_range.clone(),
129                            documentation: Some(Documentation::SingleLine(command.description())),
130                            new_text,
131                            label: command.label(cx),
132                            server_id: LanguageServerId(0),
133                            lsp_completion: Default::default(),
134                            show_new_completions_on_confirm: requires_argument,
135                            confirm,
136                        })
137                    })
138                    .collect()
139            })
140        })
141    }
142
143    fn complete_command_argument(
144        &self,
145        command_name: &str,
146        argument: String,
147        command_range: Range<Anchor>,
148        argument_range: Range<Anchor>,
149        cx: &mut WindowContext,
150    ) -> Task<Result<Vec<project::Completion>>> {
151        let new_cancel_flag = Arc::new(AtomicBool::new(false));
152        let mut flag = self.cancel_flag.lock();
153        flag.store(true, SeqCst);
154        *flag = new_cancel_flag.clone();
155
156        let commands = SlashCommandRegistry::global(cx);
157        if let Some(command) = commands.command(command_name) {
158            let completions = command.complete_argument(
159                argument,
160                new_cancel_flag.clone(),
161                self.workspace.clone(),
162                cx,
163            );
164            let command_name: Arc<str> = command_name.into();
165            let editor = self.editor.clone();
166            let workspace = self.workspace.clone();
167            cx.background_executor().spawn(async move {
168                Ok(completions
169                    .await?
170                    .into_iter()
171                    .map(|command_argument| {
172                        let confirm = if command_argument.run_command {
173                            editor
174                                .clone()
175                                .zip(workspace.clone())
176                                .map(|(editor, workspace)| {
177                                    Arc::new({
178                                        let command_range = command_range.clone();
179                                        let command_name = command_name.clone();
180                                        let command_argument = command_argument.new_text.clone();
181                                        move |cx: &mut WindowContext| {
182                                            editor
183                                                .update(cx, |editor, cx| {
184                                                    editor.run_command(
185                                                        command_range.clone(),
186                                                        &command_name,
187                                                        Some(&command_argument),
188                                                        true,
189                                                        workspace.clone(),
190                                                        cx,
191                                                    );
192                                                })
193                                                .ok();
194                                        }
195                                    }) as Arc<_>
196                                })
197                        } else {
198                            None
199                        };
200
201                        let mut new_text = command_argument.new_text.clone();
202                        if !command_argument.run_command {
203                            new_text.push(' ');
204                        }
205
206                        project::Completion {
207                            old_range: argument_range.clone(),
208                            label: CodeLabel::plain(command_argument.label, None),
209                            new_text,
210                            documentation: None,
211                            server_id: LanguageServerId(0),
212                            lsp_completion: Default::default(),
213                            show_new_completions_on_confirm: !command_argument.run_command,
214                            confirm,
215                        }
216                    })
217                    .collect())
218            })
219        } else {
220            cx.background_executor()
221                .spawn(async move { Ok(Vec::new()) })
222        }
223    }
224}
225
226impl CompletionProvider for SlashCommandCompletionProvider {
227    fn completions(
228        &self,
229        buffer: &Model<Buffer>,
230        buffer_position: Anchor,
231        _: editor::CompletionContext,
232        cx: &mut ViewContext<Editor>,
233    ) -> Task<Result<Vec<project::Completion>>> {
234        let Some((name, argument, command_range, argument_range)) =
235            buffer.update(cx, |buffer, _cx| {
236                let position = buffer_position.to_point(buffer);
237                let line_start = Point::new(position.row, 0);
238                let mut lines = buffer.text_for_range(line_start..position).lines();
239                let line = lines.next()?;
240                let call = SlashCommandLine::parse(line)?;
241
242                let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
243                let command_range_end = Point::new(
244                    position.row,
245                    call.argument.as_ref().map_or(call.name.end, |arg| arg.end) as u32,
246                );
247                let command_range = buffer.anchor_after(command_range_start)
248                    ..buffer.anchor_after(command_range_end);
249
250                let name = line[call.name.clone()].to_string();
251
252                Some(if let Some(argument) = call.argument {
253                    let start =
254                        buffer.anchor_after(Point::new(position.row, argument.start as u32));
255                    let argument = line[argument.clone()].to_string();
256                    (name, Some(argument), command_range, start..buffer_position)
257                } else {
258                    let start =
259                        buffer.anchor_after(Point::new(position.row, call.name.start as u32));
260                    (name, None, command_range, start..buffer_position)
261                })
262            })
263        else {
264            return Task::ready(Ok(Vec::new()));
265        };
266
267        if let Some(argument) = argument {
268            self.complete_command_argument(&name, argument, command_range, argument_range, cx)
269        } else {
270            self.complete_command_name(&name, command_range, argument_range, cx)
271        }
272    }
273
274    fn resolve_completions(
275        &self,
276        _: Model<Buffer>,
277        _: Vec<usize>,
278        _: Arc<RwLock<Box<[project::Completion]>>>,
279        _: &mut ViewContext<Editor>,
280    ) -> Task<Result<bool>> {
281        Task::ready(Ok(true))
282    }
283
284    fn apply_additional_edits_for_completion(
285        &self,
286        _: Model<Buffer>,
287        _: project::Completion,
288        _: bool,
289        _: &mut ViewContext<Editor>,
290    ) -> Task<Result<Option<language::Transaction>>> {
291        Task::ready(Ok(None))
292    }
293
294    fn is_completion_trigger(
295        &self,
296        buffer: &Model<Buffer>,
297        position: language::Anchor,
298        _text: &str,
299        _trigger_in_words: bool,
300        cx: &mut ViewContext<Editor>,
301    ) -> bool {
302        let buffer = buffer.read(cx);
303        let position = position.to_point(buffer);
304        let line_start = Point::new(position.row, 0);
305        let mut lines = buffer.text_for_range(line_start..position).lines();
306        if let Some(line) = lines.next() {
307            SlashCommandLine::parse(line).is_some()
308        } else {
309            false
310        }
311    }
312}
313
314impl SlashCommandLine {
315    pub(crate) fn parse(line: &str) -> Option<Self> {
316        let mut call: Option<Self> = None;
317        let mut ix = 0;
318        for c in line.chars() {
319            let next_ix = ix + c.len_utf8();
320            if let Some(call) = &mut call {
321                // The command arguments start at the first non-whitespace character
322                // after the command name, and continue until the end of the line.
323                if let Some(argument) = &mut call.argument {
324                    if (*argument).is_empty() && c.is_whitespace() {
325                        argument.start = next_ix;
326                    }
327                    argument.end = next_ix;
328                }
329                // The command name ends at the first whitespace character.
330                else if !call.name.is_empty() {
331                    if c.is_whitespace() {
332                        call.argument = Some(next_ix..next_ix);
333                    } else {
334                        call.name.end = next_ix;
335                    }
336                }
337                // The command name must begin with a letter.
338                else if c.is_alphabetic() {
339                    call.name.end = next_ix;
340                } else {
341                    return None;
342                }
343            }
344            // Commands start with a slash.
345            else if c == '/' {
346                call = Some(SlashCommandLine {
347                    name: next_ix..next_ix,
348                    argument: None,
349                });
350            }
351            // The line can't contain anything before the slash except for whitespace.
352            else if !c.is_whitespace() {
353                return None;
354            }
355            ix = next_ix;
356        }
357        call
358    }
359}
360
361pub fn create_label_for_command(
362    command_name: &str,
363    arguments: &[&str],
364    cx: &AppContext,
365) -> CodeLabel {
366    let mut label = CodeLabel::default();
367    label.push_str(command_name, None);
368    label.push_str(" ", None);
369    label.push_str(
370        &arguments.join(" "),
371        cx.theme().syntax().highlight_id("comment").map(HighlightId),
372    );
373    label.filter_range = 0..command_name.len();
374    label
375}