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::{Model, Task, ViewContext, WeakView, WindowContext};
  7use language::{Anchor, Buffer, CodeLabel, Documentation, 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 workspace::Workspace;
 18
 19pub mod active_command;
 20pub mod default_command;
 21pub mod diagnostics_command;
 22pub mod fetch_command;
 23pub mod file_command;
 24pub mod now_command;
 25pub mod project_command;
 26pub mod prompt_command;
 27pub mod rustdoc_command;
 28pub mod search_command;
 29pub mod tabs_command;
 30
 31pub(crate) struct SlashCommandCompletionProvider {
 32    commands: Arc<SlashCommandRegistry>,
 33    cancel_flag: Mutex<Arc<AtomicBool>>,
 34    editor: Option<WeakView<ContextEditor>>,
 35    workspace: Option<WeakView<Workspace>>,
 36}
 37
 38pub(crate) struct SlashCommandLine {
 39    /// The range within the line containing the command name.
 40    pub name: Range<usize>,
 41    /// The range within the line containing the command argument.
 42    pub argument: Option<Range<usize>>,
 43}
 44
 45impl SlashCommandCompletionProvider {
 46    pub fn new(
 47        commands: Arc<SlashCommandRegistry>,
 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            commands,
 55            workspace,
 56        }
 57    }
 58
 59    fn complete_command_name(
 60        &self,
 61        command_name: &str,
 62        command_range: Range<Anchor>,
 63        name_range: Range<Anchor>,
 64        cx: &mut WindowContext,
 65    ) -> Task<Result<Vec<project::Completion>>> {
 66        let candidates = self
 67            .commands
 68            .command_names()
 69            .into_iter()
 70            .enumerate()
 71            .map(|(ix, def)| StringMatchCandidate {
 72                id: ix,
 73                string: def.to_string(),
 74                char_bag: def.as_ref().into(),
 75            })
 76            .collect::<Vec<_>>();
 77        let commands = self.commands.clone();
 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        if let Some(command) = self.commands.command(command_name) {
157            let completions = command.complete_argument(
158                argument,
159                new_cancel_flag.clone(),
160                self.workspace.clone(),
161                cx,
162            );
163            let command_name: Arc<str> = command_name.into();
164            let editor = self.editor.clone();
165            let workspace = self.workspace.clone();
166            cx.background_executor().spawn(async move {
167                Ok(completions
168                    .await?
169                    .into_iter()
170                    .map(|command_argument| {
171                        let confirm =
172                            editor
173                                .clone()
174                                .zip(workspace.clone())
175                                .map(|(editor, workspace)| {
176                                    Arc::new({
177                                        let command_range = command_range.clone();
178                                        let command_name = command_name.clone();
179                                        let command_argument = command_argument.clone();
180                                        move |cx: &mut WindowContext| {
181                                            editor
182                                                .update(cx, |editor, cx| {
183                                                    editor.run_command(
184                                                        command_range.clone(),
185                                                        &command_name,
186                                                        Some(&command_argument),
187                                                        true,
188                                                        workspace.clone(),
189                                                        cx,
190                                                    );
191                                                })
192                                                .ok();
193                                        }
194                                    }) as Arc<_>
195                                });
196                        project::Completion {
197                            old_range: argument_range.clone(),
198                            label: CodeLabel::plain(command_argument.clone(), None),
199                            new_text: command_argument.clone(),
200                            documentation: None,
201                            server_id: LanguageServerId(0),
202                            lsp_completion: Default::default(),
203                            show_new_completions_on_confirm: false,
204                            confirm,
205                        }
206                    })
207                    .collect())
208            })
209        } else {
210            cx.background_executor()
211                .spawn(async move { Ok(Vec::new()) })
212        }
213    }
214}
215
216impl CompletionProvider for SlashCommandCompletionProvider {
217    fn completions(
218        &self,
219        buffer: &Model<Buffer>,
220        buffer_position: Anchor,
221        _: editor::CompletionContext,
222        cx: &mut ViewContext<Editor>,
223    ) -> Task<Result<Vec<project::Completion>>> {
224        let Some((name, argument, command_range, argument_range)) =
225            buffer.update(cx, |buffer, _cx| {
226                let position = buffer_position.to_point(buffer);
227                let line_start = Point::new(position.row, 0);
228                let mut lines = buffer.text_for_range(line_start..position).lines();
229                let line = lines.next()?;
230                let call = SlashCommandLine::parse(line)?;
231
232                let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
233                let command_range_end = Point::new(
234                    position.row,
235                    call.argument.as_ref().map_or(call.name.end, |arg| arg.end) as u32,
236                );
237                let command_range = buffer.anchor_after(command_range_start)
238                    ..buffer.anchor_after(command_range_end);
239
240                let name = line[call.name.clone()].to_string();
241
242                Some(if let Some(argument) = call.argument {
243                    let start =
244                        buffer.anchor_after(Point::new(position.row, argument.start as u32));
245                    let argument = line[argument.clone()].to_string();
246                    (name, Some(argument), command_range, start..buffer_position)
247                } else {
248                    let start =
249                        buffer.anchor_after(Point::new(position.row, call.name.start as u32));
250                    (name, None, command_range, start..buffer_position)
251                })
252            })
253        else {
254            return Task::ready(Ok(Vec::new()));
255        };
256
257        if let Some(argument) = argument {
258            self.complete_command_argument(&name, argument, command_range, argument_range, cx)
259        } else {
260            self.complete_command_name(&name, command_range, argument_range, cx)
261        }
262    }
263
264    fn resolve_completions(
265        &self,
266        _: Model<Buffer>,
267        _: Vec<usize>,
268        _: Arc<RwLock<Box<[project::Completion]>>>,
269        _: &mut ViewContext<Editor>,
270    ) -> Task<Result<bool>> {
271        Task::ready(Ok(true))
272    }
273
274    fn apply_additional_edits_for_completion(
275        &self,
276        _: Model<Buffer>,
277        _: project::Completion,
278        _: bool,
279        _: &mut ViewContext<Editor>,
280    ) -> Task<Result<Option<language::Transaction>>> {
281        Task::ready(Ok(None))
282    }
283
284    fn is_completion_trigger(
285        &self,
286        buffer: &Model<Buffer>,
287        position: language::Anchor,
288        _text: &str,
289        _trigger_in_words: bool,
290        cx: &mut ViewContext<Editor>,
291    ) -> bool {
292        let buffer = buffer.read(cx);
293        let position = position.to_point(buffer);
294        let line_start = Point::new(position.row, 0);
295        let mut lines = buffer.text_for_range(line_start..position).lines();
296        if let Some(line) = lines.next() {
297            SlashCommandLine::parse(line).is_some()
298        } else {
299            false
300        }
301    }
302}
303
304impl SlashCommandLine {
305    pub(crate) fn parse(line: &str) -> Option<Self> {
306        let mut call: Option<Self> = None;
307        let mut ix = 0;
308        for c in line.chars() {
309            let next_ix = ix + c.len_utf8();
310            if let Some(call) = &mut call {
311                // The command arguments start at the first non-whitespace character
312                // after the command name, and continue until the end of the line.
313                if let Some(argument) = &mut call.argument {
314                    if (*argument).is_empty() && c.is_whitespace() {
315                        argument.start = next_ix;
316                    }
317                    argument.end = next_ix;
318                }
319                // The command name ends at the first whitespace character.
320                else if !call.name.is_empty() {
321                    if c.is_whitespace() {
322                        call.argument = Some(next_ix..next_ix);
323                    } else {
324                        call.name.end = next_ix;
325                    }
326                }
327                // The command name must begin with a letter.
328                else if c.is_alphabetic() {
329                    call.name.end = next_ix;
330                } else {
331                    return None;
332                }
333            }
334            // Commands start with a slash.
335            else if c == '/' {
336                call = Some(SlashCommandLine {
337                    name: next_ix..next_ix,
338                    argument: None,
339                });
340            }
341            // The line can't contain anything before the slash except for whitespace.
342            else if !c.is_whitespace() {
343                return None;
344            }
345            ix = next_ix;
346        }
347        call
348    }
349}