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;
31
32pub(crate) struct SlashCommandCompletionProvider {
33 commands: Arc<SlashCommandRegistry>,
34 cancel_flag: Mutex<Arc<AtomicBool>>,
35 editor: Option<WeakView<ContextEditor>>,
36 workspace: Option<WeakView<Workspace>>,
37}
38
39pub(crate) struct SlashCommandLine {
40 /// The range within the line containing the command name.
41 pub name: Range<usize>,
42 /// The range within the line containing the command argument.
43 pub argument: Option<Range<usize>>,
44}
45
46impl SlashCommandCompletionProvider {
47 pub fn new(
48 commands: Arc<SlashCommandRegistry>,
49 editor: Option<WeakView<ContextEditor>>,
50 workspace: Option<WeakView<Workspace>>,
51 ) -> Self {
52 Self {
53 cancel_flag: Mutex::new(Arc::new(AtomicBool::new(false))),
54 editor,
55 commands,
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 candidates = self
68 .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 commands = self.commands.clone();
79 let command_name = command_name.to_string();
80 let editor = self.editor.clone();
81 let workspace = self.workspace.clone();
82 cx.spawn(|mut cx| async move {
83 let matches = match_strings(
84 &candidates,
85 &command_name,
86 true,
87 usize::MAX,
88 &Default::default(),
89 cx.background_executor().clone(),
90 )
91 .await;
92
93 cx.update(|cx| {
94 matches
95 .into_iter()
96 .filter_map(|mat| {
97 let command = commands.command(&mat.string)?;
98 let mut new_text = mat.string.clone();
99 let requires_argument = command.requires_argument();
100 if requires_argument {
101 new_text.push(' ');
102 }
103
104 let confirm = editor.clone().zip(workspace.clone()).and_then(
105 |(editor, workspace)| {
106 (!requires_argument).then(|| {
107 let command_name = mat.string.clone();
108 let command_range = command_range.clone();
109 let editor = editor.clone();
110 let workspace = workspace.clone();
111 Arc::new(move |cx: &mut WindowContext| {
112 editor
113 .update(cx, |editor, cx| {
114 editor.run_command(
115 command_range.clone(),
116 &command_name,
117 None,
118 true,
119 workspace.clone(),
120 cx,
121 );
122 })
123 .ok();
124 }) as Arc<_>
125 })
126 },
127 );
128 Some(project::Completion {
129 old_range: name_range.clone(),
130 documentation: Some(Documentation::SingleLine(command.description())),
131 new_text,
132 label: command.label(cx),
133 server_id: LanguageServerId(0),
134 lsp_completion: Default::default(),
135 show_new_completions_on_confirm: requires_argument,
136 confirm,
137 })
138 })
139 .collect()
140 })
141 })
142 }
143
144 fn complete_command_argument(
145 &self,
146 command_name: &str,
147 argument: String,
148 command_range: Range<Anchor>,
149 argument_range: Range<Anchor>,
150 cx: &mut WindowContext,
151 ) -> Task<Result<Vec<project::Completion>>> {
152 let new_cancel_flag = Arc::new(AtomicBool::new(false));
153 let mut flag = self.cancel_flag.lock();
154 flag.store(true, SeqCst);
155 *flag = new_cancel_flag.clone();
156
157 if let Some(command) = self.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 =
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.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 project::Completion {
198 old_range: argument_range.clone(),
199 label: CodeLabel::plain(command_argument.clone(), None),
200 new_text: command_argument.clone(),
201 documentation: None,
202 server_id: LanguageServerId(0),
203 lsp_completion: Default::default(),
204 show_new_completions_on_confirm: false,
205 confirm,
206 }
207 })
208 .collect())
209 })
210 } else {
211 cx.background_executor()
212 .spawn(async move { Ok(Vec::new()) })
213 }
214 }
215}
216
217impl CompletionProvider for SlashCommandCompletionProvider {
218 fn completions(
219 &self,
220 buffer: &Model<Buffer>,
221 buffer_position: Anchor,
222 _: editor::CompletionContext,
223 cx: &mut ViewContext<Editor>,
224 ) -> Task<Result<Vec<project::Completion>>> {
225 let Some((name, argument, command_range, argument_range)) =
226 buffer.update(cx, |buffer, _cx| {
227 let position = buffer_position.to_point(buffer);
228 let line_start = Point::new(position.row, 0);
229 let mut lines = buffer.text_for_range(line_start..position).lines();
230 let line = lines.next()?;
231 let call = SlashCommandLine::parse(line)?;
232
233 let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
234 let command_range_end = Point::new(
235 position.row,
236 call.argument.as_ref().map_or(call.name.end, |arg| arg.end) as u32,
237 );
238 let command_range = buffer.anchor_after(command_range_start)
239 ..buffer.anchor_after(command_range_end);
240
241 let name = line[call.name.clone()].to_string();
242
243 Some(if let Some(argument) = call.argument {
244 let start =
245 buffer.anchor_after(Point::new(position.row, argument.start as u32));
246 let argument = line[argument.clone()].to_string();
247 (name, Some(argument), command_range, start..buffer_position)
248 } else {
249 let start =
250 buffer.anchor_after(Point::new(position.row, call.name.start as u32));
251 (name, None, command_range, start..buffer_position)
252 })
253 })
254 else {
255 return Task::ready(Ok(Vec::new()));
256 };
257
258 if let Some(argument) = argument {
259 self.complete_command_argument(&name, argument, command_range, argument_range, cx)
260 } else {
261 self.complete_command_name(&name, command_range, argument_range, cx)
262 }
263 }
264
265 fn resolve_completions(
266 &self,
267 _: Model<Buffer>,
268 _: Vec<usize>,
269 _: Arc<RwLock<Box<[project::Completion]>>>,
270 _: &mut ViewContext<Editor>,
271 ) -> Task<Result<bool>> {
272 Task::ready(Ok(true))
273 }
274
275 fn apply_additional_edits_for_completion(
276 &self,
277 _: Model<Buffer>,
278 _: project::Completion,
279 _: bool,
280 _: &mut ViewContext<Editor>,
281 ) -> Task<Result<Option<language::Transaction>>> {
282 Task::ready(Ok(None))
283 }
284
285 fn is_completion_trigger(
286 &self,
287 buffer: &Model<Buffer>,
288 position: language::Anchor,
289 _text: &str,
290 _trigger_in_words: bool,
291 cx: &mut ViewContext<Editor>,
292 ) -> bool {
293 let buffer = buffer.read(cx);
294 let position = position.to_point(buffer);
295 let line_start = Point::new(position.row, 0);
296 let mut lines = buffer.text_for_range(line_start..position).lines();
297 if let Some(line) = lines.next() {
298 SlashCommandLine::parse(line).is_some()
299 } else {
300 false
301 }
302 }
303}
304
305impl SlashCommandLine {
306 pub(crate) fn parse(line: &str) -> Option<Self> {
307 let mut call: Option<Self> = None;
308 let mut ix = 0;
309 for c in line.chars() {
310 let next_ix = ix + c.len_utf8();
311 if let Some(call) = &mut call {
312 // The command arguments start at the first non-whitespace character
313 // after the command name, and continue until the end of the line.
314 if let Some(argument) = &mut call.argument {
315 if (*argument).is_empty() && c.is_whitespace() {
316 argument.start = next_ix;
317 }
318 argument.end = next_ix;
319 }
320 // The command name ends at the first whitespace character.
321 else if !call.name.is_empty() {
322 if c.is_whitespace() {
323 call.argument = Some(next_ix..next_ix);
324 } else {
325 call.name.end = next_ix;
326 }
327 }
328 // The command name must begin with a letter.
329 else if c.is_alphabetic() {
330 call.name.end = next_ix;
331 } else {
332 return None;
333 }
334 }
335 // Commands start with a slash.
336 else if c == '/' {
337 call = Some(SlashCommandLine {
338 name: next_ix..next_ix,
339 argument: None,
340 });
341 }
342 // The line can't contain anything before the slash except for whitespace.
343 else if !c.is_whitespace() {
344 return None;
345 }
346 ix = next_ix;
347 }
348 call
349 }
350}
351
352pub fn create_label_for_command(
353 command_name: &str,
354 arguments: &[&str],
355 cx: &AppContext,
356) -> CodeLabel {
357 let mut label = CodeLabel::default();
358 label.push_str(command_name, None);
359 label.push_str(" ", None);
360 label.push_str(
361 &arguments.join(" "),
362 cx.theme().syntax().highlight_id("comment").map(HighlightId),
363 );
364 label.filter_range = 0..command_name.len();
365 label
366}