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 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 = if command_argument.run_command {
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.new_text.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 } else {
199 None
200 };
201
202 let mut new_text = command_argument.new_text.clone();
203 if !command_argument.run_command {
204 new_text.push(' ');
205 }
206
207 project::Completion {
208 old_range: argument_range.clone(),
209 label: CodeLabel::plain(command_argument.label, None),
210 new_text,
211 documentation: None,
212 server_id: LanguageServerId(0),
213 lsp_completion: Default::default(),
214 show_new_completions_on_confirm: !command_argument.run_command,
215 confirm,
216 }
217 })
218 .collect())
219 })
220 } else {
221 cx.background_executor()
222 .spawn(async move { Ok(Vec::new()) })
223 }
224 }
225}
226
227impl CompletionProvider for SlashCommandCompletionProvider {
228 fn completions(
229 &self,
230 buffer: &Model<Buffer>,
231 buffer_position: Anchor,
232 _: editor::CompletionContext,
233 cx: &mut ViewContext<Editor>,
234 ) -> Task<Result<Vec<project::Completion>>> {
235 let Some((name, argument, command_range, argument_range)) =
236 buffer.update(cx, |buffer, _cx| {
237 let position = buffer_position.to_point(buffer);
238 let line_start = Point::new(position.row, 0);
239 let mut lines = buffer.text_for_range(line_start..position).lines();
240 let line = lines.next()?;
241 let call = SlashCommandLine::parse(line)?;
242
243 let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
244 let command_range_end = Point::new(
245 position.row,
246 call.argument.as_ref().map_or(call.name.end, |arg| arg.end) as u32,
247 );
248 let command_range = buffer.anchor_after(command_range_start)
249 ..buffer.anchor_after(command_range_end);
250
251 let name = line[call.name.clone()].to_string();
252
253 Some(if let Some(argument) = call.argument {
254 let start =
255 buffer.anchor_after(Point::new(position.row, argument.start as u32));
256 let argument = line[argument.clone()].to_string();
257 (name, Some(argument), command_range, start..buffer_position)
258 } else {
259 let start =
260 buffer.anchor_after(Point::new(position.row, call.name.start as u32));
261 (name, None, command_range, start..buffer_position)
262 })
263 })
264 else {
265 return Task::ready(Ok(Vec::new()));
266 };
267
268 if let Some(argument) = argument {
269 self.complete_command_argument(&name, argument, command_range, argument_range, cx)
270 } else {
271 self.complete_command_name(&name, command_range, argument_range, cx)
272 }
273 }
274
275 fn resolve_completions(
276 &self,
277 _: Model<Buffer>,
278 _: Vec<usize>,
279 _: Arc<RwLock<Box<[project::Completion]>>>,
280 _: &mut ViewContext<Editor>,
281 ) -> Task<Result<bool>> {
282 Task::ready(Ok(true))
283 }
284
285 fn apply_additional_edits_for_completion(
286 &self,
287 _: Model<Buffer>,
288 _: project::Completion,
289 _: bool,
290 _: &mut ViewContext<Editor>,
291 ) -> Task<Result<Option<language::Transaction>>> {
292 Task::ready(Ok(None))
293 }
294
295 fn is_completion_trigger(
296 &self,
297 buffer: &Model<Buffer>,
298 position: language::Anchor,
299 _text: &str,
300 _trigger_in_words: bool,
301 cx: &mut ViewContext<Editor>,
302 ) -> bool {
303 let buffer = buffer.read(cx);
304 let position = position.to_point(buffer);
305 let line_start = Point::new(position.row, 0);
306 let mut lines = buffer.text_for_range(line_start..position).lines();
307 if let Some(line) = lines.next() {
308 SlashCommandLine::parse(line).is_some()
309 } else {
310 false
311 }
312 }
313}
314
315impl SlashCommandLine {
316 pub(crate) fn parse(line: &str) -> Option<Self> {
317 let mut call: Option<Self> = None;
318 let mut ix = 0;
319 for c in line.chars() {
320 let next_ix = ix + c.len_utf8();
321 if let Some(call) = &mut call {
322 // The command arguments start at the first non-whitespace character
323 // after the command name, and continue until the end of the line.
324 if let Some(argument) = &mut call.argument {
325 if (*argument).is_empty() && c.is_whitespace() {
326 argument.start = next_ix;
327 }
328 argument.end = next_ix;
329 }
330 // The command name ends at the first whitespace character.
331 else if !call.name.is_empty() {
332 if c.is_whitespace() {
333 call.argument = Some(next_ix..next_ix);
334 } else {
335 call.name.end = next_ix;
336 }
337 }
338 // The command name must begin with a letter.
339 else if c.is_alphabetic() {
340 call.name.end = next_ix;
341 } else {
342 return None;
343 }
344 }
345 // Commands start with a slash.
346 else if c == '/' {
347 call = Some(SlashCommandLine {
348 name: next_ix..next_ix,
349 argument: None,
350 });
351 }
352 // The line can't contain anything before the slash except for whitespace.
353 else if !c.is_whitespace() {
354 return None;
355 }
356 ix = next_ix;
357 }
358 call
359 }
360}
361
362pub fn create_label_for_command(
363 command_name: &str,
364 arguments: &[&str],
365 cx: &AppContext,
366) -> CodeLabel {
367 let mut label = CodeLabel::default();
368 label.push_str(command_name, None);
369 label.push_str(" ", None);
370 label.push_str(
371 &arguments.join(" "),
372 cx.theme().syntax().highlight_id("comment").map(HighlightId),
373 );
374 label.filter_range = 0..command_name.len();
375 label
376}