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