1use crate::assistant_panel::ConversationEditor;
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 file_command;
21pub mod project_command;
22pub mod prompt_command;
23pub mod search_command;
24pub mod tabs_command;
25
26pub(crate) struct SlashCommandCompletionProvider {
27 editor: WeakView<ConversationEditor>,
28 commands: Arc<SlashCommandRegistry>,
29 cancel_flag: Mutex<Arc<AtomicBool>>,
30 workspace: WeakView<Workspace>,
31}
32
33pub(crate) struct SlashCommandLine {
34 /// The range within the line containing the command name.
35 pub name: Range<usize>,
36 /// The range within the line containing the command argument.
37 pub argument: Option<Range<usize>>,
38}
39
40impl SlashCommandCompletionProvider {
41 pub fn new(
42 editor: WeakView<ConversationEditor>,
43 commands: Arc<SlashCommandRegistry>,
44 workspace: WeakView<Workspace>,
45 ) -> Self {
46 Self {
47 cancel_flag: Mutex::new(Arc::new(AtomicBool::new(false))),
48 editor,
49 commands,
50 workspace,
51 }
52 }
53
54 fn complete_command_name(
55 &self,
56 command_name: &str,
57 command_range: Range<Anchor>,
58 name_range: Range<Anchor>,
59 cx: &mut WindowContext,
60 ) -> Task<Result<Vec<project::Completion>>> {
61 let candidates = self
62 .commands
63 .command_names()
64 .into_iter()
65 .enumerate()
66 .map(|(ix, def)| StringMatchCandidate {
67 id: ix,
68 string: def.to_string(),
69 char_bag: def.as_ref().into(),
70 })
71 .collect::<Vec<_>>();
72 let commands = self.commands.clone();
73 let command_name = command_name.to_string();
74 let editor = self.editor.clone();
75 let workspace = self.workspace.clone();
76 cx.spawn(|mut cx| async move {
77 let matches = match_strings(
78 &candidates,
79 &command_name,
80 true,
81 usize::MAX,
82 &Default::default(),
83 cx.background_executor().clone(),
84 )
85 .await;
86
87 cx.update(|cx| {
88 matches
89 .into_iter()
90 .filter_map(|mat| {
91 let command = commands.command(&mat.string)?;
92 let mut new_text = mat.string.clone();
93 let requires_argument = command.requires_argument();
94 if requires_argument {
95 new_text.push(' ');
96 }
97
98 Some(project::Completion {
99 old_range: name_range.clone(),
100 documentation: Some(Documentation::SingleLine(command.description())),
101 new_text,
102 label: command.label(cx),
103 server_id: LanguageServerId(0),
104 lsp_completion: Default::default(),
105 confirm: (!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 workspace.clone(),
118 cx,
119 );
120 })
121 .ok();
122 }) as Arc<_>
123 }),
124 })
125 })
126 .collect()
127 })
128 })
129 }
130
131 fn complete_command_argument(
132 &self,
133 command_name: &str,
134 argument: String,
135 command_range: Range<Anchor>,
136 argument_range: Range<Anchor>,
137 cx: &mut WindowContext,
138 ) -> Task<Result<Vec<project::Completion>>> {
139 let new_cancel_flag = Arc::new(AtomicBool::new(false));
140 let mut flag = self.cancel_flag.lock();
141 flag.store(true, SeqCst);
142 *flag = new_cancel_flag.clone();
143
144 if let Some(command) = self.commands.command(command_name) {
145 let completions = command.complete_argument(argument, new_cancel_flag.clone(), cx);
146 let command_name: Arc<str> = command_name.into();
147 let editor = self.editor.clone();
148 let workspace = self.workspace.clone();
149 cx.background_executor().spawn(async move {
150 Ok(completions
151 .await?
152 .into_iter()
153 .map(|arg| project::Completion {
154 old_range: argument_range.clone(),
155 label: CodeLabel::plain(arg.clone(), None),
156 new_text: arg.clone(),
157 documentation: None,
158 server_id: LanguageServerId(0),
159 lsp_completion: Default::default(),
160 confirm: Some(Arc::new({
161 let command_name = command_name.clone();
162 let command_range = command_range.clone();
163 let editor = editor.clone();
164 let workspace = workspace.clone();
165 move |cx| {
166 editor
167 .update(cx, |editor, cx| {
168 editor.run_command(
169 command_range.clone(),
170 &command_name,
171 Some(&arg),
172 workspace.clone(),
173 cx,
174 );
175 })
176 .ok();
177 }
178 })),
179 })
180 .collect())
181 })
182 } else {
183 cx.background_executor()
184 .spawn(async move { Ok(Vec::new()) })
185 }
186 }
187}
188
189impl CompletionProvider for SlashCommandCompletionProvider {
190 fn completions(
191 &self,
192 buffer: &Model<Buffer>,
193 buffer_position: Anchor,
194 cx: &mut ViewContext<Editor>,
195 ) -> Task<Result<Vec<project::Completion>>> {
196 let Some((name, argument, command_range, argument_range)) =
197 buffer.update(cx, |buffer, _cx| {
198 let position = buffer_position.to_point(buffer);
199 let line_start = Point::new(position.row, 0);
200 let mut lines = buffer.text_for_range(line_start..position).lines();
201 let line = lines.next()?;
202 let call = SlashCommandLine::parse(line)?;
203
204 let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
205 let command_range_end = Point::new(
206 position.row,
207 call.argument.as_ref().map_or(call.name.end, |arg| arg.end) as u32,
208 );
209 let command_range = buffer.anchor_after(command_range_start)
210 ..buffer.anchor_after(command_range_end);
211
212 let name = line[call.name.clone()].to_string();
213
214 Some(if let Some(argument) = call.argument {
215 let start =
216 buffer.anchor_after(Point::new(position.row, argument.start as u32));
217 let argument = line[argument.clone()].to_string();
218 (name, Some(argument), command_range, start..buffer_position)
219 } else {
220 let start =
221 buffer.anchor_after(Point::new(position.row, call.name.start as u32));
222 (name, None, command_range, start..buffer_position)
223 })
224 })
225 else {
226 return Task::ready(Ok(Vec::new()));
227 };
228
229 if let Some(argument) = argument {
230 self.complete_command_argument(&name, argument, command_range, argument_range, cx)
231 } else {
232 self.complete_command_name(&name, command_range, argument_range, cx)
233 }
234 }
235
236 fn resolve_completions(
237 &self,
238 _: Model<Buffer>,
239 _: Vec<usize>,
240 _: Arc<RwLock<Box<[project::Completion]>>>,
241 _: &mut ViewContext<Editor>,
242 ) -> Task<Result<bool>> {
243 Task::ready(Ok(true))
244 }
245
246 fn apply_additional_edits_for_completion(
247 &self,
248 _: Model<Buffer>,
249 _: project::Completion,
250 _: bool,
251 _: &mut ViewContext<Editor>,
252 ) -> Task<Result<Option<language::Transaction>>> {
253 Task::ready(Ok(None))
254 }
255
256 fn is_completion_trigger(
257 &self,
258 buffer: &Model<Buffer>,
259 position: language::Anchor,
260 _text: &str,
261 _trigger_in_words: bool,
262 cx: &mut ViewContext<Editor>,
263 ) -> bool {
264 let buffer = buffer.read(cx);
265 let position = position.to_point(buffer);
266 let line_start = Point::new(position.row, 0);
267 let mut lines = buffer.text_for_range(line_start..position).lines();
268 if let Some(line) = lines.next() {
269 SlashCommandLine::parse(line).is_some()
270 } else {
271 false
272 }
273 }
274}
275
276impl SlashCommandLine {
277 pub(crate) fn parse(line: &str) -> Option<Self> {
278 let mut call: Option<Self> = None;
279 let mut ix = 0;
280 for c in line.chars() {
281 let next_ix = ix + c.len_utf8();
282 if let Some(call) = &mut call {
283 // The command arguments start at the first non-whitespace character
284 // after the command name, and continue until the end of the line.
285 if let Some(argument) = &mut call.argument {
286 if (*argument).is_empty() && c.is_whitespace() {
287 argument.start = next_ix;
288 }
289 argument.end = next_ix;
290 }
291 // The command name ends at the first whitespace character.
292 else if !call.name.is_empty() {
293 if c.is_whitespace() {
294 call.argument = Some(next_ix..next_ix);
295 } else {
296 call.name.end = next_ix;
297 }
298 }
299 // The command name must begin with a letter.
300 else if c.is_alphabetic() {
301 call.name.end = next_ix;
302 } else {
303 return None;
304 }
305 }
306 // Commands start with a slash.
307 else if c == '/' {
308 call = Some(SlashCommandLine {
309 name: next_ix..next_ix,
310 argument: None,
311 });
312 }
313 // The line can't contain anything before the slash except for whitespace.
314 else if !c.is_whitespace() {
315 return None;
316 }
317 ix = next_ix;
318 }
319 call
320 }
321}