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 let executor = cx.background_executor().clone();
77 executor.clone().spawn(async move {
78 let matches = match_strings(
79 &candidates,
80 &command_name,
81 true,
82 usize::MAX,
83 &Default::default(),
84 executor,
85 )
86 .await;
87
88 Ok(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: CodeLabel::plain(mat.string.clone(), None),
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 fn complete_command_argument(
131 &self,
132 command_name: &str,
133 argument: String,
134 command_range: Range<Anchor>,
135 argument_range: Range<Anchor>,
136 cx: &mut WindowContext,
137 ) -> Task<Result<Vec<project::Completion>>> {
138 let new_cancel_flag = Arc::new(AtomicBool::new(false));
139 let mut flag = self.cancel_flag.lock();
140 flag.store(true, SeqCst);
141 *flag = new_cancel_flag.clone();
142
143 if let Some(command) = self.commands.command(command_name) {
144 let completions = command.complete_argument(argument, new_cancel_flag.clone(), cx);
145 let command_name: Arc<str> = command_name.into();
146 let editor = self.editor.clone();
147 let workspace = self.workspace.clone();
148 cx.background_executor().spawn(async move {
149 Ok(completions
150 .await?
151 .into_iter()
152 .map(|arg| project::Completion {
153 old_range: argument_range.clone(),
154 label: CodeLabel::plain(arg.clone(), None),
155 new_text: arg.clone(),
156 documentation: None,
157 server_id: LanguageServerId(0),
158 lsp_completion: Default::default(),
159 confirm: Some(Arc::new({
160 let command_name = command_name.clone();
161 let command_range = command_range.clone();
162 let editor = editor.clone();
163 let workspace = workspace.clone();
164 move |cx| {
165 editor
166 .update(cx, |editor, cx| {
167 editor.run_command(
168 command_range.clone(),
169 &command_name,
170 Some(&arg),
171 workspace.clone(),
172 cx,
173 );
174 })
175 .ok();
176 }
177 })),
178 })
179 .collect())
180 })
181 } else {
182 cx.background_executor()
183 .spawn(async move { Ok(Vec::new()) })
184 }
185 }
186}
187
188impl CompletionProvider for SlashCommandCompletionProvider {
189 fn completions(
190 &self,
191 buffer: &Model<Buffer>,
192 buffer_position: Anchor,
193 cx: &mut ViewContext<Editor>,
194 ) -> Task<Result<Vec<project::Completion>>> {
195 let Some((name, argument, command_range, argument_range)) =
196 buffer.update(cx, |buffer, _cx| {
197 let position = buffer_position.to_point(buffer);
198 let line_start = Point::new(position.row, 0);
199 let mut lines = buffer.text_for_range(line_start..position).lines();
200 let line = lines.next()?;
201 let call = SlashCommandLine::parse(line)?;
202
203 let command_range_start = Point::new(position.row, call.name.start as u32 - 1);
204 let command_range_end = Point::new(
205 position.row,
206 call.argument.as_ref().map_or(call.name.end, |arg| arg.end) as u32,
207 );
208 let command_range = buffer.anchor_after(command_range_start)
209 ..buffer.anchor_after(command_range_end);
210
211 let name = line[call.name.clone()].to_string();
212
213 Some(if let Some(argument) = call.argument {
214 let start =
215 buffer.anchor_after(Point::new(position.row, argument.start as u32));
216 let argument = line[argument.clone()].to_string();
217 (name, Some(argument), command_range, start..buffer_position)
218 } else {
219 let start =
220 buffer.anchor_after(Point::new(position.row, call.name.start as u32));
221 (name, None, command_range, start..buffer_position)
222 })
223 })
224 else {
225 return Task::ready(Ok(Vec::new()));
226 };
227
228 if let Some(argument) = argument {
229 self.complete_command_argument(&name, argument, command_range, argument_range, cx)
230 } else {
231 self.complete_command_name(&name, command_range, argument_range, cx)
232 }
233 }
234
235 fn resolve_completions(
236 &self,
237 _: Model<Buffer>,
238 _: Vec<usize>,
239 _: Arc<RwLock<Box<[project::Completion]>>>,
240 _: &mut ViewContext<Editor>,
241 ) -> Task<Result<bool>> {
242 Task::ready(Ok(true))
243 }
244
245 fn apply_additional_edits_for_completion(
246 &self,
247 _: Model<Buffer>,
248 _: project::Completion,
249 _: bool,
250 _: &mut ViewContext<Editor>,
251 ) -> Task<Result<Option<language::Transaction>>> {
252 Task::ready(Ok(None))
253 }
254
255 fn is_completion_trigger(
256 &self,
257 buffer: &Model<Buffer>,
258 position: language::Anchor,
259 _text: &str,
260 _trigger_in_words: bool,
261 cx: &mut ViewContext<Editor>,
262 ) -> bool {
263 let buffer = buffer.read(cx);
264 let position = position.to_point(buffer);
265 let line_start = Point::new(position.row, 0);
266 let mut lines = buffer.text_for_range(line_start..position).lines();
267 if let Some(line) = lines.next() {
268 SlashCommandLine::parse(line).is_some()
269 } else {
270 false
271 }
272 }
273}
274
275impl SlashCommandLine {
276 pub(crate) fn parse(line: &str) -> Option<Self> {
277 let mut call: Option<Self> = None;
278 let mut ix = 0;
279 for c in line.chars() {
280 let next_ix = ix + c.len_utf8();
281 if let Some(call) = &mut call {
282 // The command arguments start at the first non-whitespace character
283 // after the command name, and continue until the end of the line.
284 if let Some(argument) = &mut call.argument {
285 if (*argument).is_empty() && c.is_whitespace() {
286 argument.start = next_ix;
287 }
288 argument.end = next_ix;
289 }
290 // The command name ends at the first whitespace character.
291 else if !call.name.is_empty() {
292 if c.is_whitespace() {
293 call.argument = Some(next_ix..next_ix);
294 } else {
295 call.name.end = next_ix;
296 }
297 }
298 // The command name must begin with a letter.
299 else if c.is_alphabetic() {
300 call.name.end = next_ix;
301 } else {
302 return None;
303 }
304 }
305 // Commands start with a slash.
306 else if c == '/' {
307 call = Some(SlashCommandLine {
308 name: next_ix..next_ix,
309 argument: None,
310 });
311 }
312 // The line can't contain anything before the slash except for whitespace.
313 else if !c.is_whitespace() {
314 return None;
315 }
316 ix = next_ix;
317 }
318 call
319 }
320}