slash_command.rs

  1use crate::context_editor::ContextEditor;
  2use anyhow::Result;
  3pub use assistant_slash_command::SlashCommand;
  4use assistant_slash_command::{AfterCompletion, SlashCommandLine, SlashCommandWorkingSet};
  5use editor::{CompletionProvider, Editor};
  6use fuzzy::{match_strings, StringMatchCandidate};
  7use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity, Window};
  8use language::{Anchor, Buffer, LanguageServerId, ToPoint};
  9use parking_lot::Mutex;
 10use project::{lsp_store::CompletionDocumentation, CompletionIntent};
 11use rope::Point;
 12use std::{
 13    cell::RefCell,
 14    ops::Range,
 15    rc::Rc,
 16    sync::{
 17        atomic::{AtomicBool, Ordering::SeqCst},
 18        Arc,
 19    },
 20};
 21use workspace::Workspace;
 22
 23pub struct SlashCommandCompletionProvider {
 24    cancel_flag: Mutex<Arc<AtomicBool>>,
 25    slash_commands: Arc<SlashCommandWorkingSet>,
 26    editor: Option<WeakEntity<ContextEditor>>,
 27    workspace: Option<WeakEntity<Workspace>>,
 28}
 29
 30impl SlashCommandCompletionProvider {
 31    pub fn new(
 32        slash_commands: Arc<SlashCommandWorkingSet>,
 33        editor: Option<WeakEntity<ContextEditor>>,
 34        workspace: Option<WeakEntity<Workspace>>,
 35    ) -> Self {
 36        Self {
 37            cancel_flag: Mutex::new(Arc::new(AtomicBool::new(false))),
 38            slash_commands,
 39            editor,
 40            workspace,
 41        }
 42    }
 43
 44    fn complete_command_name(
 45        &self,
 46        command_name: &str,
 47        command_range: Range<Anchor>,
 48        name_range: Range<Anchor>,
 49        window: &mut Window,
 50        cx: &mut App,
 51    ) -> Task<Result<Vec<project::Completion>>> {
 52        let slash_commands = self.slash_commands.clone();
 53        let candidates = slash_commands
 54            .command_names(cx)
 55            .into_iter()
 56            .enumerate()
 57            .map(|(ix, def)| StringMatchCandidate::new(ix, &def))
 58            .collect::<Vec<_>>();
 59        let command_name = command_name.to_string();
 60        let editor = self.editor.clone();
 61        let workspace = self.workspace.clone();
 62        window.spawn(cx, |mut cx| async move {
 63            let matches = match_strings(
 64                &candidates,
 65                &command_name,
 66                true,
 67                usize::MAX,
 68                &Default::default(),
 69                cx.background_executor().clone(),
 70            )
 71            .await;
 72
 73            cx.update(|_, cx| {
 74                matches
 75                    .into_iter()
 76                    .filter_map(|mat| {
 77                        let command = slash_commands.command(&mat.string, cx)?;
 78                        let mut new_text = mat.string.clone();
 79                        let requires_argument = command.requires_argument();
 80                        let accepts_arguments = command.accepts_arguments();
 81                        if requires_argument || accepts_arguments {
 82                            new_text.push(' ');
 83                        }
 84
 85                        let confirm =
 86                            editor
 87                                .clone()
 88                                .zip(workspace.clone())
 89                                .map(|(editor, workspace)| {
 90                                    let command_name = mat.string.clone();
 91                                    let command_range = command_range.clone();
 92                                    let editor = editor.clone();
 93                                    let workspace = workspace.clone();
 94                                    Arc::new(
 95                                    move |intent: CompletionIntent,
 96                                          window: &mut Window,
 97                                          cx: &mut App| {
 98                                        if !requires_argument
 99                                            && (!accepts_arguments || intent.is_complete())
100                                        {
101                                            editor
102                                                .update(cx, |editor, cx| {
103                                                    editor.run_command(
104                                                        command_range.clone(),
105                                                        &command_name,
106                                                        &[],
107                                                        true,
108                                                        workspace.clone(),
109                                                        window,
110                                                        cx,
111                                                    );
112                                                })
113                                                .ok();
114                                            false
115                                        } else {
116                                            requires_argument || accepts_arguments
117                                        }
118                                    },
119                                ) as Arc<_>
120                                });
121                        Some(project::Completion {
122                            old_range: name_range.clone(),
123                            documentation: Some(CompletionDocumentation::SingleLine(
124                                command.description().into(),
125                            )),
126                            new_text,
127                            label: command.label(cx),
128                            server_id: LanguageServerId(0),
129                            lsp_completion: Default::default(),
130                            confirm,
131                            resolved: true,
132                        })
133                    })
134                    .collect()
135            })
136        })
137    }
138
139    #[allow(clippy::too_many_arguments)]
140    fn complete_command_argument(
141        &self,
142        command_name: &str,
143        arguments: &[String],
144        command_range: Range<Anchor>,
145        argument_range: Range<Anchor>,
146        last_argument_range: Range<Anchor>,
147        window: &mut Window,
148        cx: &mut App,
149    ) -> Task<Result<Vec<project::Completion>>> {
150        let new_cancel_flag = Arc::new(AtomicBool::new(false));
151        let mut flag = self.cancel_flag.lock();
152        flag.store(true, SeqCst);
153        *flag = new_cancel_flag.clone();
154        if let Some(command) = self.slash_commands.command(command_name, cx) {
155            let completions = command.complete_argument(
156                arguments,
157                new_cancel_flag.clone(),
158                self.workspace.clone(),
159                window,
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            let arguments = arguments.to_vec();
166            cx.background_spawn(async move {
167                Ok(completions
168                    .await?
169                    .into_iter()
170                    .map(|new_argument| {
171                        let confirm =
172                            editor
173                                .clone()
174                                .zip(workspace.clone())
175                                .map(|(editor, workspace)| {
176                                    Arc::new({
177                                        let mut completed_arguments = arguments.clone();
178                                        if new_argument.replace_previous_arguments {
179                                            completed_arguments.clear();
180                                        } else {
181                                            completed_arguments.pop();
182                                        }
183                                        completed_arguments.push(new_argument.new_text.clone());
184
185                                        let command_range = command_range.clone();
186                                        let command_name = command_name.clone();
187                                        move |intent: CompletionIntent,
188                                              window: &mut Window,
189                                              cx: &mut App| {
190                                            if new_argument.after_completion.run()
191                                                || intent.is_complete()
192                                            {
193                                                editor
194                                                    .update(cx, |editor, cx| {
195                                                        editor.run_command(
196                                                            command_range.clone(),
197                                                            &command_name,
198                                                            &completed_arguments,
199                                                            true,
200                                                            workspace.clone(),
201                                                            window,
202                                                            cx,
203                                                        );
204                                                    })
205                                                    .ok();
206                                                false
207                                            } else {
208                                                !new_argument.after_completion.run()
209                                            }
210                                        }
211                                    }) as Arc<_>
212                                });
213
214                        let mut new_text = new_argument.new_text.clone();
215                        if new_argument.after_completion == AfterCompletion::Continue {
216                            new_text.push(' ');
217                        }
218
219                        project::Completion {
220                            old_range: if new_argument.replace_previous_arguments {
221                                argument_range.clone()
222                            } else {
223                                last_argument_range.clone()
224                            },
225                            label: new_argument.label,
226                            new_text,
227                            documentation: None,
228                            server_id: LanguageServerId(0),
229                            lsp_completion: Default::default(),
230                            confirm,
231                            resolved: true,
232                        }
233                    })
234                    .collect())
235            })
236        } else {
237            Task::ready(Ok(Vec::new()))
238        }
239    }
240}
241
242impl CompletionProvider for SlashCommandCompletionProvider {
243    fn completions(
244        &self,
245        buffer: &Entity<Buffer>,
246        buffer_position: Anchor,
247        _: editor::CompletionContext,
248        window: &mut Window,
249        cx: &mut Context<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                window,
305                cx,
306            )
307        } else {
308            self.complete_command_name(&name, command_range, last_argument_range, window, cx)
309        }
310    }
311
312    fn resolve_completions(
313        &self,
314        _: Entity<Buffer>,
315        _: Vec<usize>,
316        _: Rc<RefCell<Box<[project::Completion]>>>,
317        _: &mut Context<Editor>,
318    ) -> Task<Result<bool>> {
319        Task::ready(Ok(true))
320    }
321
322    fn is_completion_trigger(
323        &self,
324        buffer: &Entity<Buffer>,
325        position: language::Anchor,
326        _text: &str,
327        _trigger_in_words: bool,
328        cx: &mut Context<Editor>,
329    ) -> bool {
330        let buffer = buffer.read(cx);
331        let position = position.to_point(buffer);
332        let line_start = Point::new(position.row, 0);
333        let mut lines = buffer.text_for_range(line_start..position).lines();
334        if let Some(line) = lines.next() {
335            SlashCommandLine::parse(line).is_some()
336        } else {
337            false
338        }
339    }
340
341    fn sort_completions(&self) -> bool {
342        false
343    }
344}